muonium 0.2.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.
muonium/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ """muonium: a distributed-ready Muon optimizer built on PyTorch DTensor."""
2
+
3
+ from .optim import (
4
+ BufferSpec,
5
+ Muon,
6
+ MuonAlgorithm,
7
+ get_algorithm,
8
+ register_muon_algorithm,
9
+ registered_algorithms,
10
+ )
11
+ from .orthogonalize import OrthogonalizationStrategy
12
+
13
+ __all__ = [
14
+ "BufferSpec",
15
+ "Muon",
16
+ "MuonAlgorithm",
17
+ "OrthogonalizationStrategy",
18
+ "get_algorithm",
19
+ "register_muon_algorithm",
20
+ "registered_algorithms",
21
+ ]
22
+
23
+ try:
24
+ from .optim import MuonLP
25
+
26
+ __all__ += ["MuonLP"]
27
+ except ImportError:
28
+ pass
@@ -0,0 +1,3 @@
1
+ from .gram import gram_, gram
2
+
3
+ __all__ = ["gram", "gram_"]
@@ -0,0 +1,165 @@
1
+ import torch
2
+ import triton
3
+ import triton.language as tl
4
+
5
+
6
+ def get_autotune_config():
7
+ return [
8
+ triton.Config(
9
+ {"BLOCK_SIZE_M": blk_m, "BLOCK_SIZE_K": blk_k, "GROUP_SIZE_M": grp_sz},
10
+ num_stages=n_stages,
11
+ num_warps=n_warps,
12
+ )
13
+ for blk_m in [32, 64, 128]
14
+ for blk_k in [32, 64]
15
+ for grp_sz in [8]
16
+ for n_stages in [3, 4, 5]
17
+ for n_warps in [4, 8]
18
+ ]
19
+
20
+
21
+ @triton.autotune(
22
+ configs=get_autotune_config(),
23
+ key=["M", "K"],
24
+ )
25
+ @triton.jit
26
+ def gram_nd(
27
+ x,
28
+ y,
29
+ M,
30
+ K,
31
+ stride_xb,
32
+ stride_xm,
33
+ stride_xk,
34
+ stride_yb,
35
+ stride_ym,
36
+ stride_yn,
37
+ BLOCK_SIZE_M: tl.constexpr,
38
+ BLOCK_SIZE_K: tl.constexpr,
39
+ GROUP_SIZE_M: tl.constexpr,
40
+ ):
41
+ """
42
+ Computes (per batch): y[b] = x[b] @ x[b].T
43
+ where x has shape (B, M, K) and y has shape (B, M, M).
44
+
45
+ We only compute the upper triangle blocks and mirror them into the lower triangle.
46
+ """
47
+ # 2D launch grid:
48
+ pid = tl.program_id(axis=0) # tiles over (M, M)
49
+ pid_b = tl.program_id(axis=1) # batch index (flattened leading dims)
50
+
51
+ # Move base pointers to this batch
52
+ x = x + pid_b * stride_xb
53
+ y = y + pid_b * stride_yb
54
+
55
+ # --- same block mapping logic as your original kernel ---
56
+ num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
57
+ num_pid_n = tl.cdiv(M, BLOCK_SIZE_M)
58
+
59
+ num_pid_in_group = GROUP_SIZE_M * num_pid_n
60
+ group_id = pid // num_pid_in_group
61
+ first_pid_m = group_id * GROUP_SIZE_M
62
+ group_size_m = tl.minimum(num_pid_m - first_pid_m, GROUP_SIZE_M)
63
+
64
+ pid_m = first_pid_m + ((pid % num_pid_in_group) % group_size_m)
65
+ pid_n = (pid % num_pid_in_group) // group_size_m
66
+
67
+ # Only compute upper triangle (including diagonal)
68
+ if pid_m > pid_n:
69
+ return
70
+
71
+ offs_xm = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
72
+ offs_xn = (pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
73
+ offs_k = tl.arange(0, BLOCK_SIZE_K)
74
+
75
+ a_ptrs = x + (offs_xm[:, None] * stride_xm + offs_k[None, :] * stride_xk)
76
+ b_ptrs = x + (offs_xn[:, None] * stride_xm + offs_k[None, :] * stride_xk)
77
+
78
+ acc = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_M), dtype=tl.float32)
79
+
80
+ # K loop
81
+ for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
82
+ # mask only on K (M handled via %M wrap + store mask)
83
+ k_remaining = K - k * BLOCK_SIZE_K
84
+ a = tl.load(a_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
85
+ b = tl.load(b_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
86
+
87
+ # b^T via permute
88
+ acc = tl.dot(a, tl.permute(b, (1, 0)), acc)
89
+
90
+ a_ptrs += BLOCK_SIZE_K * stride_xk
91
+ b_ptrs += BLOCK_SIZE_K * stride_xk
92
+
93
+ c = acc.to(x.dtype.element_ty)
94
+
95
+ offs_cm = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
96
+ offs_cn = pid_n * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
97
+
98
+ c_ptrs = y + stride_ym * offs_cm[:, None] + stride_yn * offs_cn[None, :]
99
+ c_mask = (offs_cm[:, None] < M) & (offs_cn[None, :] < M)
100
+ tl.store(c_ptrs, c, mask=c_mask)
101
+
102
+ # transpose+copy to lower triangle block
103
+ if pid_m < pid_n:
104
+ ct_ptrs = y + stride_ym * offs_cn[:, None] + stride_yn * offs_cm[None, :]
105
+ ct_mask = (offs_cn[:, None] < M) & (offs_cm[None, :] < M)
106
+ tl.store(ct_ptrs, tl.permute(c, (1, 0)), mask=ct_mask)
107
+
108
+
109
+ def gram_(d_in: torch.Tensor, d_out: torch.Tensor) -> None:
110
+ """
111
+ d_in: (..., M, K)
112
+ d_out: (..., M, M)
113
+ """
114
+ assert d_in.is_cuda and d_out.is_cuda
115
+ assert d_in.device == d_out.device
116
+ assert d_in.dtype == d_out.dtype
117
+ assert d_in.ndim >= 2 and d_out.ndim >= 2
118
+ assert d_in.shape[:-2] == d_out.shape[:-2]
119
+
120
+ M, K = d_in.shape[-2], d_in.shape[-1]
121
+ assert d_out.shape[-2:] == (M, M)
122
+
123
+ # We need a view as (B, M, K) and (B, M, M). Output must be viewable (no copies).
124
+ # Input we can safely make contiguous (if it was transposed etc).
125
+ x = d_in.contiguous().view(-1, M, K)
126
+
127
+ # For correctness, don't allow reshape() to silently copy the output.
128
+ assert d_out.is_contiguous(), (
129
+ "d_out must be contiguous (or you must write into a contiguous temp and copy_ back)"
130
+ )
131
+ y = d_out.view(-1, M, M)
132
+
133
+ B = x.shape[0]
134
+
135
+ grid = lambda META: (
136
+ triton.cdiv(M, META["BLOCK_SIZE_M"]) * triton.cdiv(M, META["BLOCK_SIZE_M"]),
137
+ B,
138
+ )
139
+
140
+ with torch.cuda.device(d_in.device.index):
141
+ gram_nd[grid](
142
+ x,
143
+ y,
144
+ M,
145
+ K,
146
+ x.stride(0),
147
+ x.stride(1),
148
+ x.stride(2),
149
+ y.stride(0),
150
+ y.stride(1),
151
+ y.stride(2),
152
+ )
153
+
154
+
155
+ def gram(d_in: torch.Tensor) -> torch.Tensor:
156
+ """
157
+ Returns y = d_in @ d_in^T over the last 2 dims.
158
+ d_in: (..., M, K) -> y: (..., M, M)
159
+ """
160
+ assert d_in.ndim >= 2
161
+ M = d_in.size(-2)
162
+ out_shape = (*d_in.shape[:-2], M, M)
163
+ d_out = torch.empty(out_shape, device=d_in.device, dtype=d_in.dtype)
164
+ gram_(d_in, d_out)
165
+ return d_out
@@ -0,0 +1,26 @@
1
+ from .algorithms import (
2
+ BufferSpec,
3
+ MuonAlgorithm,
4
+ get_algorithm,
5
+ register_muon_algorithm,
6
+ registered_algorithms,
7
+ )
8
+ from .optim import Muon
9
+
10
+ __all__ = [
11
+ "BufferSpec",
12
+ "Muon",
13
+ "MuonAlgorithm",
14
+ "get_algorithm",
15
+ "register_muon_algorithm",
16
+ "registered_algorithms",
17
+ ]
18
+
19
+ try:
20
+ import torchao # noqa: F401 # ty: ignore[unresolved-import]
21
+
22
+ from .optim_lp import MuonLP
23
+
24
+ __all__ += ["MuonLP"]
25
+ except ImportError:
26
+ pass
@@ -0,0 +1,34 @@
1
+ """Pluggable Muon algorithm variants.
2
+
3
+ Selected per param group via ``{"params": ..., "algorithm": "<name>"}``. Register
4
+ your own variant by subclassing :class:`MuonAlgorithm` and decorating it with
5
+ :func:`register_muon_algorithm`.
6
+ """
7
+
8
+ from .base import (
9
+ BufferSpec,
10
+ MuonAlgorithm,
11
+ get_algorithm,
12
+ orthogonalize_batch,
13
+ orthogonalize_single,
14
+ register_muon_algorithm,
15
+ registered_algorithms,
16
+ split_lr_scales,
17
+ )
18
+
19
+ # Importing these modules registers the built-in algorithms.
20
+ from .muon import MuonBaseline
21
+ from .normuon import NorMuon
22
+
23
+ __all__ = [
24
+ "BufferSpec",
25
+ "MuonAlgorithm",
26
+ "MuonBaseline",
27
+ "NorMuon",
28
+ "get_algorithm",
29
+ "orthogonalize_batch",
30
+ "orthogonalize_single",
31
+ "register_muon_algorithm",
32
+ "registered_algorithms",
33
+ "split_lr_scales",
34
+ ]
@@ -0,0 +1,310 @@
1
+ # Base class, registry, and shared helpers for pluggable Muon algorithm variants.
2
+ import math
3
+ from abc import ABC, abstractmethod
4
+ from dataclasses import dataclass
5
+ from typing import Any, ClassVar, Literal, cast
6
+
7
+ import torch
8
+ from torch import Tensor
9
+ from torch.distributed.tensor import DTensor, Replicate
10
+
11
+ from muonium.orthogonalize import (
12
+ OrthogonalizationStrategy,
13
+ foreach_zeropower,
14
+ foreach_zeropower_3d_fsdp,
15
+ is_fsdp_3d_sharded,
16
+ zeropower,
17
+ )
18
+
19
+ # Group keys owned by the optimizer itself; algorithm options may not shadow them.
20
+ RESERVED_GROUP_KEYS = frozenset(
21
+ {
22
+ "params",
23
+ "algorithm",
24
+ "use_muon",
25
+ "lr",
26
+ "wd",
27
+ "use_cautious_wd",
28
+ "momentum",
29
+ "nesterov",
30
+ "ns_steps",
31
+ "orthogonalization_strategy",
32
+ "maximize",
33
+ "flatten",
34
+ "foreach",
35
+ "split_sizes",
36
+ }
37
+ )
38
+
39
+ # Algorithm names routed to the Adam path in Muon.__init__, never to this registry.
40
+ ADAM_ALGORITHMS = ("adam", "adamw")
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class BufferSpec:
45
+ """Shape/signedness declaration for one per-parameter state buffer.
46
+
47
+ ``like="grad"`` allocates an fp32 buffer shaped like the (possibly flattened)
48
+ gradient; ``like="grad_rows"`` shapes it like ``grad[..., :1]`` (one value per
49
+ row/neuron). ``signed`` is consumed by quantized-state optimizers (``MuonLP``).
50
+ """
51
+
52
+ like: Literal["grad", "grad_rows"]
53
+ signed: bool = True
54
+
55
+
56
+ def split_lr_scales(
57
+ shape: torch.Size | tuple[int, ...], split_sizes: tuple[int, ...]
58
+ ) -> tuple[float, ...]:
59
+ """Per-row-block LR corrections for a fused 2D weight split via ``split_sizes``.
60
+
61
+ The optimizer scales the whole update by the full matrix's cached
62
+ ``lr_ratio = sqrt(max(1, N/M))``. Each independently orthogonalized row block
63
+ should instead see the adjustment its own shape would receive as a separate
64
+ parameter, so each block is pre-scaled by ``ratio(block) / ratio(full)``.
65
+ """
66
+ rows, cols = shape[-2], shape[-1]
67
+ full_ratio = math.sqrt(max(1.0, rows / cols))
68
+ return tuple(
69
+ math.sqrt(max(1.0, block_rows / cols)) / full_ratio for block_rows in split_sizes
70
+ )
71
+
72
+
73
+ def _split_orthogonalize_full(
74
+ g: Tensor,
75
+ split_sizes: tuple[int, ...],
76
+ scales: tuple[float, ...],
77
+ *,
78
+ ns_steps: int,
79
+ strategy: OrthogonalizationStrategy,
80
+ ) -> Tensor:
81
+ """Orthogonalize row blocks of a regular (non-DTensor) 2D tensor independently.
82
+
83
+ Equal-height blocks (e.g. K and V of a fused QKV weight under GQA) share one
84
+ batched ``foreach_zeropower`` call, mirroring microsoft/dion.
85
+ """
86
+ blocks = list(g.split(list(split_sizes), dim=-2))
87
+
88
+ by_height: dict[int, list[int]] = {}
89
+ for i, block in enumerate(blocks):
90
+ by_height.setdefault(block.size(-2), []).append(i)
91
+
92
+ out: list[Tensor | None] = [None] * len(blocks)
93
+ for indices in by_height.values():
94
+ ortho = foreach_zeropower(
95
+ [blocks[i] for i in indices], steps=ns_steps, strategy=strategy
96
+ )
97
+ for i, u in zip(indices, ortho, strict=True):
98
+ out[i] = u * scales[i]
99
+ return torch.cat([u for u in out if u is not None], dim=-2)
100
+
101
+
102
+ def orthogonalize_single(
103
+ g: Tensor,
104
+ *,
105
+ ns_steps: int,
106
+ strategy: OrthogonalizationStrategy,
107
+ split_sizes: tuple[int, ...] | None = None,
108
+ ):
109
+ """Orthogonalize one tensor. DTensor handling lives inside ``zeropower``.
110
+
111
+ With ``split_sizes``, row blocks of a fused 2D weight are orthogonalized
112
+ independently and rescaled so the whole-matrix ``lr_ratio`` applied later
113
+ matches the per-block adjustment separate parameters would receive. DTensor
114
+ inputs take a full-tensor round trip (gather, per-block orthogonalize,
115
+ redistribute back to the original placements) so any sharding is supported.
116
+ """
117
+ if split_sizes is None:
118
+ return zeropower(g, steps=ns_steps, strategy=strategy)
119
+
120
+ scales = split_lr_scales(g.shape, split_sizes)
121
+ if isinstance(g, DTensor):
122
+ u = _split_orthogonalize_full(
123
+ g.full_tensor(), split_sizes, scales, ns_steps=ns_steps, strategy=strategy
124
+ )
125
+ u_replicated = DTensor.from_local(
126
+ u,
127
+ device_mesh=g.device_mesh,
128
+ placements=(Replicate(),) * g.device_mesh.ndim,
129
+ )
130
+ return u_replicated.redistribute(placements=g.placements, async_op=True)
131
+ return _split_orthogonalize_full(g, split_sizes, scales, ns_steps=ns_steps, strategy=strategy)
132
+
133
+
134
+ def orthogonalize_batch(
135
+ gs: list[Tensor],
136
+ *,
137
+ ns_steps: int,
138
+ strategy: OrthogonalizationStrategy,
139
+ split_sizes: tuple[int, ...] | None = None,
140
+ ) -> list[Tensor]:
141
+ """Orthogonalize a same-shape batch, preferring the FSDP local-shard fast path.
142
+
143
+ This is the one place algorithms touch distributed logic; variants call this
144
+ helper and stay placement-agnostic. ``split_sizes`` (2D fused weights only)
145
+ orthogonalizes row blocks independently; see :func:`orthogonalize_single`.
146
+ """
147
+ if split_sizes is not None:
148
+ if isinstance(gs[0], DTensor):
149
+ # Correctness path: per-tensor full-tensor round trips.
150
+ return [
151
+ orthogonalize_single(
152
+ g, ns_steps=ns_steps, strategy=strategy, split_sizes=split_sizes
153
+ )
154
+ for g in gs
155
+ ]
156
+ scales = split_lr_scales(gs[0].shape, split_sizes)
157
+ return [
158
+ _split_orthogonalize_full(
159
+ g, split_sizes, scales, ns_steps=ns_steps, strategy=strategy
160
+ )
161
+ for g in gs
162
+ ]
163
+ if is_fsdp_3d_sharded(gs):
164
+ return cast(
165
+ list[Tensor],
166
+ foreach_zeropower_3d_fsdp(gs, steps=ns_steps, strategy=strategy), # ty: ignore
167
+ )
168
+ return cast(list[Tensor], foreach_zeropower(gs, steps=ns_steps, strategy=strategy))
169
+
170
+
171
+ class MuonAlgorithm(ABC):
172
+ """A Muon-family update rule, selected per param group via ``"algorithm"``.
173
+
174
+ Subclasses own only the math. The optimizer classes own everything around it:
175
+ group building, state allocation (``state_spec``), batching, CPU offload, state
176
+ quantization, and torch.compile. Register subclasses with
177
+ :func:`register_muon_algorithm` and select them by name in a param-group dict.
178
+ """
179
+
180
+ name: ClassVar[str]
181
+ # Variant-specific hyperparameters and their defaults. Overridable per param
182
+ # group; resolved by ``Muon._build_muon_group`` and passed to ``update`` /
183
+ # ``foreach_update`` as keyword arguments.
184
+ options: ClassVar[dict[str, Any]] = {}
185
+ # Per-parameter state buffers (beyond the shared ``step`` / ``lr_ratio``).
186
+ state_spec: ClassVar[dict[str, BufferSpec]] = {
187
+ "momentum_buffer": BufferSpec(like="grad", signed=True),
188
+ }
189
+
190
+ def validate_param(self, p: Tensor) -> None:
191
+ """Reject parameters this algorithm cannot handle (called at group build)."""
192
+ if p.ndim < 2:
193
+ raise ValueError(
194
+ "Muon only supports 2D+ parameters; found a 1D tensor in a Muon group"
195
+ )
196
+ if torch.is_complex(p):
197
+ raise NotImplementedError(
198
+ "Complex parameters are not supported in Muon. Add these parameters "
199
+ "to the Adam group or use a different optimizer."
200
+ )
201
+
202
+ @abstractmethod
203
+ def update(
204
+ self,
205
+ param: Tensor,
206
+ grad: Tensor,
207
+ state: dict[str, Tensor],
208
+ lr_ratio: Tensor,
209
+ *,
210
+ lr: Tensor,
211
+ weight_decay: float,
212
+ cautious_wd: bool,
213
+ momentum: float,
214
+ nesterov: bool,
215
+ maximize: bool,
216
+ ns_steps: int,
217
+ orthogonalization_strategy: OrthogonalizationStrategy,
218
+ split_sizes: tuple[int, ...] | None,
219
+ **opts,
220
+ ) -> None:
221
+ """Per-tensor fp32 reference update; mutates ``param`` and ``state`` in place.
222
+
223
+ Keep compiled math out-of-place until copying back into state (see the
224
+ aliasing note in ``MuonBaseline.update``).
225
+ """
226
+
227
+ def foreach_update(
228
+ self,
229
+ params: list[Tensor],
230
+ grads: list[Tensor],
231
+ state: dict[str, list[Tensor]],
232
+ lr_ratios: list[Tensor],
233
+ *,
234
+ lr: Tensor,
235
+ weight_decay: float,
236
+ cautious_wd: bool,
237
+ momentum: float,
238
+ nesterov: bool,
239
+ maximize: bool,
240
+ ns_steps: int,
241
+ orthogonalization_strategy: OrthogonalizationStrategy,
242
+ split_sizes: tuple[int, ...] | None,
243
+ **opts,
244
+ ) -> None:
245
+ """Batched update over same-(device, dtype, shape) tensors.
246
+
247
+ Default falls back to the per-tensor reference; override with
248
+ ``torch._foreach_*`` ops for performance.
249
+ """
250
+ for i, (param, grad, lr_ratio) in enumerate(
251
+ zip(params, grads, lr_ratios, strict=True)
252
+ ):
253
+ self.update(
254
+ param,
255
+ grad,
256
+ {key: buffers[i] for key, buffers in state.items()},
257
+ lr_ratio,
258
+ lr=lr,
259
+ weight_decay=weight_decay,
260
+ cautious_wd=cautious_wd,
261
+ momentum=momentum,
262
+ nesterov=nesterov,
263
+ maximize=maximize,
264
+ ns_steps=ns_steps,
265
+ orthogonalization_strategy=orthogonalization_strategy,
266
+ split_sizes=split_sizes,
267
+ **opts,
268
+ )
269
+
270
+
271
+ _REGISTRY: dict[str, MuonAlgorithm] = {}
272
+
273
+
274
+ def register_muon_algorithm(cls: type[MuonAlgorithm]) -> type[MuonAlgorithm]:
275
+ """Register a :class:`MuonAlgorithm` subclass under ``cls.name``.
276
+
277
+ Usable as a class decorator. Third-party packages can register their own
278
+ variants and select them via ``{"params": ..., "algorithm": "<name>"}``.
279
+ """
280
+ name = getattr(cls, "name", None)
281
+ if not isinstance(name, str) or not name:
282
+ raise ValueError(f"{cls.__qualname__} must define a non-empty string `name`")
283
+ name = name.lower()
284
+ if name in ADAM_ALGORITHMS:
285
+ raise ValueError(f"'{name}' is reserved for the Adam path")
286
+ if name in _REGISTRY and type(_REGISTRY[name]).__qualname__ != cls.__qualname__:
287
+ raise ValueError(f"Muon algorithm '{name}' is already registered")
288
+ shadowed = RESERVED_GROUP_KEYS.intersection(cls.options)
289
+ if shadowed:
290
+ raise ValueError(
291
+ f"{cls.__qualname__}.options shadow reserved group keys: {sorted(shadowed)}"
292
+ )
293
+ _REGISTRY[name] = cls()
294
+ return cls
295
+
296
+
297
+ def get_algorithm(name: str) -> MuonAlgorithm:
298
+ """Look up a registered algorithm by name (case-insensitive)."""
299
+ try:
300
+ return _REGISTRY[name.lower()]
301
+ except KeyError:
302
+ raise ValueError(
303
+ f"Unknown algorithm '{name}'. Registered Muon algorithms: "
304
+ f"{sorted(_REGISTRY)}; 'adam' and 'adamw' select the Adam path."
305
+ ) from None
306
+
307
+
308
+ def registered_algorithms() -> tuple[str, ...]:
309
+ """Names of all registered Muon algorithms (excludes 'adam'/'adamw')."""
310
+ return tuple(sorted(_REGISTRY))