raglu 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.
raglu/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """RaGLU: Pure Rational GLU ve RaLU aktivasyonları.
2
+
3
+ PyTorch (CPU/CUDA/MPS), isteğe bağlı Triton CUDA çekirdekleri ve Apple MLX
4
+ desteği sunar.
5
+ """
6
+
7
+ from .core import (
8
+ HAS_MLX,
9
+ HAS_TRITON,
10
+ fused_pure_rational,
11
+ fused_pure_rational_glu,
12
+ )
13
+ from .torch_module import RaGLU, RaLU
14
+
15
+ if HAS_MLX:
16
+ from .core import mlx_pure_rational, mlx_pure_rational_glu
17
+
18
+ __version__ = "0.1.0"
19
+
20
+ __all__ = [
21
+ "fused_pure_rational_glu",
22
+ "fused_pure_rational",
23
+ "RaGLU",
24
+ "RaLU",
25
+ "HAS_TRITON",
26
+ "HAS_MLX",
27
+ "__version__",
28
+ ]
29
+
30
+ if HAS_MLX:
31
+ __all__ += ["mlx_pure_rational_glu", "mlx_pure_rational"]
raglu/core.py ADDED
@@ -0,0 +1,116 @@
1
+ import torch
2
+
3
+ # Triton ve CUDA kontrolü
4
+ HAS_TRITON = False
5
+ if torch.cuda.is_available():
6
+ try:
7
+ import triton
8
+ import triton.language as tl
9
+ HAS_TRITON = True
10
+ except ImportError:
11
+ HAS_TRITON = False
12
+
13
+ # MLX kontrolü (Apple Silicon / Mac desteği için)
14
+ HAS_MLX = False
15
+ try:
16
+ import mlx.core as mx
17
+ import mlx.nn as mx_nn
18
+ HAS_MLX = True
19
+ except ImportError:
20
+ HAS_MLX = False
21
+
22
+
23
+ # ==============================================================================
24
+ # 1. TRITON KERNELS (NVIDIA CUDA OPTİMİZE)
25
+ # ==============================================================================
26
+ if HAS_TRITON:
27
+ @triton.jit
28
+ def _pure_rational_glu_fwd_kernel(gate_ptr, val_ptr, out_ptr, n_elements, BLOCK_SIZE: tl.constexpr):
29
+ pid = tl.program_id(axis=0)
30
+ offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
31
+ mask = offsets < n_elements
32
+
33
+ g = tl.load(gate_ptr + offsets, mask=mask)
34
+ v = tl.load(val_ptr + offsets, mask=mask)
35
+
36
+ g = tl.clamp(g, -50.0, 50.0)
37
+ g_sq = g * g
38
+ fg = (g * g_sq + g) / (g_sq + 3.0)
39
+ tl.store(out_ptr + offsets, fg * v, mask=mask)
40
+
41
+ @triton.jit
42
+ def _pure_rational_glu_bwd_kernel(dy_ptr, gate_ptr, val_ptr, dg_ptr, dv_ptr, n_elements, BLOCK_SIZE: tl.constexpr):
43
+ pid = tl.program_id(axis=0)
44
+ offsets = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
45
+ mask = offsets < n_elements
46
+
47
+ dy = tl.load(dy_ptr + offsets, mask=mask)
48
+ g = tl.load(gate_ptr + offsets, mask=mask)
49
+ v = tl.load(val_ptr + offsets, mask=mask)
50
+
51
+ g = tl.clamp(g, -50.0, 50.0)
52
+ g_sq = g * g
53
+ denom = g_sq + 3.0
54
+
55
+ fg = (g * g_sq + g) / denom
56
+ dv = dy * fg
57
+ dfg = (g_sq * g_sq + 8.0 * g_sq + 3.0) / (denom * denom)
58
+ dg = dy * v * dfg
59
+
60
+ tl.store(dv_ptr + offsets, dv, mask=mask)
61
+ tl.store(dg_ptr + offsets, dg, mask=mask)
62
+
63
+ class FusedPureRationalGLUFunction(torch.autograd.Function):
64
+ @staticmethod
65
+ def forward(ctx, gate, val):
66
+ gate_c, val_c = gate.contiguous(), val.contiguous()
67
+ n_elements = gate_c.numel()
68
+ out = torch.empty_like(gate_c)
69
+ GRID = lambda meta: (triton.cdiv(n_elements, meta['BLOCK_SIZE']),)
70
+ _pure_rational_glu_fwd_kernel[GRID](gate_c, val_c, out, n_elements, BLOCK_SIZE=1024)
71
+ ctx.save_for_backward(gate_c, val_c)
72
+ return out
73
+
74
+ @staticmethod
75
+ def backward(ctx, dy):
76
+ gate, val = ctx.saved_tensors
77
+ dy_c = dy.contiguous()
78
+ n_elements = gate.numel()
79
+ dgate, dval = torch.empty_like(gate), torch.empty_like(val)
80
+ GRID = lambda meta: (triton.cdiv(n_elements, meta['BLOCK_SIZE']),)
81
+ _pure_rational_glu_bwd_kernel[GRID](dy_c, gate, val, dgate, dval, n_elements, BLOCK_SIZE=1024)
82
+ return dgate, dval
83
+
84
+
85
+ # ==============================================================================
86
+ # 2. PYTORCH API (CUDA + MPS/Mac + CPU FALLBACK)
87
+ # ==============================================================================
88
+ def fused_pure_rational_glu(gate: torch.Tensor, val: torch.Tensor) -> torch.Tensor:
89
+ """Pure Rational GLU Function: f(g) = (g^3 + g) / (g^2 + 3) * v"""
90
+ if HAS_TRITON and gate.is_cuda:
91
+ return FusedPureRationalGLUFunction.apply(gate, val)
92
+ else:
93
+ # PyTorch Native Fallback (MPS, CPU veya Triton bulunmayan ortamlar)
94
+ g_sq = gate * gate
95
+ fg = (gate * g_sq + gate) / (g_sq + 3.0)
96
+ return fg * val
97
+
98
+
99
+ def fused_pure_rational(x: torch.Tensor) -> torch.Tensor:
100
+ """RaLU (Non-GLU Pure Rational): f(x) = (x^3 + x) / (x^2 + 3)"""
101
+ x_sq = x * x
102
+ return (x * x_sq + x) / (x_sq + 3.0)
103
+
104
+
105
+ # ==============================================================================
106
+ # 3. APPLE MLX NATIVE DESTEĞİ
107
+ # ==============================================================================
108
+ if HAS_MLX:
109
+ def mlx_pure_rational_glu(gate: mx.array, val: mx.array) -> mx.array:
110
+ g_sq = mx.square(gate)
111
+ fg = (gate * g_sq + gate) / (g_sq + 3.0)
112
+ return fg * val
113
+
114
+ def mlx_pure_rational(x: mx.array) -> mx.array:
115
+ x_sq = mx.square(x)
116
+ return (x * x_sq + x) / (x_sq + 3.0)
raglu/py.typed ADDED
File without changes
raglu/torch_module.py ADDED
@@ -0,0 +1,121 @@
1
+ """PyTorch ``nn.Module`` katman sarmalayıcıları.
2
+
3
+ ``RaGLU`` gated (kapılı) doğrusal katmanı, ``RaLU`` ise kapısız
4
+ element-wise aktivasyonu sağlar.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from torch import Tensor, nn
10
+
11
+ from .core import fused_pure_rational, fused_pure_rational_glu
12
+
13
+ __all__ = ["RaGLU", "RaLU"]
14
+
15
+
16
+ class RaGLU(nn.Module):
17
+ """Pure Rational GLU katmanı.
18
+
19
+ İki kullanım biçimi vardır:
20
+
21
+ 1. Yerleşik doğrusal katman (önerilen)::
22
+
23
+ layer = RaGLU(in_features=768, out_features=768)
24
+ y = layer(x) # x: (..., 768) -> y: (..., 768)
25
+
26
+ Girdi, tek bir doğrusal katmanla ``2 * out_features`` boyutuna
27
+ genişletilir ve ikiye bölünür. İlk yarı kapı (``gate``), ikinci yarı
28
+ değer (``val``) olarak kullanılır.
29
+
30
+ 2. Hazır ``gate`` ve ``val`` modülleri ile::
31
+
32
+ layer = RaGLU(gate=nn.Linear(768, 1024), val=nn.Linear(768, 1024))
33
+ y = layer(x)
34
+
35
+ Args:
36
+ in_features: Girdi özellik sayısı (yerleşik modda zorunludur).
37
+ out_features: Çıktı özellik sayısı. Varsayılan olarak ``in_features``.
38
+ bias: Yerleşik doğrusal katmanda bias kullanılıp kullanılmayacağı.
39
+ gate: Hazır kapı modülü. Verilirse ``val`` da verilmelidir.
40
+ val: Hazır değer modülü. Verilirse ``gate`` de verilmelidir.
41
+
42
+ Girdi ve çıktı şekilleri aynı son boyuta sahip olmalıdır: ``gate`` ve
43
+ ``val`` çıktıları eşleşmezse hata verilir.
44
+ """
45
+
46
+ def __init__(
47
+ self,
48
+ in_features: int | None = None,
49
+ out_features: int | None = None,
50
+ bias: bool = True,
51
+ gate: nn.Module | None = None,
52
+ val: nn.Module | None = None,
53
+ ) -> None:
54
+ super().__init__()
55
+
56
+ self.in_features: int | None = in_features
57
+ self.out_features: int | None = out_features
58
+
59
+ if gate is not None or val is not None:
60
+ if gate is None or val is None:
61
+ raise ValueError("'gate' ve 'val' birlikte verilmelidir.")
62
+ if in_features is not None or out_features is not None:
63
+ raise ValueError(
64
+ "Hazır 'gate'/'val' modülleriyle 'in_features'/'out_features' birlikte kullanılamaz."
65
+ )
66
+ self.linear = None
67
+ self.gate = gate
68
+ self.val = val
69
+ else:
70
+ if in_features is None:
71
+ raise ValueError("'in_features' veya hem 'gate' hem 'val' verilmelidir.")
72
+ if out_features is None:
73
+ out_features = in_features
74
+ self.in_features = in_features
75
+ self.out_features = out_features
76
+
77
+ # Tek matmul ile gate ve val üretimi (GLU standardı).
78
+ self.linear: nn.Linear | None = nn.Linear(
79
+ in_features, 2 * out_features, bias=bias
80
+ )
81
+ self.gate = None
82
+ self.val = None
83
+
84
+ def forward(self, x: Tensor) -> Tensor:
85
+ """``x`` üzerinde Pure Rational GLU uygular."""
86
+ if self.linear is not None:
87
+ gate, val = self.linear(x).chunk(2, dim=-1)
88
+ else:
89
+ gate = self.gate(x)
90
+ val = self.val(x)
91
+ if gate.shape != val.shape:
92
+ raise ValueError(
93
+ f"'gate' ve 'val' çıktı şekilleri eşleşmiyor: "
94
+ f"{tuple(gate.shape)} != {tuple(val.shape)}"
95
+ )
96
+
97
+ return fused_pure_rational_glu(gate, val)
98
+
99
+ def extra_repr(self) -> str:
100
+ if self.linear is not None:
101
+ return (
102
+ f"in_features={self.in_features}, out_features={self.out_features}, "
103
+ f"bias={self.linear.bias is not None}"
104
+ )
105
+ return "gate=<custom>, val=<custom>"
106
+
107
+
108
+ class RaLU(nn.Module):
109
+ """Kapısız Pure Rational aktivasyonu.
110
+
111
+ ``f(x) = (x^3 + x) / (x^2 + 3)``
112
+
113
+ Şekil değiştirmez; tüm tensörlerde (``float16``/``bfloat16``/``float32``)
114
+ ve cihazlarda (CPU/CUDA/MPS) çalışır.
115
+ """
116
+
117
+ def forward(self, x: Tensor) -> Tensor:
118
+ return fused_pure_rational(x)
119
+
120
+ def extra_repr(self) -> str:
121
+ return "inplace=False"
@@ -0,0 +1,192 @@
1
+ Metadata-Version: 2.4
2
+ Name: raglu
3
+ Version: 0.1.0
4
+ Summary: Pure Rational GLU (RaGLU) and RaLU activations for PyTorch, Triton CUDA and Apple MLX.
5
+ Author: Ömer Faruk Solmaz
6
+ License-Expression: MIT
7
+ Keywords: activation,glu,ralu,rational,pytorch,triton,mlx,deep-learning
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Classifier: Typing :: Typed
20
+ Requires-Python: >=3.9
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Requires-Dist: torch>=2.0.0
24
+ Provides-Extra: triton
25
+ Requires-Dist: triton>=2.0.0; extra == "triton"
26
+ Provides-Extra: mlx
27
+ Requires-Dist: mlx>=0.1.0; extra == "mlx"
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
30
+ Requires-Dist: build>=1.0.0; extra == "dev"
31
+ Requires-Dist: twine>=4.0.0; extra == "dev"
32
+ Dynamic: license-file
33
+
34
+ # RaGLU
35
+
36
+ **Pure Rational GLU (RaGLU)** ve **RaLU** aktivasyon fonksiyonları için platform
37
+ bağımsız PyTorch kütüphanesi. NVIDIA CUDA'da isteğe bağlı **Triton** çekirdekleri,
38
+ Apple Silicon'da ise yerel **MLX** desteği sunar.
39
+
40
+ Paket iki `nn.Module` sınıfı sunar:
41
+
42
+ | Sınıf | Görevi |
43
+ | --- | --- |
44
+ | `RaGLU()` | Kapılı (GLU) katman: `Linear` çıktısını gate/val olarak ikiye böler, `f(g) * v` uygular. |
45
+ | `RaLU()` | Kapısız, element-wise aktivasyon: `f(x)` uygular, şekli değiştirmez. |
46
+
47
+ ## Fonksiyonlar
48
+
49
+ Kapılı (gated) varyant:
50
+
51
+ $$
52
+ \operatorname{RaGLU}(g, v) = \frac{g^3 + g}{g^2 + 3} \cdot v
53
+ $$
54
+
55
+ Kapısız varyant:
56
+
57
+ $$
58
+ \operatorname{RaLU}(x) = \frac{x^3 + x}{x^2 + 3}
59
+ $$
60
+
61
+ Türev (her iki varyantın çekirdeği):
62
+
63
+ $$
64
+ \frac{d}{dx}\left(\frac{x^3 + x}{x^2 + 3}\right)
65
+ = \frac{x^4 + 8x^2 + 3}{(x^2 + 3)^2}
66
+ $$
67
+
68
+ Fonksiyon tek (odd) bir fonksiyondur: `f(-x) = -f(x)`. Payda her zaman
69
+ `>= 3` olduğundan sayısal olarak kararlıdır.
70
+
71
+ ## Kurulum
72
+
73
+ ```bash
74
+ pip install raglu
75
+ ```
76
+
77
+ İsteğe bağlı hızlandırıcılar:
78
+
79
+ ```bash
80
+ pip install "raglu[triton]" # NVIDIA CUDA için Triton çekirdekleri
81
+ pip install "raglu[mlx]" # Apple Silicon için MLX
82
+ pip install "raglu[dev]" # test + derleme araçları
83
+ ```
84
+
85
+ ## Kullanım
86
+
87
+ ### Fonksiyonel PyTorch API
88
+
89
+ ```python
90
+ import torch
91
+ from raglu import fused_pure_rational_glu, fused_pure_rational
92
+
93
+ gate = torch.randn(32, 128)
94
+ val = torch.randn(32, 128)
95
+
96
+ y = fused_pure_rational_glu(gate, val) # (32, 128)
97
+ z = fused_pure_rational(gate) # (32, 128)
98
+ ```
99
+
100
+ `fused_pure_rational_glu`, CUDA + Triton mevcutsa füzyonlu çekirdeği kullanır.
101
+ Aksi halde otomatik olarak CPU/MPS uyumlu PyTorch fallback'ine döner.
102
+ Her iki yol da autograd desteklidir.
103
+
104
+ ### Katmanlar
105
+
106
+ ```python
107
+ import torch
108
+ from raglu import RaGLU, RaLU
109
+
110
+ # Girdiyi 2 * out_features boyutuna genişletip gate/val olarak böler.
111
+ layer = RaGLU(in_features=768, out_features=768)
112
+ x = torch.randn(8, 128, 768)
113
+ y = layer(x) # (8, 128, 768)
114
+
115
+ # Kapısız aktivasyon
116
+ act = RaLU()
117
+ z = act(x) # (8, 128, 768)
118
+ ```
119
+
120
+ Hazır `gate` ve `val` modülleri de kullanılabilir:
121
+
122
+ ```python
123
+ from torch import nn
124
+ from raglu import RaGLU
125
+
126
+ layer = RaGLU(
127
+ gate=nn.Linear(768, 1024),
128
+ val=nn.Linear(768, 1024),
129
+ )
130
+ ```
131
+
132
+ ### Apple MLX
133
+
134
+ ```python
135
+ import mlx.core as mx
136
+ from raglu import mlx_pure_rational_glu, mlx_pure_rational
137
+
138
+ gate = mx.random.normal((32, 128))
139
+ val = mx.random.normal((32, 128))
140
+
141
+ y = mlx_pure_rational_glu(gate, val)
142
+ z = mlx_pure_rational(gate)
143
+ ```
144
+
145
+ MLX kurulu değilse bu semboller dışa aktarılmaz; `raglu.HAS_MLX` ile kontrol
146
+ edebilirsiniz.
147
+
148
+ ## API
149
+
150
+ | Sembol | Açıklama |
151
+ | --- | --- |
152
+ | `raglu.fused_pure_rational_glu(gate, val)` | Kapılı Pure Rational GLU (Triton/CUDA veya PyTorch fallback) |
153
+ | `raglu.fused_pure_rational(x)` | Kapısız RaLU aktivasyonu |
154
+ | `raglu.RaGLU` | Doğrusal katman + Pure Rational GLU `nn.Module`'ü |
155
+ | `raglu.RaLU` | Element-wise RaLU `nn.Module`'ü |
156
+ | `raglu.mlx_pure_rational_glu` | MLX kapılı varyant (MLX varsa) |
157
+ | `raglu.mlx_pure_rational` | MLX kapısız varyant (MLX varsa) |
158
+ | `raglu.HAS_TRITON` | Triton çekirdeklerinin kullanılabilirliği |
159
+ | `raglu.HAS_MLX` | MLX'in kullanılabilirliği |
160
+
161
+ ### Not: CUDA clamp
162
+
163
+ Triton çekirdekleri sayısal kararlılık için kapı değerini `[-50, 50]` aralığına
164
+ kırpar. Bu aralığın dışındaki değerlerde Triton ve fallback çıktıları
165
+ farklılaşabilir; pratik aktivasyon girdilerinde fark yoktur.
166
+
167
+ ## Geliştirme
168
+
169
+ ```bash
170
+ git clone <repo-url>
171
+ cd RaGLU
172
+ python -m venv .venv
173
+ source .venv/bin/activate
174
+ pip install -e ".[dev]"
175
+ pytest -v
176
+ ```
177
+
178
+ Triton testleri yalnızca CUDA + Triton mevcut olduğunda, MLX testleri ise
179
+ yalnızca MLX kurulu olduğunda çalışır; diğer ortamlarda otomatik atlanır.
180
+
181
+ ### Paket derleme
182
+
183
+ ```bash
184
+ python -m build
185
+ python -m twine check dist/*
186
+ ```
187
+
188
+ ## Lisans
189
+
190
+ MIT — bkz. [LICENSE](LICENSE).
191
+
192
+ Copyright (c) 2026 Ömer Faruk Solmaz
@@ -0,0 +1,9 @@
1
+ raglu/__init__.py,sha256=FcWZq1XN-i9cKo4Qz9d-64b1pf3ttEYFgCkzI5Vl1p4,621
2
+ raglu/core.py,sha256=sFj_zzAnjKsKOjPaJjaJN9wB8IiD4LrhLkFFIS_dkx4,4248
3
+ raglu/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ raglu/torch_module.py,sha256=nr4SIS86Biccogm3V449romNv4fZtvJ__B2L5rVXsTc,4129
5
+ raglu-0.1.0.dist-info/licenses/LICENSE,sha256=k1JAVRiTnpXhVIXp5swyTlFdBYUEQ2yDVMF4_9ew8zY,1075
6
+ raglu-0.1.0.dist-info/METADATA,sha256=qEozdnyk3KZ0M-d9PoPyfg97PgenrNnOtEAkdRBExNk,5187
7
+ raglu-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ raglu-0.1.0.dist-info/top_level.txt,sha256=f2EdUXjqFV1EtaIUCQ8lQgZ4d9ewf5QJKy_jB7UzlTI,6
9
+ raglu-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ömer Faruk Solmaz
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, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ raglu