socket-lm 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.
- socket_lm-0.1.0.dist-info/METADATA +199 -0
- socket_lm-0.1.0.dist-info/RECORD +43 -0
- socket_lm-0.1.0.dist-info/WHEEL +5 -0
- socket_lm-0.1.0.dist-info/licenses/LICENSE +21 -0
- socket_lm-0.1.0.dist-info/top_level.txt +1 -0
- socketimport/__init__.py +161 -0
- socketimport/config.py +103 -0
- socketimport/core/__init__.py +42 -0
- socketimport/core/accelerator.py +89 -0
- socketimport/core/attention.py +51 -0
- socketimport/core/base.py +87 -0
- socketimport/core/galore.py +308 -0
- socketimport/core/lite_ladder.py +330 -0
- socketimport/core/lora.py +394 -0
- socketimport/core/model_loader.py +86 -0
- socketimport/core/quantization.py +93 -0
- socketimport/core/reft.py +300 -0
- socketimport/data/__init__.py +3 -0
- socketimport/data/loader.py +65 -0
- socketimport/deps.py +67 -0
- socketimport/device.py +172 -0
- socketimport/distributed/__init__.py +131 -0
- socketimport/errors.py +247 -0
- socketimport/memory/__init__.py +17 -0
- socketimport/memory/batch_finder.py +109 -0
- socketimport/memory/checkpointing.py +78 -0
- socketimport/memory/tracker.py +85 -0
- socketimport/optim/__init__.py +19 -0
- socketimport/optim/ema.py +69 -0
- socketimport/optim/fused.py +56 -0
- socketimport/optim/lion.py +68 -0
- socketimport/optim/scheduler.py +83 -0
- socketimport/optim/swa.py +63 -0
- socketimport/profiler/__init__.py +4 -0
- socketimport/profiler/benchmark.py +87 -0
- socketimport/profiler/trace.py +43 -0
- socketimport/training/__init__.py +25 -0
- socketimport/training/callbacks.py +102 -0
- socketimport/training/framework_adapter.py +89 -0
- socketimport/training/oom_recovery.py +109 -0
- socketimport/training/trainer.py +194 -0
- socketimport/training/vram_guard.py +125 -0
- socketimport/utils.py +63 -0
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: socket-lm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A training-speed-focused LoRA/PEFT library offering four parameter-efficient fine-tuning methods (LoRA, ReFT, LiteLadder, GaLore)
|
|
5
|
+
Author: Omur Bera Isik
|
|
6
|
+
License: MIT License
|
|
7
|
+
|
|
8
|
+
Copyright (c) 2026 Ömür Bera Işık
|
|
9
|
+
|
|
10
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
11
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
12
|
+
in the Software without restriction, including without limitation the rights
|
|
13
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
14
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
15
|
+
furnished to do so, subject to the following conditions:
|
|
16
|
+
|
|
17
|
+
The above copyright notice and this permission notice shall be included in all
|
|
18
|
+
copies or substantial portions of the Software.
|
|
19
|
+
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
21
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
25
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
26
|
+
SOFTWARE.
|
|
27
|
+
|
|
28
|
+
Keywords: lora,peft,fine-tuning,pytorch,llm,deep-learning
|
|
29
|
+
Classifier: Development Status :: 3 - Alpha
|
|
30
|
+
Classifier: Intended Audience :: Science/Research
|
|
31
|
+
Classifier: Intended Audience :: Developers
|
|
32
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
33
|
+
Classifier: Programming Language :: Python :: 3
|
|
34
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
35
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
36
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
38
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
39
|
+
Requires-Python: >=3.9
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
License-File: LICENSE
|
|
42
|
+
Requires-Dist: torch>=2.0
|
|
43
|
+
Provides-Extra: quantization
|
|
44
|
+
Requires-Dist: bitsandbytes>=0.41.0; extra == "quantization"
|
|
45
|
+
Provides-Extra: dev
|
|
46
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
47
|
+
Requires-Dist: bitsandbytes>=0.41.0; extra == "dev"
|
|
48
|
+
Dynamic: license-file
|
|
49
|
+
|
|
50
|
+
# Socket
|
|
51
|
+
|
|
52
|
+
A LoRA/PEFT library focused on training speed. Offers four different parameter-efficient
|
|
53
|
+
fine-tuning methods — all written from scratch with no dependency on external PEFT libraries
|
|
54
|
+
(`peft` etc.).
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install socket
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
> **Important:** PyPI package name is `socket`, but to avoid clashing with Python's built-in `socket`
|
|
61
|
+
> (networking) module, **the import name is `socketimport`**:
|
|
62
|
+
> ```python
|
|
63
|
+
> import socketimport as sk
|
|
64
|
+
> ```
|
|
65
|
+
|
|
66
|
+
## Methods
|
|
67
|
+
|
|
68
|
+
| Method | What it does | Status |
|
|
69
|
+
|---|---|---|
|
|
70
|
+
| **LoRA** (+ rsLoRA, DoRA) | Low-rank addition to weights: `W + (α/r)·BA` | Mature, tested |
|
|
71
|
+
| **ReFT** (LoReFT) | Intervenes in hidden representations, not weights | Mature, tested |
|
|
72
|
+
| **LiteLadder** | Trains a separate "side network" with no backprop to backbone | **Experimental** — validated at small scale, not yet tested with real language data |
|
|
73
|
+
| **GaLore** | Full-parameter training with low-rank gradient projection to reduce optimizer memory | Mature, tested |
|
|
74
|
+
|
|
75
|
+
When to use each method differs: LoRA/ReFT/LiteLadder reduce parameter count (adapter-based),
|
|
76
|
+
while GaLore allows **full-parameter** training but only reduces optimizer memory — they are not
|
|
77
|
+
interchangeable, but complementary tools.
|
|
78
|
+
|
|
79
|
+
## Quick Start
|
|
80
|
+
|
|
81
|
+
### LoRA
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
import torch
|
|
85
|
+
from socketimport import LoRAAdapter, LoRAConfig
|
|
86
|
+
|
|
87
|
+
model = ... # any nn.Module (e.g., a Llama model)
|
|
88
|
+
config = LoRAConfig(r=16, alpha=32, use_rslora=True, dropout=0.05)
|
|
89
|
+
adapter = LoRAAdapter(model, config)
|
|
90
|
+
|
|
91
|
+
optimizer = torch.optim.AdamW(adapter.trainable_parameters(), lr=1e-4)
|
|
92
|
+
# ... normal training loop, forward with adapter(x) ...
|
|
93
|
+
|
|
94
|
+
adapter.merge() # zero-overhead embedding for inference
|
|
95
|
+
saved = adapter.adapter_state_dict() # only LoRA weights (KB not MB)
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Config parameters accept alternative names
|
|
99
|
+
(`rank`, `lora_r`, `lora_alpha`, `dora`, `rslora` etc.) — if conflicting values
|
|
100
|
+
are provided, an error is raised, not silently chosen.
|
|
101
|
+
|
|
102
|
+
### ReFT
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from socketimport import ReFTAdapter, ReFTConfig
|
|
106
|
+
|
|
107
|
+
# `layers` must be provided explicitly - Socket does not attempt to guess model architecture
|
|
108
|
+
adapter = ReFTAdapter(
|
|
109
|
+
model, layers=model.model.layers, embed_dim=4096,
|
|
110
|
+
config=ReFTConfig(r=4, layers=(8, 16, 24)),
|
|
111
|
+
)
|
|
112
|
+
optimizer = torch.optim.AdamW(adapter.trainable_parameters(), lr=1e-3)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### LiteLadder (experimental)
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from socketimport import LiteLadderAdapter, LiteLadderConfig
|
|
119
|
+
|
|
120
|
+
adapter = LiteLadderAdapter(
|
|
121
|
+
model, layers=model.model.layers, embed_dim=4096, output_dim=32000,
|
|
122
|
+
config=LiteLadderConfig(side_width=256, rank=32, n_taps=4),
|
|
123
|
+
)
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Backward never enters the backbone (showed much lower overhead than LoRA as depth increased in
|
|
127
|
+
small-scale tests) — but this has only been validated on synthetic tasks with a single CPU core.
|
|
128
|
+
**Not recommended** as production default; should be considered an opt-in experimental option.
|
|
129
|
+
|
|
130
|
+
### GaLore
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
from socketimport import GaLoreAdamW, GaLoreConfig, create_galore_param_groups
|
|
134
|
+
|
|
135
|
+
groups = create_galore_param_groups(model, GaLoreConfig(rank=128, update_proj_gap=200))
|
|
136
|
+
optimizer = GaLoreAdamW(groups, lr=1e-4)
|
|
137
|
+
# Model is trained FULL-PARAMETER - no adapter, no merge, GaLore
|
|
138
|
+
# only reduces optimizer memory usage
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
`GaLoreAdamW` does **not** implement `SocketAdapterBase` — it is not an adapter,
|
|
142
|
+
but a standard `torch.optim.Optimizer` subclass.
|
|
143
|
+
|
|
144
|
+
## Architecture
|
|
145
|
+
|
|
146
|
+
```
|
|
147
|
+
socketimport/
|
|
148
|
+
├── core/
|
|
149
|
+
│ ├── base.py # SocketAdapterBase - shared interface for LoRA/ReFT/LiteLadder
|
|
150
|
+
│ ├── lora.py
|
|
151
|
+
│ ├── reft.py
|
|
152
|
+
│ ├── lite_ladder.py
|
|
153
|
+
│ └── galore.py
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
All adapter classes (`LoRAAdapter`, `ReFTAdapter`, `LiteLadderAdapter`)
|
|
157
|
+
share the same `SocketAdapterBase` interface: `trainable_parameters()`,
|
|
158
|
+
`merge()`/`unmerge()`, `adapter_state_dict()`/`load_adapter_state_dict()`.
|
|
159
|
+
This allows the training infrastructure (trainer, distributed, profiler) to be
|
|
160
|
+
written independently of which method is selected.
|
|
161
|
+
|
|
162
|
+
## Development
|
|
163
|
+
|
|
164
|
+
```bash
|
|
165
|
+
pip install -e ".[dev]"
|
|
166
|
+
pytest tests/ -v
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
444 tests covering all modules: mathematical correctness (e.g., zero-initialization as no-op,
|
|
170
|
+
merge/unmerge being inverses), model freezing behavior, end-to-end training actually reducing loss,
|
|
171
|
+
and save/load round-trips.
|
|
172
|
+
|
|
173
|
+
> **Note:** `quantize_linear`/`quantize_model` and their tests require `bitsandbytes`
|
|
174
|
+
> (see [Dependencies](#dependencies)). The `dev` extra installs this automatically; if not installed,
|
|
175
|
+
> quantization tests will fail with `DependencyError` (not a library error).
|
|
176
|
+
|
|
177
|
+
## Dependencies
|
|
178
|
+
|
|
179
|
+
| Package | Required? | For |
|
|
180
|
+
|---|---|---|
|
|
181
|
+
| `torch>=2.0` | Yes | Entire library |
|
|
182
|
+
| `bitsandbytes>=0.41.0` | No (`pip install socket[quantization]`) | Only `quantize_linear`/`quantize_model` (4-bit/8-bit weight quantization) |
|
|
183
|
+
|
|
184
|
+
All other features (LoRA, ReFT, LiteLadder, GaLore, checkpointing, OOM recovery,
|
|
185
|
+
VRAM guard, distributed backend selection, etc.) work with `torch` alone.
|
|
186
|
+
|
|
187
|
+
## Limitations (honestly)
|
|
188
|
+
|
|
189
|
+
- All tests run on 1 CPU core with small synthetic tasks — no scale testing on GPU
|
|
190
|
+
or with real language data yet.
|
|
191
|
+
- LiteLadder is not a published method; Socket-specific architecture tested at small scale
|
|
192
|
+
(combination of LST + ReFT-style lightweight interventions).
|
|
193
|
+
- No multi-seed statistical validation; results are single-seed.
|
|
194
|
+
|
|
195
|
+
-Note: PyPI does not normally allow this package name; please use -pip install socket-lm- to install it.
|
|
196
|
+
|
|
197
|
+
## License
|
|
198
|
+
|
|
199
|
+
MIT — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
socket_lm-0.1.0.dist-info/licenses/LICENSE,sha256=LZhsxZQFqBiE7rkm3FLsj2_A5npqmqDJAgE2C_YkWbU,1075
|
|
2
|
+
socketimport/__init__.py,sha256=RaLnMdlLImGqagtScneXU6ZsRb5QrulHlPGEb37HABY,4210
|
|
3
|
+
socketimport/config.py,sha256=qjzWuclfZYzRBLUxpLvZSDmwsA9HJ7c6glSJVb-Y9jM,4402
|
|
4
|
+
socketimport/deps.py,sha256=BnVhastO_ylBTLP8V1Y_ryKwORJscW0294XHKo_JT2M,2110
|
|
5
|
+
socketimport/device.py,sha256=jWOEAyuGXg-NCJmWCdB8bIO7ewiWXaQK-Lxopy9uhXs,6009
|
|
6
|
+
socketimport/errors.py,sha256=pUQfu2xb0GO3uwjEJdLtfjDkRx8CgGQxrXQ-NweUj74,10169
|
|
7
|
+
socketimport/utils.py,sha256=GfeLV4ynaDi2aN_hPMtuTROQDMalzzeCnOi1ufEwF-4,2445
|
|
8
|
+
socketimport/core/__init__.py,sha256=MVut1OvGvKVkna2SsvFbqFni1Yegd6kzOjW1O86Y1QY,1447
|
|
9
|
+
socketimport/core/accelerator.py,sha256=ruIR_7ughakBgx_xrPL_JdyTS_Wix5uCOXryS3lTRhE,3293
|
|
10
|
+
socketimport/core/attention.py,sha256=5ve-tC-IMp0F44EX2wqM2C4fJ0zzmT8VI_gqD-4tNOM,1895
|
|
11
|
+
socketimport/core/base.py,sha256=X82OIWAF2DiJi_-xT5bWLrCHC3wGSmo2AcvkOU0TTcI,3205
|
|
12
|
+
socketimport/core/galore.py,sha256=rS8KRPMyoZ2Ga3umTNFEjFY31p-DQRBnkolUlwHtVMc,13262
|
|
13
|
+
socketimport/core/lite_ladder.py,sha256=N50xaBF2QdZq8sjErXAQa8wE3_c9EhhkebmrH0sYBps,14401
|
|
14
|
+
socketimport/core/lora.py,sha256=FACt7Y_NavOwHckhSVQOVBh04b3MHMM0MHqscCn7ueI,17472
|
|
15
|
+
socketimport/core/model_loader.py,sha256=VKtshzBXMSCWcfh4-9Drv4D3uqLz4Btv4-1i7CQU4Dg,3115
|
|
16
|
+
socketimport/core/quantization.py,sha256=CMpfO03LeIxYKiWX6yMDTNooh8BpXIX4X6joE9rCMKs,3493
|
|
17
|
+
socketimport/core/reft.py,sha256=F1r0VnK0Di7w7Jxgs0w3ZkCCQk45KHbhAojqjYbso-w,12832
|
|
18
|
+
socketimport/data/__init__.py,sha256=qvWb4n1wSdETMeGp7Ko1Z23baP6Rp3wp-Xig7Xo6fpY,65
|
|
19
|
+
socketimport/data/loader.py,sha256=Ohd2JjSYlsFXiIip9pM_Sq-WIwS9iVSm_5lxn6MUk8U,2353
|
|
20
|
+
socketimport/distributed/__init__.py,sha256=tn34fRlz9_EhQHSr3IpZfdPqqx0m6i8xWYwHex-Z9fk,5288
|
|
21
|
+
socketimport/memory/__init__.py,sha256=Y2MbehihG8MOb3Rm0K98KQJCv5ZRmnKhOoX6vBR2gvE,451
|
|
22
|
+
socketimport/memory/batch_finder.py,sha256=E9XFjwSQg7CDkZ2jzhv84PqebdVr7hOSq_O_JO5-H80,3640
|
|
23
|
+
socketimport/memory/checkpointing.py,sha256=k2AKmPXj8ybISB0Og6qWeTEhVADXgeucXS4920rn8MY,2632
|
|
24
|
+
socketimport/memory/tracker.py,sha256=Fp8mtom9XWRtCLYvDET-cS0c7CO66In4KxeYRZMdKtM,2954
|
|
25
|
+
socketimport/optim/__init__.py,sha256=Sm9Qy3xsoGgfW10lfy6tZm7_qYZtBShhfamlZRJ00FY,413
|
|
26
|
+
socketimport/optim/ema.py,sha256=9-BgAolCus3CNZqUZHEyvk8KrHxVoWdoFHmz3_J1t2o,2664
|
|
27
|
+
socketimport/optim/fused.py,sha256=MzAIrhu9_TfKPLvqVo843vKH5VIFzkMlvQDyd29_F14,2477
|
|
28
|
+
socketimport/optim/lion.py,sha256=GFSX-E3i1zD4b8O502bnfepHeshJlz5TYMsl2Csz1ks,2471
|
|
29
|
+
socketimport/optim/scheduler.py,sha256=h0s7-_utpOHnu4P70QOqVFZy0ZVJ1g0HUvGmN5ZI8V8,3299
|
|
30
|
+
socketimport/optim/swa.py,sha256=rEf5fBQzwUKuuzXLSb9KBeQcqSqLrlTAGwN418P_NgM,2327
|
|
31
|
+
socketimport/profiler/__init__.py,sha256=Gm1ckYCWWOQCAE8PYJqO_9Lk69UHxtYY0xOkxMK090Q,172
|
|
32
|
+
socketimport/profiler/benchmark.py,sha256=z38SCKEFO__ajPpHNtrHRJLnTHpD9y-ZYd8j5r0k0F0,2795
|
|
33
|
+
socketimport/profiler/trace.py,sha256=Onh8o2J1NvJrbvyaKc5EmdeQSpUDGWb-V3IixPQNatA,1527
|
|
34
|
+
socketimport/training/__init__.py,sha256=d8Vkm54c_SQd6aINlqrTJg5MjY_JEwd32y0Gmx8WMAM,792
|
|
35
|
+
socketimport/training/callbacks.py,sha256=vlLUgbqwL2Hj1gEeHsIOY4lcSPbKa_7U8o2MngFVMPA,3751
|
|
36
|
+
socketimport/training/framework_adapter.py,sha256=Q3vB5aJm6Naknkq7LJGjZACH_9SWvrBARGNOx84xNH4,3418
|
|
37
|
+
socketimport/training/oom_recovery.py,sha256=J_Huj_HzLtGwn5Aj4y7O26tt47m5YJCa6CxzLmcnNek,3793
|
|
38
|
+
socketimport/training/trainer.py,sha256=86_ATYVvuKCN6tEK4SroCHIT1WmfgyiARxluMOs0MVQ,7986
|
|
39
|
+
socketimport/training/vram_guard.py,sha256=aWUWmfLQDujdvrl_b0rzo8hGONV5T89Z5iRMItvPlJI,5108
|
|
40
|
+
socket_lm-0.1.0.dist-info/METADATA,sha256=LyOqqESP-uL0wFVisxZRfKAUhQtBcCE09cxxUxT6_Gw,8000
|
|
41
|
+
socket_lm-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
42
|
+
socket_lm-0.1.0.dist-info/top_level.txt,sha256=gHAgDHBRkVnTlTvqydTTm5CP39pDgD9D_W23fIfDzPM,13
|
|
43
|
+
socket_lm-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ömür Bera Işık
|
|
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
|
+
socketimport
|
socketimport/__init__.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
"""Socket - egitim hizina odaklanan bir LoRA/PEFT kutuphanesi.
|
|
2
|
+
|
|
3
|
+
PyPI paket adi 'socket'tir ama Python'un yerlesik `socket` (ag) modulu ile
|
|
4
|
+
karismamasi icin import adi 'socketimport'tur:
|
|
5
|
+
|
|
6
|
+
pip install socket
|
|
7
|
+
import socketimport as sk
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .core.accelerator import Accelerator
|
|
11
|
+
from .core.attention import is_flash_attention_active, optimized_attention
|
|
12
|
+
from .core.base import SocketAdapterBase
|
|
13
|
+
from .core.galore import GaLoreAdamW, GaLoreConfig, GaLoreProjector, create_galore_param_groups
|
|
14
|
+
from .core.lite_ladder import LiteLadderAdapter, LiteLadderConfig, LiteLadderSide
|
|
15
|
+
from .core.lora import DEFAULT_TARGET_MODULES, LoRAAdapter, LoRAConfig, LoRALinear
|
|
16
|
+
from .core.model_loader import ModelLoadConfig, ModelLoadError, SafeModelLoader
|
|
17
|
+
from .core.quantization import QuantizationConfig, quantize_linear, quantize_model
|
|
18
|
+
from .core.reft import LoReftIntervention, ReFTAdapter, ReFTConfig
|
|
19
|
+
from .config import SocketConfig
|
|
20
|
+
from .deps import get_version, is_available, require, require_any
|
|
21
|
+
from .device import DeviceManager, DeviceType
|
|
22
|
+
from .errors import (
|
|
23
|
+
ConfigurationError,
|
|
24
|
+
DependencyError,
|
|
25
|
+
ErrorReport,
|
|
26
|
+
ErrorSeverity,
|
|
27
|
+
GradientMonitor,
|
|
28
|
+
RateLimitedLogger,
|
|
29
|
+
SocketError,
|
|
30
|
+
auto_install,
|
|
31
|
+
classify_error,
|
|
32
|
+
)
|
|
33
|
+
from .memory import (
|
|
34
|
+
MemorySnapshot,
|
|
35
|
+
MemoryTracker,
|
|
36
|
+
apply_activation_checkpointing,
|
|
37
|
+
binary_search_max,
|
|
38
|
+
find_max_batch_size,
|
|
39
|
+
is_checkpointed,
|
|
40
|
+
remove_activation_checkpointing,
|
|
41
|
+
)
|
|
42
|
+
from .data import PrefetchLoader
|
|
43
|
+
from .distributed import DistributedConfig, select_backend
|
|
44
|
+
from .optim import (
|
|
45
|
+
EMA,
|
|
46
|
+
SWA,
|
|
47
|
+
Lion,
|
|
48
|
+
convert_to_fused,
|
|
49
|
+
get_constant_schedule_with_warmup,
|
|
50
|
+
get_warmup_cosine_schedule,
|
|
51
|
+
get_warmup_linear_schedule,
|
|
52
|
+
)
|
|
53
|
+
from .profiler import BenchmarkResult, benchmark, compare
|
|
54
|
+
from .profiler import summarize as profiler_summarize
|
|
55
|
+
from .profiler import trace as profiler_trace
|
|
56
|
+
from .training import (
|
|
57
|
+
EarlyStopping,
|
|
58
|
+
FrameworkInfo,
|
|
59
|
+
LossSpikeDetector,
|
|
60
|
+
OOMRecovery,
|
|
61
|
+
OOMRecoveryConfig,
|
|
62
|
+
OOMRecoveryExhausted,
|
|
63
|
+
RecoveryPlan,
|
|
64
|
+
Trainer,
|
|
65
|
+
TrainerConfig,
|
|
66
|
+
VRAMGuard,
|
|
67
|
+
VRAMGuardConfig,
|
|
68
|
+
VRAMStatus,
|
|
69
|
+
detect_framework,
|
|
70
|
+
optimal_attention_backend,
|
|
71
|
+
optimal_dtype,
|
|
72
|
+
)
|
|
73
|
+
from .training import framework_summary
|
|
74
|
+
from .utils import check_environment, format_alpaca, format_chatml
|
|
75
|
+
|
|
76
|
+
__version__ = "0.1.0"
|
|
77
|
+
|
|
78
|
+
__all__ = [
|
|
79
|
+
"SocketAdapterBase",
|
|
80
|
+
"LoRAAdapter",
|
|
81
|
+
"LoRAConfig",
|
|
82
|
+
"LoRALinear",
|
|
83
|
+
"DEFAULT_TARGET_MODULES",
|
|
84
|
+
"ReFTAdapter",
|
|
85
|
+
"ReFTConfig",
|
|
86
|
+
"LoReftIntervention",
|
|
87
|
+
"LiteLadderAdapter",
|
|
88
|
+
"LiteLadderConfig",
|
|
89
|
+
"LiteLadderSide",
|
|
90
|
+
"GaLoreAdamW",
|
|
91
|
+
"GaLoreConfig",
|
|
92
|
+
"GaLoreProjector",
|
|
93
|
+
"create_galore_param_groups",
|
|
94
|
+
"SafeModelLoader",
|
|
95
|
+
"ModelLoadConfig",
|
|
96
|
+
"ModelLoadError",
|
|
97
|
+
"QuantizationConfig",
|
|
98
|
+
"quantize_linear",
|
|
99
|
+
"quantize_model",
|
|
100
|
+
"optimized_attention",
|
|
101
|
+
"is_flash_attention_active",
|
|
102
|
+
"Accelerator",
|
|
103
|
+
"DeviceManager",
|
|
104
|
+
"DeviceType",
|
|
105
|
+
"SocketError",
|
|
106
|
+
"ConfigurationError",
|
|
107
|
+
"DependencyError",
|
|
108
|
+
"ErrorReport",
|
|
109
|
+
"ErrorSeverity",
|
|
110
|
+
"GradientMonitor",
|
|
111
|
+
"RateLimitedLogger",
|
|
112
|
+
"classify_error",
|
|
113
|
+
"auto_install",
|
|
114
|
+
"is_available",
|
|
115
|
+
"get_version",
|
|
116
|
+
"require",
|
|
117
|
+
"require_any",
|
|
118
|
+
"MemoryTracker",
|
|
119
|
+
"MemorySnapshot",
|
|
120
|
+
"find_max_batch_size",
|
|
121
|
+
"binary_search_max",
|
|
122
|
+
"apply_activation_checkpointing",
|
|
123
|
+
"remove_activation_checkpointing",
|
|
124
|
+
"is_checkpointed",
|
|
125
|
+
"VRAMGuard",
|
|
126
|
+
"VRAMGuardConfig",
|
|
127
|
+
"VRAMStatus",
|
|
128
|
+
"OOMRecovery",
|
|
129
|
+
"OOMRecoveryConfig",
|
|
130
|
+
"OOMRecoveryExhausted",
|
|
131
|
+
"RecoveryPlan",
|
|
132
|
+
"LossSpikeDetector",
|
|
133
|
+
"EarlyStopping",
|
|
134
|
+
"Trainer",
|
|
135
|
+
"TrainerConfig",
|
|
136
|
+
"FrameworkInfo",
|
|
137
|
+
"detect_framework",
|
|
138
|
+
"optimal_dtype",
|
|
139
|
+
"optimal_attention_backend",
|
|
140
|
+
"framework_summary",
|
|
141
|
+
"Lion",
|
|
142
|
+
"EMA",
|
|
143
|
+
"SWA",
|
|
144
|
+
"convert_to_fused",
|
|
145
|
+
"get_warmup_linear_schedule",
|
|
146
|
+
"get_warmup_cosine_schedule",
|
|
147
|
+
"get_constant_schedule_with_warmup",
|
|
148
|
+
"PrefetchLoader",
|
|
149
|
+
"DistributedConfig",
|
|
150
|
+
"select_backend",
|
|
151
|
+
"benchmark",
|
|
152
|
+
"compare",
|
|
153
|
+
"BenchmarkResult",
|
|
154
|
+
"profiler_trace",
|
|
155
|
+
"profiler_summarize",
|
|
156
|
+
"SocketConfig",
|
|
157
|
+
"format_alpaca",
|
|
158
|
+
"format_chatml",
|
|
159
|
+
"check_environment",
|
|
160
|
+
"__version__",
|
|
161
|
+
]
|
socketimport/config.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Socket Config
|
|
3
|
+
==============
|
|
4
|
+
Ust duzey egitim yapilandirmasi - hangi adaptasyon yontemi, temel
|
|
5
|
+
egitim hiperparametreleri. LoRAConfig/ReFTConfig/vb'nin YERINE gecmez -
|
|
6
|
+
onlarla BIRLIKTE kullanilir (method='lora' secildiginde ayrica bir
|
|
7
|
+
LoRAConfig de verilir)."""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, fields
|
|
12
|
+
from typing import Any, ClassVar
|
|
13
|
+
|
|
14
|
+
_VALID_METHODS = ("lora", "reft", "lite_ladder", "galore")
|
|
15
|
+
_VALID_SCHEDULERS = ("linear", "cosine", "constant")
|
|
16
|
+
_VALID_PRECISIONS = ("no", "fp16", "bf16")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class SocketConfig:
|
|
21
|
+
method: str = "lora"
|
|
22
|
+
output_dir: str = "./socket_output"
|
|
23
|
+
num_epochs: int = 1
|
|
24
|
+
max_steps: int | None = None
|
|
25
|
+
per_device_batch_size: int = 8
|
|
26
|
+
gradient_accumulation_steps: int = 1
|
|
27
|
+
learning_rate: float = 2e-4
|
|
28
|
+
lr_scheduler: str = "cosine"
|
|
29
|
+
warmup_ratio: float = 0.03
|
|
30
|
+
mixed_precision: str = "bf16"
|
|
31
|
+
max_grad_norm: float = 1.0
|
|
32
|
+
logging_steps: int = 10
|
|
33
|
+
save_steps: int = 100
|
|
34
|
+
seed: int = 42
|
|
35
|
+
|
|
36
|
+
_ALIASES: ClassVar[dict[str, str]] = {
|
|
37
|
+
"adaptation_method": "method",
|
|
38
|
+
"epochs": "num_epochs",
|
|
39
|
+
"batch_size": "per_device_batch_size",
|
|
40
|
+
"per_device_train_batch_size": "per_device_batch_size",
|
|
41
|
+
"grad_accum_steps": "gradient_accumulation_steps",
|
|
42
|
+
"lr": "learning_rate",
|
|
43
|
+
"scheduler": "lr_scheduler",
|
|
44
|
+
"fp16": "mixed_precision",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
def __post_init__(self) -> None:
|
|
48
|
+
if self.method not in _VALID_METHODS:
|
|
49
|
+
raise ValueError(f"method {_VALID_METHODS} icinde olmali, alinan: {self.method!r}")
|
|
50
|
+
if self.num_epochs <= 0:
|
|
51
|
+
raise ValueError(f"num_epochs pozitif olmali, alinan: {self.num_epochs!r}")
|
|
52
|
+
if self.max_steps is not None and self.max_steps <= 0:
|
|
53
|
+
raise ValueError(f"max_steps verilirse pozitif olmali, alinan: {self.max_steps!r}")
|
|
54
|
+
if self.per_device_batch_size <= 0:
|
|
55
|
+
raise ValueError(
|
|
56
|
+
f"per_device_batch_size pozitif olmali, alinan: {self.per_device_batch_size!r}"
|
|
57
|
+
)
|
|
58
|
+
if self.gradient_accumulation_steps <= 0:
|
|
59
|
+
raise ValueError(
|
|
60
|
+
f"gradient_accumulation_steps pozitif olmali, alinan: "
|
|
61
|
+
f"{self.gradient_accumulation_steps!r}"
|
|
62
|
+
)
|
|
63
|
+
if self.learning_rate <= 0:
|
|
64
|
+
raise ValueError(f"learning_rate pozitif olmali, alinan: {self.learning_rate!r}")
|
|
65
|
+
if self.lr_scheduler not in _VALID_SCHEDULERS:
|
|
66
|
+
raise ValueError(
|
|
67
|
+
f"lr_scheduler {_VALID_SCHEDULERS} icinde olmali, alinan: {self.lr_scheduler!r}"
|
|
68
|
+
)
|
|
69
|
+
if not (0.0 <= self.warmup_ratio < 1.0):
|
|
70
|
+
raise ValueError(f"warmup_ratio [0,1) araliginda olmali, alinan: {self.warmup_ratio!r}")
|
|
71
|
+
if self.mixed_precision not in _VALID_PRECISIONS:
|
|
72
|
+
raise ValueError(
|
|
73
|
+
f"mixed_precision {_VALID_PRECISIONS} icinde olmali, alinan: {self.mixed_precision!r}"
|
|
74
|
+
)
|
|
75
|
+
if self.max_grad_norm <= 0:
|
|
76
|
+
raise ValueError(f"max_grad_norm pozitif olmali, alinan: {self.max_grad_norm!r}")
|
|
77
|
+
if self.logging_steps <= 0:
|
|
78
|
+
raise ValueError(f"logging_steps pozitif olmali, alinan: {self.logging_steps!r}")
|
|
79
|
+
if self.save_steps <= 0:
|
|
80
|
+
raise ValueError(f"save_steps pozitif olmali, alinan: {self.save_steps!r}")
|
|
81
|
+
|
|
82
|
+
def effective_batch_size(self, world_size: int = 1) -> int:
|
|
83
|
+
"""Gradient accumulation ve dagitik egitim (varsa) sonrasi
|
|
84
|
+
GERCEK etkin batch size'i hesaplar."""
|
|
85
|
+
return self.per_device_batch_size * self.gradient_accumulation_steps * world_size
|
|
86
|
+
|
|
87
|
+
@classmethod
|
|
88
|
+
def from_kwargs(cls, **kwargs: Any) -> "SocketConfig":
|
|
89
|
+
resolved: dict[str, Any] = {}
|
|
90
|
+
for key, value in kwargs.items():
|
|
91
|
+
canonical = cls._ALIASES.get(key, key)
|
|
92
|
+
if canonical in resolved and resolved[canonical] != value:
|
|
93
|
+
raise ValueError(
|
|
94
|
+
f"'{key}' parametresi '{canonical}' alanina celisen bir "
|
|
95
|
+
f"deger veriyor (once {resolved[canonical]!r} verilmisti, "
|
|
96
|
+
f"simdi {value!r})."
|
|
97
|
+
)
|
|
98
|
+
resolved[canonical] = value
|
|
99
|
+
valid_fields = {f.name for f in fields(cls)}
|
|
100
|
+
unknown = set(resolved) - valid_fields
|
|
101
|
+
if unknown:
|
|
102
|
+
raise ValueError(f"Bilinmeyen SocketConfig parametre(ler)i: {sorted(unknown)}")
|
|
103
|
+
return cls(**resolved)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from .accelerator import Accelerator
|
|
2
|
+
from .attention import is_flash_attention_active, optimized_attention
|
|
3
|
+
from .base import SocketAdapterBase
|
|
4
|
+
from .galore import GaLoreAdamW, GaLoreConfig, GaLoreProjector, create_galore_param_groups
|
|
5
|
+
from .lite_ladder import LiteLadderAdapter, LiteLadderConfig, LiteLadderSide
|
|
6
|
+
from .lora import DEFAULT_TARGET_MODULES, LoRAAdapter, LoRAConfig, LoRALinear
|
|
7
|
+
from .model_loader import ModelLoadConfig, ModelLoadError, SafeModelLoader
|
|
8
|
+
from .quantization import QuantizationConfig, quantize_linear, quantize_model
|
|
9
|
+
from .reft import LoReftIntervention, ReFTAdapter, ReFTConfig
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"SocketAdapterBase",
|
|
13
|
+
# LoRA
|
|
14
|
+
"LoRAAdapter",
|
|
15
|
+
"LoRAConfig",
|
|
16
|
+
"LoRALinear",
|
|
17
|
+
"DEFAULT_TARGET_MODULES",
|
|
18
|
+
# ReFT
|
|
19
|
+
"ReFTAdapter",
|
|
20
|
+
"ReFTConfig",
|
|
21
|
+
"LoReftIntervention",
|
|
22
|
+
# LiteLadder (deneysel - kucuk olcekte dogrulandi, gercek dil
|
|
23
|
+
# verisiyle henuz test edilmedi, varsayilan olarak onerilmez)
|
|
24
|
+
"LiteLadderAdapter",
|
|
25
|
+
"LiteLadderConfig",
|
|
26
|
+
"LiteLadderSide",
|
|
27
|
+
# GaLore (SocketAdapterBase DEGIL - bir optimizer)
|
|
28
|
+
"GaLoreAdamW",
|
|
29
|
+
"GaLoreConfig",
|
|
30
|
+
"GaLoreProjector",
|
|
31
|
+
"create_galore_param_groups",
|
|
32
|
+
# Model yukleme / quantization / attention / accelerator
|
|
33
|
+
"SafeModelLoader",
|
|
34
|
+
"ModelLoadConfig",
|
|
35
|
+
"ModelLoadError",
|
|
36
|
+
"QuantizationConfig",
|
|
37
|
+
"quantize_linear",
|
|
38
|
+
"quantize_model",
|
|
39
|
+
"optimized_attention",
|
|
40
|
+
"is_flash_attention_active",
|
|
41
|
+
"Accelerator",
|
|
42
|
+
]
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Socket Core - accelerator
|
|
3
|
+
============================
|
|
4
|
+
Karisik hassasiyet (mixed precision), gradient accumulation ve
|
|
5
|
+
aktivasyon checkpointing'i tek bir arayuzde toplayan Accelerator.
|
|
6
|
+
|
|
7
|
+
Onceki incelenen bir kutuphanede DEPRECATED `torch.cuda.amp.GradScaler`/
|
|
8
|
+
`torch.cuda.amp.autocast` API'si kullaniliyordu. Burada GUNCEL
|
|
9
|
+
`torch.amp.GradScaler(device_type)` / `torch.autocast(device_type=...)`
|
|
10
|
+
API'si kullanilir - bu ayrica CPU'da da (bf16 VE fp16 icin, bu sandbox'ta
|
|
11
|
+
dogrulandi) GERCEKTEN CALISIR, yani sadece CUDA'da degil, CPU'da da tam
|
|
12
|
+
anlamiyla test edilebilir."""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
from typing import Any, Iterator
|
|
18
|
+
|
|
19
|
+
import torch
|
|
20
|
+
import torch.nn as nn
|
|
21
|
+
|
|
22
|
+
from ..device import DeviceManager
|
|
23
|
+
|
|
24
|
+
_VALID_PRECISIONS = ("no", "fp16", "bf16")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Accelerator:
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
mixed_precision: str = "no",
|
|
31
|
+
gradient_accumulation_steps: int = 1,
|
|
32
|
+
device_manager: DeviceManager | None = None,
|
|
33
|
+
):
|
|
34
|
+
if mixed_precision not in _VALID_PRECISIONS:
|
|
35
|
+
raise ValueError(
|
|
36
|
+
f"mixed_precision {_VALID_PRECISIONS} icinde olmali, alinan: {mixed_precision!r}"
|
|
37
|
+
)
|
|
38
|
+
if gradient_accumulation_steps <= 0:
|
|
39
|
+
raise ValueError(
|
|
40
|
+
f"gradient_accumulation_steps pozitif olmali, alinan: "
|
|
41
|
+
f"{gradient_accumulation_steps!r}"
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
self.device_manager = device_manager or DeviceManager()
|
|
45
|
+
self.mixed_precision = mixed_precision
|
|
46
|
+
self.gradient_accumulation_steps = gradient_accumulation_steps
|
|
47
|
+
self._micro_step = 0
|
|
48
|
+
|
|
49
|
+
self._autocast_device_type = (
|
|
50
|
+
self.device_manager.device_type.value
|
|
51
|
+
if self.device_manager.device_type.value in ("cuda", "cpu")
|
|
52
|
+
else "cpu"
|
|
53
|
+
)
|
|
54
|
+
self.scaler: torch.amp.GradScaler | None = None
|
|
55
|
+
if mixed_precision == "fp16":
|
|
56
|
+
self.scaler = torch.amp.GradScaler(self._autocast_device_type)
|
|
57
|
+
|
|
58
|
+
def autocast(self) -> contextlib.AbstractContextManager:
|
|
59
|
+
if self.mixed_precision == "no":
|
|
60
|
+
return contextlib.nullcontext()
|
|
61
|
+
dtype = torch.float16 if self.mixed_precision == "fp16" else torch.bfloat16
|
|
62
|
+
return torch.autocast(device_type=self._autocast_device_type, dtype=dtype)
|
|
63
|
+
|
|
64
|
+
def backward(self, loss: torch.Tensor) -> None:
|
|
65
|
+
"""Loss'u gradient_accumulation_steps'e boler ve geri yayilim
|
|
66
|
+
yapar. Olceklendirme (scaler varsa) burada uygulanir."""
|
|
67
|
+
scaled_loss = loss / self.gradient_accumulation_steps
|
|
68
|
+
if self.scaler is not None:
|
|
69
|
+
self.scaler.scale(scaled_loss).backward()
|
|
70
|
+
else:
|
|
71
|
+
scaled_loss.backward()
|
|
72
|
+
|
|
73
|
+
def should_step(self) -> bool:
|
|
74
|
+
"""Her mikro-adimda cagrilir; sadece gradient_accumulation_steps'in
|
|
75
|
+
katinda True doner - o zaman optimizer.step() cagirmak
|
|
76
|
+
gerektigi anlamina gelir."""
|
|
77
|
+
self._micro_step += 1
|
|
78
|
+
return self._micro_step % self.gradient_accumulation_steps == 0
|
|
79
|
+
|
|
80
|
+
def step(self, optimizer: torch.optim.Optimizer) -> None:
|
|
81
|
+
if self.scaler is not None:
|
|
82
|
+
self.scaler.step(optimizer)
|
|
83
|
+
self.scaler.update()
|
|
84
|
+
else:
|
|
85
|
+
optimizer.step()
|
|
86
|
+
optimizer.zero_grad(set_to_none=True)
|
|
87
|
+
|
|
88
|
+
def reset(self) -> None:
|
|
89
|
+
self._micro_step = 0
|