pytinytensor 0.1.0__tar.gz → 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. pytinytensor-0.1.1/PKG-INFO +224 -0
  2. pytinytensor-0.1.1/pytinytensor.egg-info/PKG-INFO +224 -0
  3. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/setup.py +12 -7
  4. pytinytensor-0.1.0/PKG-INFO +0 -13
  5. pytinytensor-0.1.0/pytinytensor.egg-info/PKG-INFO +0 -13
  6. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/README.md +0 -0
  7. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/pyproject.toml +0 -0
  8. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/pytinytensor.egg-info/SOURCES.txt +0 -0
  9. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/pytinytensor.egg-info/dependency_links.txt +0 -0
  10. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/pytinytensor.egg-info/requires.txt +0 -0
  11. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/pytinytensor.egg-info/top_level.txt +0 -0
  12. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/setup.cfg +0 -0
  13. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tests/test_autograd.py +0 -0
  14. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tests/test_data.py +0 -0
  15. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tests/test_losses.py +0 -0
  16. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tests/test_nn.py +0 -0
  17. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tests/test_optim.py +0 -0
  18. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tests/test_tensor_math.py +0 -0
  19. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/__init__.py +0 -0
  20. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/backends/__init__.py +0 -0
  21. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/backends/cpu_numpy.py +0 -0
  22. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/backends/cuda_binding.cpp +0 -0
  23. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/backends/cuda_gpu.cu +0 -0
  24. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/config.py +0 -0
  25. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/core/__init__.py +0 -0
  26. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/core/autograd.py +0 -0
  27. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/core/ops.py +0 -0
  28. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/core/tensor.py +0 -0
  29. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/data/__init__.py +0 -0
  30. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/data/dataloader.py +0 -0
  31. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/data/dataset.py +0 -0
  32. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/nn/__init__.py +0 -0
  33. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/nn/activations.py +0 -0
  34. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/nn/linear.py +0 -0
  35. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/nn/losses.py +0 -0
  36. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/nn/modules.py +0 -0
  37. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/optim/__init__.py +0 -0
  38. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/optim/optimizer.py +0 -0
  39. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/utils/__init__.py +0 -0
  40. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/utils/bar.py +0 -0
  41. {pytinytensor-0.1.0 → pytinytensor-0.1.1}/tinytensor/utils/early_stopping.py +0 -0
@@ -0,0 +1,224 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytinytensor
3
+ Version: 0.1.1
4
+ Summary: мини ИИ фреймворк от IbrokimN ( github/IbrokhimN )
5
+ Home-page: https://github.com/IbrokhimN/tinytensor
6
+ Author: IbrokhimN
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: numpy>=1.23
10
+ Requires-Dist: pybind11>=2.10
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=7.0; extra == "dev"
13
+ Dynamic: author
14
+ Dynamic: description
15
+ Dynamic: description-content-type
16
+ Dynamic: home-page
17
+ Dynamic: provides-extra
18
+ Dynamic: requires-dist
19
+ Dynamic: requires-python
20
+ Dynamic: summary
21
+
22
+ # tinytensor
23
+
24
+ Маленький самописный autograd на numpy. Тензоры, backprop, пара слоев,
25
+ лоссы, оптимизаторы и даталоадер. По сути свой мини-pytorch, только без
26
+ плюшек и без cuda (пока).
27
+
28
+ Никакой производительности тут не ищите, тут просто видно как все
29
+ устроено внутри, без магии.
30
+
31
+ ## Содержание
32
+
33
+ - [Установка](#установка)
34
+ - [Быстрый старт](#быстрый-старт)
35
+ - [Как работает autograd](#как-работает-autograd)
36
+ - [API](#api)
37
+ - [Примеры](#примеры)
38
+ - [Тесты](#тесты)
39
+ - [Структура](#структура)
40
+ - [Чего нет](#чего-нет)
41
+ - [Ссылки](#ссылки)
42
+
43
+ ## Установка
44
+
45
+ ```bash
46
+ git clone https://github.com/IbrokhimN/tinytensor
47
+ cd tinytensor
48
+ pip install -e . # обычная установка
49
+ pip install -e .[dev] # плюс pytest, если хотите гонять тесты
50
+ ```
51
+
52
+ Или руками:
53
+
54
+ ```bash
55
+ pip install -r requirements.txt
56
+ ```
57
+
58
+ Зависимость одна - numpy.
59
+
60
+ ## Быстрый старт
61
+
62
+ ```python
63
+ from tinytensor.core.tensor import Tensor
64
+ from tinytensor.nn.linear import Linear
65
+ from tinytensor.nn.losses import MSELoss
66
+ from tinytensor.optim import SGD
67
+
68
+ model = Linear(in_features=1, out_features=1)
69
+ loss_fn = MSELoss()
70
+ optimizer = SGD(model.parameters(), lr=0.01)
71
+
72
+ x = Tensor([[1.0], [2.0], [3.0]])
73
+ y = Tensor([[3.0], [5.0], [7.0]]) # y = 2x + 1
74
+
75
+ for epoch in range(100):
76
+ optimizer.zero_grad()
77
+ pred = model(x)
78
+ loss = loss_fn(pred, y)
79
+ loss.backward()
80
+ optimizer.step()
81
+
82
+ print(model.weight.data, model.bias.data) # ~2.0, ~1.0
83
+ ```
84
+
85
+ Рабочие примеры целиком лежат в [`examples/`](examples/).
86
+
87
+ ## Как работает autograd
88
+
89
+ У каждого `Tensor` есть:
90
+
91
+ - `data` - сами значения (numpy-массив, всегда float32);
92
+ - `grad` - градиент, пока не посчитан - None;
93
+ - `_prev` - от каких тензоров он произошел (родители в графе);
94
+ - `_backward` - функция которая знает как раскидать градиент на родителей.
95
+
96
+ Когда считаете `z = f(x, y)`, по цепному правилу:
97
+
98
+ ```
99
+ dL/dx = dL/dz * dz/dx
100
+ dL/dy = dL/dz * dz/dy
101
+ ```
102
+
103
+ `backward()` строит топологический порядок графа (`tinytensor/core/autograd.py`),
104
+ ставит корню градиент = 1 и идет в обратном порядке, вызывая `_backward()`
105
+ у каждого узла. Ровно так же устроен micrograd Карпатова, только у него
106
+ даже покомпактнее:
107
+
108
+ - [Karpathy - micrograd](https://github.com/karpathy/micrograd) - реализация того же самого на ~100 строк, must see
109
+ - [CS231n: Backpropagation, Intuitions](https://cs231n.github.io/optimization-2/) - если нужно разложить backprop по полочкам
110
+ - [colah - Calculus on Computational Graphs](https://colah.github.io/posts/2015-08-Backprop/)
111
+
112
+ Если совсем в тему - есть видос Карпатова где он с нуля пишет micrograd и
113
+ объясняет каждую строчку: ["The spelled-out intro to neural networks and backpropagation"](https://www.youtube.com/watch?v=VMj-3S1tku0).
114
+ Собственно тут все то же самое, только на numpy и чуть пошире.
115
+
116
+ ### Формулы, которые реализованы в Tensor
117
+
118
+ | операция | вперед | производная |
119
+ |---|---|---|
120
+ | `a + b` | `a + b` | `dL/da += dL/dz`, `dL/db += dL/dz` (плюс схлопывание по broadcast-осям) |
121
+ | `a * b` | `a * b` | `dL/da += dL/dz * b`, `dL/db += dL/dz * a` |
122
+ | `a @ b` | matmul | `dL/da += dL/dz @ bᵀ`, `dL/db += aᵀ @ dL/dz` |
123
+ | `a ** p` | `aᵖ` | `dL/da += dL/dz * p * a^(p-1)` |
124
+ | ReLU | `max(0, x)` | 1 при x>0, иначе 0 |
125
+ | LeakyReLU | x или αx | 1 при x>0, иначе α |
126
+ | sigmoid | `1/(1+e⁻ˣ)` | `σ(x)*(1-σ(x))` |
127
+ | tanh | `tanh(x)` | `1 - tanh²(x)` |
128
+ | GELU | `0.5x(1+tanh(√(2/π)(x+0.044715x³)))` | см. [статью по GELU](https://arxiv.org/abs/1606.08415), формула там не самая короткая |
129
+
130
+ Про broadcasting и почему градиент иногда надо досуммировать обратно
131
+ (`_unbroadcast`) норм объясняют [правила broadcasting в numpy](https://numpy.org/doc/stable/user/basics.broadcasting.html).
132
+
133
+ ## API
134
+
135
+ ### Tensor
136
+
137
+ `tinytensor.core.tensor.Tensor` - главный класс. Есть `+ - * @ **`, `.sum()`,
138
+ активации `relu / leaky_relu / sigmoid / tanh / gelu`, ну и `.backward()`.
139
+
140
+ ### nn
141
+
142
+ - `Module` - от него наследуются все слои, `forward / parameters() / zero_grad()`, по духу как [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html);
143
+ - `Linear(in_features, out_features)` - обычный `y = xW + b`, веса инициализируются по [He/Kaiming init](https://arxiv.org/abs/1502.01852) (`std = sqrt(2/in_features)`);
144
+ - `ReLU, LeReLU, Sigmod, Tanh, GELU` - тонкие обертки над методами Tensor;
145
+ - `MSELoss` - `mean((pred - target)^2)`, банальщина.
146
+
147
+ ### optim
148
+
149
+ - `SGD(params, lr, momentum=0.0)` - обычный градиентный спуск, можно с моментом;
150
+ - `AdamW(params, lr, betas, eps, weight_decay)` - Adam с отдельным weight decay, см. [Loshchilov & Hutter](https://arxiv.org/abs/1711.05101) (в отличие от обычного [Adam](https://arxiv.org/abs/1412.6980), decay тут не лезет в градиент, а сразу режет веса).
151
+
152
+ ### data
153
+
154
+ - `Dataset / TensorDataset` - обертка над (x, y);
155
+ - `DataLoader` - бьет на батчи, можно с shuffle, мини-версия [`torch.utils.data.DataLoader`](https://pytorch.org/docs/stable/data.html).
156
+
157
+ ## Примеры
158
+
159
+ - [`examples/01_linear_regression.py`](examples/01_linear_regression.py) - линейная регрессия, Linear + MSELoss + SGD на `y = 3x + 2 + шум`.
160
+ - [`examples/02_mnist_mlp.py`](examples/02_mnist_mlp.py) - MLP (Linear -> ReLU -> Linear) с AdamW и DataLoader на синтетике в формате mnist (784 фичи, 10 классов). Настоящего mnist и загрузчиков датасетов тут нет, лень было тащить.
161
+
162
+ Как выглядит запуск вживую:
163
+
164
+ ```
165
+ $ python3 01_linear_regression.py
166
+ epoch 0 | loss 30.8016
167
+ epoch 180 | loss 0.2365
168
+ выученные параметры: weight ~ 2.995, bias ~ 1.996
169
+
170
+ $ python3 02_mnist_mlp.py
171
+ epoch 1/5 | avg loss 2.0998
172
+ epoch 5/5 | avg loss 0.0481
173
+ ```
174
+
175
+ ## Тесты
176
+
177
+ ```bash
178
+ pip install -e .[dev]
179
+ python3 -m pytest tests/ -v
180
+ ```
181
+
182
+ 47 штук, гоняют арифметику тензоров и broadcasting, autograd (накопление
183
+ градиента, топология, повторный backward), лоссы, оптимизаторы и
184
+ Dataset/DataLoader.
185
+
186
+ > Важно: запускать через pytest из корня репы (или после `pip install -e .`),
187
+ > а не `python3 test_x.py` из папки tests - иначе tinytensor просто не найдется.
188
+
189
+ ## Структура
190
+
191
+ ```
192
+ tinytensor/
193
+ ├── tinytensor/
194
+ │ ├── core/ # Tensor, autograd, ops
195
+ │ ├── nn/ # Module, Linear, активации, MSELoss
196
+ │ ├── optim/ # SGD, AdamW
197
+ │ ├── data/ # Dataset, DataLoader
198
+ │ ├── backends/ # заготовка под cuda, пока пусто
199
+ │ └── config.py # сид рандома
200
+ ├── examples/
201
+ ├── tests/
202
+ ├── setup.py
203
+ └── requirements.txt
204
+ ```
205
+
206
+ ## Чего нет
207
+
208
+ - Только numpy-backend, cuda_gpu.py пустой файл-заглушка.
209
+ - Нет кросс-энтропии, сверток, рекуррентных слоев, сохранения модели (см. ToDo в исходном плане проекта).
210
+ - backward не кэширует граф между вызовами, каждый раз строит топологию заново, как и в micrograd - никакой лени в духе pytorch тут нет.
211
+
212
+ ## Ссылки
213
+
214
+ - [Andrej Karpathy - micrograd (GitHub)](https://github.com/karpathy/micrograd) - основной референс для всего autograd
215
+ - [Andrej Karpathy - видео про backprop и micrograd](https://www.youtube.com/watch?v=VMj-3S1tku0)
216
+ - [CS231n - Backpropagation, Intuitions](https://cs231n.github.io/optimization-2/)
217
+ - [colah - Calculus on Computational Graphs](https://colah.github.io/posts/2015-08-Backprop/)
218
+ - [NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)
219
+ - [He et al. - инициализация весов](https://arxiv.org/abs/1502.01852)
220
+ - [Kingma & Ba - Adam](https://arxiv.org/abs/1412.6980)
221
+ - [Loshchilov & Hutter - AdamW](https://arxiv.org/abs/1711.05101)
222
+ - [Hendrycks & Gimpel - GELU](https://arxiv.org/abs/1606.08415)
223
+ - [PyTorch - torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)
224
+ - [PyTorch - torch.utils.data.DataLoader](https://pytorch.org/docs/stable/data.html)
@@ -0,0 +1,224 @@
1
+ Metadata-Version: 2.4
2
+ Name: pytinytensor
3
+ Version: 0.1.1
4
+ Summary: мини ИИ фреймворк от IbrokimN ( github/IbrokhimN )
5
+ Home-page: https://github.com/IbrokhimN/tinytensor
6
+ Author: IbrokhimN
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: numpy>=1.23
10
+ Requires-Dist: pybind11>=2.10
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=7.0; extra == "dev"
13
+ Dynamic: author
14
+ Dynamic: description
15
+ Dynamic: description-content-type
16
+ Dynamic: home-page
17
+ Dynamic: provides-extra
18
+ Dynamic: requires-dist
19
+ Dynamic: requires-python
20
+ Dynamic: summary
21
+
22
+ # tinytensor
23
+
24
+ Маленький самописный autograd на numpy. Тензоры, backprop, пара слоев,
25
+ лоссы, оптимизаторы и даталоадер. По сути свой мини-pytorch, только без
26
+ плюшек и без cuda (пока).
27
+
28
+ Никакой производительности тут не ищите, тут просто видно как все
29
+ устроено внутри, без магии.
30
+
31
+ ## Содержание
32
+
33
+ - [Установка](#установка)
34
+ - [Быстрый старт](#быстрый-старт)
35
+ - [Как работает autograd](#как-работает-autograd)
36
+ - [API](#api)
37
+ - [Примеры](#примеры)
38
+ - [Тесты](#тесты)
39
+ - [Структура](#структура)
40
+ - [Чего нет](#чего-нет)
41
+ - [Ссылки](#ссылки)
42
+
43
+ ## Установка
44
+
45
+ ```bash
46
+ git clone https://github.com/IbrokhimN/tinytensor
47
+ cd tinytensor
48
+ pip install -e . # обычная установка
49
+ pip install -e .[dev] # плюс pytest, если хотите гонять тесты
50
+ ```
51
+
52
+ Или руками:
53
+
54
+ ```bash
55
+ pip install -r requirements.txt
56
+ ```
57
+
58
+ Зависимость одна - numpy.
59
+
60
+ ## Быстрый старт
61
+
62
+ ```python
63
+ from tinytensor.core.tensor import Tensor
64
+ from tinytensor.nn.linear import Linear
65
+ from tinytensor.nn.losses import MSELoss
66
+ from tinytensor.optim import SGD
67
+
68
+ model = Linear(in_features=1, out_features=1)
69
+ loss_fn = MSELoss()
70
+ optimizer = SGD(model.parameters(), lr=0.01)
71
+
72
+ x = Tensor([[1.0], [2.0], [3.0]])
73
+ y = Tensor([[3.0], [5.0], [7.0]]) # y = 2x + 1
74
+
75
+ for epoch in range(100):
76
+ optimizer.zero_grad()
77
+ pred = model(x)
78
+ loss = loss_fn(pred, y)
79
+ loss.backward()
80
+ optimizer.step()
81
+
82
+ print(model.weight.data, model.bias.data) # ~2.0, ~1.0
83
+ ```
84
+
85
+ Рабочие примеры целиком лежат в [`examples/`](examples/).
86
+
87
+ ## Как работает autograd
88
+
89
+ У каждого `Tensor` есть:
90
+
91
+ - `data` - сами значения (numpy-массив, всегда float32);
92
+ - `grad` - градиент, пока не посчитан - None;
93
+ - `_prev` - от каких тензоров он произошел (родители в графе);
94
+ - `_backward` - функция которая знает как раскидать градиент на родителей.
95
+
96
+ Когда считаете `z = f(x, y)`, по цепному правилу:
97
+
98
+ ```
99
+ dL/dx = dL/dz * dz/dx
100
+ dL/dy = dL/dz * dz/dy
101
+ ```
102
+
103
+ `backward()` строит топологический порядок графа (`tinytensor/core/autograd.py`),
104
+ ставит корню градиент = 1 и идет в обратном порядке, вызывая `_backward()`
105
+ у каждого узла. Ровно так же устроен micrograd Карпатова, только у него
106
+ даже покомпактнее:
107
+
108
+ - [Karpathy - micrograd](https://github.com/karpathy/micrograd) - реализация того же самого на ~100 строк, must see
109
+ - [CS231n: Backpropagation, Intuitions](https://cs231n.github.io/optimization-2/) - если нужно разложить backprop по полочкам
110
+ - [colah - Calculus on Computational Graphs](https://colah.github.io/posts/2015-08-Backprop/)
111
+
112
+ Если совсем в тему - есть видос Карпатова где он с нуля пишет micrograd и
113
+ объясняет каждую строчку: ["The spelled-out intro to neural networks and backpropagation"](https://www.youtube.com/watch?v=VMj-3S1tku0).
114
+ Собственно тут все то же самое, только на numpy и чуть пошире.
115
+
116
+ ### Формулы, которые реализованы в Tensor
117
+
118
+ | операция | вперед | производная |
119
+ |---|---|---|
120
+ | `a + b` | `a + b` | `dL/da += dL/dz`, `dL/db += dL/dz` (плюс схлопывание по broadcast-осям) |
121
+ | `a * b` | `a * b` | `dL/da += dL/dz * b`, `dL/db += dL/dz * a` |
122
+ | `a @ b` | matmul | `dL/da += dL/dz @ bᵀ`, `dL/db += aᵀ @ dL/dz` |
123
+ | `a ** p` | `aᵖ` | `dL/da += dL/dz * p * a^(p-1)` |
124
+ | ReLU | `max(0, x)` | 1 при x>0, иначе 0 |
125
+ | LeakyReLU | x или αx | 1 при x>0, иначе α |
126
+ | sigmoid | `1/(1+e⁻ˣ)` | `σ(x)*(1-σ(x))` |
127
+ | tanh | `tanh(x)` | `1 - tanh²(x)` |
128
+ | GELU | `0.5x(1+tanh(√(2/π)(x+0.044715x³)))` | см. [статью по GELU](https://arxiv.org/abs/1606.08415), формула там не самая короткая |
129
+
130
+ Про broadcasting и почему градиент иногда надо досуммировать обратно
131
+ (`_unbroadcast`) норм объясняют [правила broadcasting в numpy](https://numpy.org/doc/stable/user/basics.broadcasting.html).
132
+
133
+ ## API
134
+
135
+ ### Tensor
136
+
137
+ `tinytensor.core.tensor.Tensor` - главный класс. Есть `+ - * @ **`, `.sum()`,
138
+ активации `relu / leaky_relu / sigmoid / tanh / gelu`, ну и `.backward()`.
139
+
140
+ ### nn
141
+
142
+ - `Module` - от него наследуются все слои, `forward / parameters() / zero_grad()`, по духу как [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html);
143
+ - `Linear(in_features, out_features)` - обычный `y = xW + b`, веса инициализируются по [He/Kaiming init](https://arxiv.org/abs/1502.01852) (`std = sqrt(2/in_features)`);
144
+ - `ReLU, LeReLU, Sigmod, Tanh, GELU` - тонкие обертки над методами Tensor;
145
+ - `MSELoss` - `mean((pred - target)^2)`, банальщина.
146
+
147
+ ### optim
148
+
149
+ - `SGD(params, lr, momentum=0.0)` - обычный градиентный спуск, можно с моментом;
150
+ - `AdamW(params, lr, betas, eps, weight_decay)` - Adam с отдельным weight decay, см. [Loshchilov & Hutter](https://arxiv.org/abs/1711.05101) (в отличие от обычного [Adam](https://arxiv.org/abs/1412.6980), decay тут не лезет в градиент, а сразу режет веса).
151
+
152
+ ### data
153
+
154
+ - `Dataset / TensorDataset` - обертка над (x, y);
155
+ - `DataLoader` - бьет на батчи, можно с shuffle, мини-версия [`torch.utils.data.DataLoader`](https://pytorch.org/docs/stable/data.html).
156
+
157
+ ## Примеры
158
+
159
+ - [`examples/01_linear_regression.py`](examples/01_linear_regression.py) - линейная регрессия, Linear + MSELoss + SGD на `y = 3x + 2 + шум`.
160
+ - [`examples/02_mnist_mlp.py`](examples/02_mnist_mlp.py) - MLP (Linear -> ReLU -> Linear) с AdamW и DataLoader на синтетике в формате mnist (784 фичи, 10 классов). Настоящего mnist и загрузчиков датасетов тут нет, лень было тащить.
161
+
162
+ Как выглядит запуск вживую:
163
+
164
+ ```
165
+ $ python3 01_linear_regression.py
166
+ epoch 0 | loss 30.8016
167
+ epoch 180 | loss 0.2365
168
+ выученные параметры: weight ~ 2.995, bias ~ 1.996
169
+
170
+ $ python3 02_mnist_mlp.py
171
+ epoch 1/5 | avg loss 2.0998
172
+ epoch 5/5 | avg loss 0.0481
173
+ ```
174
+
175
+ ## Тесты
176
+
177
+ ```bash
178
+ pip install -e .[dev]
179
+ python3 -m pytest tests/ -v
180
+ ```
181
+
182
+ 47 штук, гоняют арифметику тензоров и broadcasting, autograd (накопление
183
+ градиента, топология, повторный backward), лоссы, оптимизаторы и
184
+ Dataset/DataLoader.
185
+
186
+ > Важно: запускать через pytest из корня репы (или после `pip install -e .`),
187
+ > а не `python3 test_x.py` из папки tests - иначе tinytensor просто не найдется.
188
+
189
+ ## Структура
190
+
191
+ ```
192
+ tinytensor/
193
+ ├── tinytensor/
194
+ │ ├── core/ # Tensor, autograd, ops
195
+ │ ├── nn/ # Module, Linear, активации, MSELoss
196
+ │ ├── optim/ # SGD, AdamW
197
+ │ ├── data/ # Dataset, DataLoader
198
+ │ ├── backends/ # заготовка под cuda, пока пусто
199
+ │ └── config.py # сид рандома
200
+ ├── examples/
201
+ ├── tests/
202
+ ├── setup.py
203
+ └── requirements.txt
204
+ ```
205
+
206
+ ## Чего нет
207
+
208
+ - Только numpy-backend, cuda_gpu.py пустой файл-заглушка.
209
+ - Нет кросс-энтропии, сверток, рекуррентных слоев, сохранения модели (см. ToDo в исходном плане проекта).
210
+ - backward не кэширует граф между вызовами, каждый раз строит топологию заново, как и в micrograd - никакой лени в духе pytorch тут нет.
211
+
212
+ ## Ссылки
213
+
214
+ - [Andrej Karpathy - micrograd (GitHub)](https://github.com/karpathy/micrograd) - основной референс для всего autograd
215
+ - [Andrej Karpathy - видео про backprop и micrograd](https://www.youtube.com/watch?v=VMj-3S1tku0)
216
+ - [CS231n - Backpropagation, Intuitions](https://cs231n.github.io/optimization-2/)
217
+ - [colah - Calculus on Computational Graphs](https://colah.github.io/posts/2015-08-Backprop/)
218
+ - [NumPy broadcasting rules](https://numpy.org/doc/stable/user/basics.broadcasting.html)
219
+ - [He et al. - инициализация весов](https://arxiv.org/abs/1502.01852)
220
+ - [Kingma & Ba - Adam](https://arxiv.org/abs/1412.6980)
221
+ - [Loshchilov & Hutter - AdamW](https://arxiv.org/abs/1711.05101)
222
+ - [Hendrycks & Gimpel - GELU](https://arxiv.org/abs/1606.08415)
223
+ - [PyTorch - torch.nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)
224
+ - [PyTorch - torch.utils.data.DataLoader](https://pytorch.org/docs/stable/data.html)
@@ -1,9 +1,12 @@
1
1
  import os
2
2
  import subprocess
3
3
  import pybind11
4
+ from pathlib import Path
4
5
  from setuptools import setup, find_packages, Extension
5
6
  from setuptools.command.build_ext import build_ext
6
7
 
8
+ long_description = Path(__file__).parent / "README.md"
9
+ long_description = long_description.read_text(encoding="utf-8") if long_description.exists() else ""
7
10
 
8
11
  def check_cuda():
9
12
  try:
@@ -12,7 +15,6 @@ def check_cuda():
12
15
  except (FileNotFoundError, subprocess.CalledProcessError):
13
16
  return False
14
17
 
15
-
16
18
  class CUDABuildExt(build_ext):
17
19
  def build_extensions(self):
18
20
  self.compiler.src_extensions.append('.cu')
@@ -36,15 +38,14 @@ class CUDABuildExt(build_ext):
36
38
  self.compiler._compile = custom_compile
37
39
  super().build_extensions()
38
40
 
39
-
40
41
  ext_modules = []
41
42
 
42
43
  if check_cuda():
43
44
  cuda_module = Extension(
44
45
  'tinytensor.cuda_ops',
45
46
  sources=[
46
- 'tinytensor/backends/cuda_gpu.cu',
47
- 'tinytensor/backends/cuda_binding.cpp'
47
+ 'tinytensor/backends/cuda_gpu.cu',
48
+ 'tinytensor/backends/cuda_binding.cpp'
48
49
  ],
49
50
  include_dirs=[
50
51
  pybind11.get_include(),
@@ -59,14 +60,18 @@ if check_cuda():
59
60
  }
60
61
  )
61
62
  ext_modules.append(cuda_module)
62
- print("CUDA найдена. Собираем cuBLAS бэкенд")
63
+ print("CUDA найдена! Собираем cuBLAS бэкенд...")
63
64
  else:
64
- print("CUDA не найдена. Сборка продолжится на CPU (NumPy)")
65
+ print("CUDA не найдена. Сборка продолжится на CPU (NumPy).")
65
66
 
66
67
  setup(
67
68
  name="pytinytensor",
68
- version="0.1.0",
69
+ version="0.1.1",
69
70
  description="мини ИИ фреймворк от IbrokimN ( github/IbrokhimN )",
71
+ long_description=long_description,
72
+ long_description_content_type="text/markdown",
73
+ author="IbrokhimN",
74
+ url="https://github.com/IbrokhimN/tinytensor",
70
75
  packages=find_packages(include=["tinytensor", "tinytensor.*"]),
71
76
  ext_modules=ext_modules,
72
77
  cmdclass={'build_ext': CUDABuildExt},
@@ -1,13 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: pytinytensor
3
- Version: 0.1.0
4
- Summary: мини ИИ фреймворк от IbrokimN ( github/IbrokhimN )
5
- Requires-Python: >=3.9
6
- Requires-Dist: numpy>=1.23
7
- Requires-Dist: pybind11>=2.10
8
- Provides-Extra: dev
9
- Requires-Dist: pytest>=7.0; extra == "dev"
10
- Dynamic: provides-extra
11
- Dynamic: requires-dist
12
- Dynamic: requires-python
13
- Dynamic: summary
@@ -1,13 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: pytinytensor
3
- Version: 0.1.0
4
- Summary: мини ИИ фреймворк от IbrokimN ( github/IbrokhimN )
5
- Requires-Python: >=3.9
6
- Requires-Dist: numpy>=1.23
7
- Requires-Dist: pybind11>=2.10
8
- Provides-Extra: dev
9
- Requires-Dist: pytest>=7.0; extra == "dev"
10
- Dynamic: provides-extra
11
- Dynamic: requires-dist
12
- Dynamic: requires-python
13
- Dynamic: summary
File without changes
File without changes