newch 0.2.0__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.
- newch-0.2.0/LICENSE +202 -0
- newch-0.2.0/MANIFEST.in +6 -0
- newch-0.2.0/NOTICE +8 -0
- newch-0.2.0/PKG-INFO +166 -0
- newch-0.2.0/README.md +137 -0
- newch-0.2.0/docs/FORMAT.md +26 -0
- newch-0.2.0/docs/PROGRESS.md +225 -0
- newch-0.2.0/docs/PUBLISHING.md +74 -0
- newch-0.2.0/engine/include/nc.h +325 -0
- newch-0.2.0/engine/src/autograd/autograd.c +103 -0
- newch-0.2.0/engine/src/autograd/gradcheck.c +41 -0
- newch-0.2.0/engine/src/core/ctx.c +265 -0
- newch-0.2.0/engine/src/core/io.c +161 -0
- newch-0.2.0/engine/src/core/nc_internal.h +225 -0
- newch-0.2.0/engine/src/core/tensor.c +402 -0
- newch-0.2.0/engine/src/kernels/dispatch.c +44 -0
- newch-0.2.0/engine/src/kernels/kernels.h +46 -0
- newch-0.2.0/engine/src/kernels/neon/kernels_neon.c +195 -0
- newch-0.2.0/engine/src/kernels/ref/kernels_ref.c +128 -0
- newch-0.2.0/engine/src/kernels/x86/kernels_avx2.c +262 -0
- newch-0.2.0/engine/src/nn/modules.c +172 -0
- newch-0.2.0/engine/src/ops/ops_conv.c +290 -0
- newch-0.2.0/engine/src/ops/ops_elementwise.c +250 -0
- newch-0.2.0/engine/src/ops/ops_linalg.c +158 -0
- newch-0.2.0/engine/src/ops/ops_nn.c +361 -0
- newch-0.2.0/engine/src/ops/ops_quant.c +113 -0
- newch-0.2.0/engine/src/ops/ops_reduce.c +136 -0
- newch-0.2.0/engine/src/ops/ops_shape.c +253 -0
- newch-0.2.0/engine/src/optim/optim.c +103 -0
- newch-0.2.0/engine/src/runtime/cpu_features.c +126 -0
- newch-0.2.0/engine/src/runtime/threadpool.c +231 -0
- newch-0.2.0/engine/tests/test_main.c +802 -0
- newch-0.2.0/newch/__init__.py +29 -0
- newch-0.2.0/newch/_lib.py +168 -0
- newch-0.2.0/newch/callbacks.py +91 -0
- newch-0.2.0/newch/data.py +227 -0
- newch-0.2.0/newch/net.py +449 -0
- newch-0.2.0/newch/optim.py +64 -0
- newch-0.2.0/newch/tensor.py +759 -0
- newch-0.2.0/newch/training.py +301 -0
- newch-0.2.0/newch.egg-info/PKG-INFO +166 -0
- newch-0.2.0/newch.egg-info/SOURCES.txt +49 -0
- newch-0.2.0/newch.egg-info/dependency_links.txt +1 -0
- newch-0.2.0/newch.egg-info/requires.txt +3 -0
- newch-0.2.0/newch.egg-info/top_level.txt +1 -0
- newch-0.2.0/pyproject.toml +41 -0
- newch-0.2.0/setup.cfg +4 -0
- newch-0.2.0/setup.py +50 -0
- newch-0.2.0/tests/test_features.py +253 -0
- newch-0.2.0/tests/test_python.py +252 -0
- newch-0.2.0/tools/build.py +125 -0
newch-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
newch-0.2.0/MANIFEST.in
ADDED
newch-0.2.0/NOTICE
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
newch
|
|
2
|
+
Copyright 2026 The newch authors
|
|
3
|
+
|
|
4
|
+
This product is licensed under the Apache License, Version 2.0 (see LICENSE).
|
|
5
|
+
|
|
6
|
+
Third-party algorithms:
|
|
7
|
+
- xoshiro256** and splitmix64 random number generators, by David Blackman
|
|
8
|
+
and Sebastiano Vigna (public domain, https://prng.di.unimi.it/).
|
newch-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: newch
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: A small machine-learning library for low-spec machines: PyTorch-style autograd, Keras-style fit, portable C engine
|
|
5
|
+
Author: The newch authors
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/dandmadp/newch
|
|
8
|
+
Project-URL: Source, https://github.com/dandmadp/newch
|
|
9
|
+
Project-URL: Issues, https://github.com/dandmadp/newch/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/dandmadp/newch/blob/main/docs/PROGRESS.md
|
|
11
|
+
Keywords: machine learning,deep learning,autograd,neural network,embedded,low-spec
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: C
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
20
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
21
|
+
Classifier: Operating System :: MacOS
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
License-File: NOTICE
|
|
26
|
+
Provides-Extra: numpy
|
|
27
|
+
Requires-Dist: numpy; extra == "numpy"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# newch
|
|
31
|
+
|
|
32
|
+
저사양 기기에서도 **학습**까지 할 수 있는 작은 머신러닝 라이브러리입니다. 엔진은 C11이고, Python에서는
|
|
33
|
+
PyTorch 스타일 텐서와 autograd, Keras 스타일 `compile`/`fit`을 씁니다. Python 의존성은 없습니다
|
|
34
|
+
(numpy가 있으면 사용합니다). 싱글보드 컴퓨터는 호환 대상 중 하나입니다.
|
|
35
|
+
|
|
36
|
+
- 네이티브 라이브러리 약 200KB (Windows), aarch64 리눅스용 약 90KB
|
|
37
|
+
- MNIST CNN: 1 에포크 18초, 테스트 정확도 98.1% (x86 PC, 디스크에서 스트리밍)
|
|
38
|
+
- 행렬곱: 멀티스레드 + AVX2로 numpy(BLAS)의 0.9~1.5배 시간
|
|
39
|
+
|
|
40
|
+
## 설치
|
|
41
|
+
|
|
42
|
+
```
|
|
43
|
+
pip install newch # Windows x86-64는 바로 설치, 그 밖의 플랫폼은 설치 중 엔진을 컴파일합니다
|
|
44
|
+
pip install "newch[numpy]" # numpy 연동까지
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
소스에서 설치할 때도 시스템 C 컴파일러는 필요 없습니다 (pip 패키지 `ziglang`을 씁니다).
|
|
48
|
+
저장소에서는 `pip install .`, 개발할 때는 `pip install ziglang` 후 `python tools/build.py`를 실행합니다.
|
|
49
|
+
라이선스는 Apache-2.0입니다 ([LICENSE](https://github.com/dandmadp/newch/blob/main/LICENSE), [NOTICE](https://github.com/dandmadp/newch/blob/main/NOTICE)).
|
|
50
|
+
|
|
51
|
+
## Python 사용 예
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import newch as nc
|
|
55
|
+
from newch import net
|
|
56
|
+
|
|
57
|
+
# Keras 스타일
|
|
58
|
+
model = nc.Sequential([
|
|
59
|
+
net.Conv2d(1, 16, 3, padding=1), net.BatchNorm2d(16), net.ReLU(), net.MaxPool2d(2),
|
|
60
|
+
net.Flatten(), net.Dropout(0.25), net.Linear(16 * 14 * 14, 10),
|
|
61
|
+
])
|
|
62
|
+
model.compile(optimizer="adam", loss="cross_entropy", metrics=["accuracy"])
|
|
63
|
+
model.summary()
|
|
64
|
+
history = model.fit(x, y, epochs=5, validation_split=0.1,
|
|
65
|
+
callbacks=[nc.callbacks.EarlyStopping(patience=2)])
|
|
66
|
+
loss, acc = model.evaluate(x_test, y_test)
|
|
67
|
+
model.save_weights("model.ncw") # 다른 기기에서 model.load_weights(...)
|
|
68
|
+
|
|
69
|
+
# PyTorch 스타일
|
|
70
|
+
opt = nc.optim.Adam(model.parameters(), lr=1e-3)
|
|
71
|
+
for xb, yb in loader:
|
|
72
|
+
loss = nc.cross_entropy(model(xb), yb)
|
|
73
|
+
opt.zero_grad(); loss.backward(); opt.step()
|
|
74
|
+
nc.step_end() # 이 스텝의 임시 텐서를 한 번에 해제
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
**RAM보다 큰 데이터셋:** 샘플을 디스크 파일에 저장하고 `FileArray`로 열면 배치 단위로만 읽습니다.
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
from newch.data import DataLoader, FileArray, TensorDataset
|
|
81
|
+
|
|
82
|
+
x = FileArray.create("x.bin", rows, row_shape=(1, 28, 28)) # 한 행씩 기록
|
|
83
|
+
y = FileArray.create("y.bin", labels, row_shape=(), dtype=nc.int32)
|
|
84
|
+
model.fit(DataLoader(TensorDataset(x, y), batch_size=64, shuffle=True), epochs=3)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
**PyTorch 가중치 가져오기:** 레이어 이름과 레이아웃이 같으므로 numpy로 바꿔서 넣으면 됩니다.
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
model.load_state_dict({k: v.numpy() for k, v in torch_model.state_dict().items()})
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
**int8 양자화 (추론):** `nc.quantize_(model)`은 모든 `Linear`를 int8 가중치로 바꿉니다 (가중치 메모리 1/4).
|
|
94
|
+
|
|
95
|
+
**스레드:** 기본값은 모든 코어입니다. `nc.set_default_context(nc.Context(threads=2))`로 바꿀 수 있습니다.
|
|
96
|
+
|
|
97
|
+
전체 예제는 [examples/mnist_cnn.py](https://github.com/dandmadp/newch/blob/main/examples/mnist_cnn.py)에 있습니다 (다운로드 → 디스크 변환 → 스트리밍 학습 → 저장 → 양자화).
|
|
98
|
+
|
|
99
|
+
PyTorch나 Keras와 이름이 같은 API는 동작도 같고, 의미가 다른 경우에는 다른 이름을 씁니다
|
|
100
|
+
(목록은 [docs/PROGRESS.md](https://github.com/dandmadp/newch/blob/main/docs/PROGRESS.md)의 "이름 규칙").
|
|
101
|
+
|
|
102
|
+
## C 사용 예
|
|
103
|
+
|
|
104
|
+
```c
|
|
105
|
+
nc_ctx *ctx = nc_init(&(nc_config){.threads = 0}); /* 0 = 모든 코어 */
|
|
106
|
+
nc_module *layers[] = {nc_linear(ctx, 2, 64, 1), nc_act(ctx, NC_ACT_RELU), nc_linear(ctx, 64, 3, 1)};
|
|
107
|
+
nc_module *model = nc_sequential(ctx, 3, layers);
|
|
108
|
+
nc_tensor *params[16];
|
|
109
|
+
int np = nc_parameters(model, params, 16);
|
|
110
|
+
nc_optim *opt = nc_adam(ctx, params, np, (nc_optim_opts){.lr = 1e-3f});
|
|
111
|
+
|
|
112
|
+
for (int step = 0; step < steps; step++) {
|
|
113
|
+
nc_tensor *x = nc_from_data(ctx, NC_F32, batch_x, 2, (int64_t[]){B, 2});
|
|
114
|
+
nc_tensor *y = nc_from_data(ctx, NC_I32, batch_y, 1, (int64_t[]){B});
|
|
115
|
+
nc_tensor *loss = nc_cross_entropy(nc_forward(model, x), y);
|
|
116
|
+
nc_optim_zero_grad(opt);
|
|
117
|
+
nc_backward(loss);
|
|
118
|
+
nc_optim_step(opt);
|
|
119
|
+
if (!nc_ok(ctx)) { puts(nc_error(ctx)); break; } /* 에러는 한 번에 확인 */
|
|
120
|
+
nc_step_end(ctx); /* 임시 텐서 전부 해제, O(1) */
|
|
121
|
+
}
|
|
122
|
+
const char *names[] = {"w", "b"};
|
|
123
|
+
nc_save(ctx, "model.ncw", 2, names, params);
|
|
124
|
+
nc_free_ctx(ctx);
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## 지원 플랫폼
|
|
128
|
+
|
|
129
|
+
| 타깃 (`tools/build.py --target`) | 대표 기기 | 커널 |
|
|
130
|
+
|---|---|---|
|
|
131
|
+
| `host` | 개발 PC (Windows / Linux / macOS) | x86: AVX2+FMA (런타임 감지), ARM: NEON |
|
|
132
|
+
| `aarch64`, `aarch64-static` | Pi 3/4/5, Orange Pi 5, RK35xx, Apple Silicon | NEON |
|
|
133
|
+
| `armv7`, `armv7-static` | Pi 2/3 (32비트 OS), 구형 Allwinner | NEON (런타임 확인) |
|
|
134
|
+
| `riscv64`, `riscv64-static` | VisionFive 2, Milk-V, BPI-F3 | 레퍼런스 (RVV 예정) |
|
|
135
|
+
|
|
136
|
+
`*-static`은 musl 정적 링크 바이너리라서 어떤 리눅스 기기에든 복사해서 바로 실행할 수 있습니다.
|
|
137
|
+
기기에서 직접 빌드할 때는 `cmake -B build && cmake --build build -j && ctest --test-dir build`.
|
|
138
|
+
|
|
139
|
+
## 핵심 설계
|
|
140
|
+
|
|
141
|
+
- **메모리:** 파라미터 등 영구 텐서와 스텝 아레나(활성값, 중간 그래디언트)를 나눕니다. `step_end()`가 아레나를 O(1)로
|
|
142
|
+
되돌리고, `trim()`이 남는 메모리를 OS에 반환합니다. Python에서는 영구 텐서를 마지막 참조가 사라질 때 자동으로 해제합니다
|
|
143
|
+
- **에러:** 연산은 abort하지 않습니다. 첫 에러를 기록하고 NULL을 전파하며, Python에서는 `NcError`가 됩니다
|
|
144
|
+
- **연산은 데이터로 기술:** 모든 연산이 `nc_op_def`(infer/view/forward/backward)로 등록되고 `nc__apply()`를 거칩니다
|
|
145
|
+
- **커널 디스패치:** 레퍼런스 테이블에서 시작해 CPU가 지원하는 계층(NEON, AVX2)이 항목별로 덮어씁니다.
|
|
146
|
+
`test_kernel_parity`가 모든 계층을 레퍼런스와 비교합니다
|
|
147
|
+
- **스레드:** 큰 GEMM만 행 또는 열 단위로 나눠 병렬 실행합니다. 출력 원소 하나는 스레드 하나가 계산하므로 결과가 스레드 수와
|
|
148
|
+
무관하게 비트 단위로 같습니다
|
|
149
|
+
|
|
150
|
+
## 디렉터리
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
engine/include/nc.h 공개 C API (NC_API로 표시된 함수만 공유 라이브러리에서 노출)
|
|
154
|
+
engine/src/core/ 컨텍스트, 메모리, 텐서, 레지스트리, 파일 입출력
|
|
155
|
+
engine/src/autograd/ nc__apply, 테이프, backward, gradcheck
|
|
156
|
+
engine/src/ops/ elementwise, linalg, reduce, shape, nn, conv, quant
|
|
157
|
+
engine/src/kernels/ 디스패치, ref/, neon/, x86/(AVX2)
|
|
158
|
+
engine/src/runtime/ CPU 감지, 스레드 풀
|
|
159
|
+
engine/tests/ C 테스트
|
|
160
|
+
newch/ Python 패키지 (tensor, net, optim, data, training, callbacks)
|
|
161
|
+
tests/ Python 테스트
|
|
162
|
+
examples/ train_spiral.c, mnist_cnn.py
|
|
163
|
+
docs/ PROGRESS.md (작업 요약), FORMAT.md (가중치 파일 포맷)
|
|
164
|
+
tools/build.py zig cc 기반 멀티 타깃 빌드
|
|
165
|
+
.github/workflows/ci.yml CI (Windows/Linux/macOS, QEMU ARM·RISC-V, 휠)
|
|
166
|
+
```
|
newch-0.2.0/README.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# newch
|
|
2
|
+
|
|
3
|
+
저사양 기기에서도 **학습**까지 할 수 있는 작은 머신러닝 라이브러리입니다. 엔진은 C11이고, Python에서는
|
|
4
|
+
PyTorch 스타일 텐서와 autograd, Keras 스타일 `compile`/`fit`을 씁니다. Python 의존성은 없습니다
|
|
5
|
+
(numpy가 있으면 사용합니다). 싱글보드 컴퓨터는 호환 대상 중 하나입니다.
|
|
6
|
+
|
|
7
|
+
- 네이티브 라이브러리 약 200KB (Windows), aarch64 리눅스용 약 90KB
|
|
8
|
+
- MNIST CNN: 1 에포크 18초, 테스트 정확도 98.1% (x86 PC, 디스크에서 스트리밍)
|
|
9
|
+
- 행렬곱: 멀티스레드 + AVX2로 numpy(BLAS)의 0.9~1.5배 시간
|
|
10
|
+
|
|
11
|
+
## 설치
|
|
12
|
+
|
|
13
|
+
```
|
|
14
|
+
pip install newch # Windows x86-64는 바로 설치, 그 밖의 플랫폼은 설치 중 엔진을 컴파일합니다
|
|
15
|
+
pip install "newch[numpy]" # numpy 연동까지
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
소스에서 설치할 때도 시스템 C 컴파일러는 필요 없습니다 (pip 패키지 `ziglang`을 씁니다).
|
|
19
|
+
저장소에서는 `pip install .`, 개발할 때는 `pip install ziglang` 후 `python tools/build.py`를 실행합니다.
|
|
20
|
+
라이선스는 Apache-2.0입니다 ([LICENSE](https://github.com/dandmadp/newch/blob/main/LICENSE), [NOTICE](https://github.com/dandmadp/newch/blob/main/NOTICE)).
|
|
21
|
+
|
|
22
|
+
## Python 사용 예
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
import newch as nc
|
|
26
|
+
from newch import net
|
|
27
|
+
|
|
28
|
+
# Keras 스타일
|
|
29
|
+
model = nc.Sequential([
|
|
30
|
+
net.Conv2d(1, 16, 3, padding=1), net.BatchNorm2d(16), net.ReLU(), net.MaxPool2d(2),
|
|
31
|
+
net.Flatten(), net.Dropout(0.25), net.Linear(16 * 14 * 14, 10),
|
|
32
|
+
])
|
|
33
|
+
model.compile(optimizer="adam", loss="cross_entropy", metrics=["accuracy"])
|
|
34
|
+
model.summary()
|
|
35
|
+
history = model.fit(x, y, epochs=5, validation_split=0.1,
|
|
36
|
+
callbacks=[nc.callbacks.EarlyStopping(patience=2)])
|
|
37
|
+
loss, acc = model.evaluate(x_test, y_test)
|
|
38
|
+
model.save_weights("model.ncw") # 다른 기기에서 model.load_weights(...)
|
|
39
|
+
|
|
40
|
+
# PyTorch 스타일
|
|
41
|
+
opt = nc.optim.Adam(model.parameters(), lr=1e-3)
|
|
42
|
+
for xb, yb in loader:
|
|
43
|
+
loss = nc.cross_entropy(model(xb), yb)
|
|
44
|
+
opt.zero_grad(); loss.backward(); opt.step()
|
|
45
|
+
nc.step_end() # 이 스텝의 임시 텐서를 한 번에 해제
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
**RAM보다 큰 데이터셋:** 샘플을 디스크 파일에 저장하고 `FileArray`로 열면 배치 단위로만 읽습니다.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from newch.data import DataLoader, FileArray, TensorDataset
|
|
52
|
+
|
|
53
|
+
x = FileArray.create("x.bin", rows, row_shape=(1, 28, 28)) # 한 행씩 기록
|
|
54
|
+
y = FileArray.create("y.bin", labels, row_shape=(), dtype=nc.int32)
|
|
55
|
+
model.fit(DataLoader(TensorDataset(x, y), batch_size=64, shuffle=True), epochs=3)
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
**PyTorch 가중치 가져오기:** 레이어 이름과 레이아웃이 같으므로 numpy로 바꿔서 넣으면 됩니다.
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
model.load_state_dict({k: v.numpy() for k, v in torch_model.state_dict().items()})
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**int8 양자화 (추론):** `nc.quantize_(model)`은 모든 `Linear`를 int8 가중치로 바꿉니다 (가중치 메모리 1/4).
|
|
65
|
+
|
|
66
|
+
**스레드:** 기본값은 모든 코어입니다. `nc.set_default_context(nc.Context(threads=2))`로 바꿀 수 있습니다.
|
|
67
|
+
|
|
68
|
+
전체 예제는 [examples/mnist_cnn.py](https://github.com/dandmadp/newch/blob/main/examples/mnist_cnn.py)에 있습니다 (다운로드 → 디스크 변환 → 스트리밍 학습 → 저장 → 양자화).
|
|
69
|
+
|
|
70
|
+
PyTorch나 Keras와 이름이 같은 API는 동작도 같고, 의미가 다른 경우에는 다른 이름을 씁니다
|
|
71
|
+
(목록은 [docs/PROGRESS.md](https://github.com/dandmadp/newch/blob/main/docs/PROGRESS.md)의 "이름 규칙").
|
|
72
|
+
|
|
73
|
+
## C 사용 예
|
|
74
|
+
|
|
75
|
+
```c
|
|
76
|
+
nc_ctx *ctx = nc_init(&(nc_config){.threads = 0}); /* 0 = 모든 코어 */
|
|
77
|
+
nc_module *layers[] = {nc_linear(ctx, 2, 64, 1), nc_act(ctx, NC_ACT_RELU), nc_linear(ctx, 64, 3, 1)};
|
|
78
|
+
nc_module *model = nc_sequential(ctx, 3, layers);
|
|
79
|
+
nc_tensor *params[16];
|
|
80
|
+
int np = nc_parameters(model, params, 16);
|
|
81
|
+
nc_optim *opt = nc_adam(ctx, params, np, (nc_optim_opts){.lr = 1e-3f});
|
|
82
|
+
|
|
83
|
+
for (int step = 0; step < steps; step++) {
|
|
84
|
+
nc_tensor *x = nc_from_data(ctx, NC_F32, batch_x, 2, (int64_t[]){B, 2});
|
|
85
|
+
nc_tensor *y = nc_from_data(ctx, NC_I32, batch_y, 1, (int64_t[]){B});
|
|
86
|
+
nc_tensor *loss = nc_cross_entropy(nc_forward(model, x), y);
|
|
87
|
+
nc_optim_zero_grad(opt);
|
|
88
|
+
nc_backward(loss);
|
|
89
|
+
nc_optim_step(opt);
|
|
90
|
+
if (!nc_ok(ctx)) { puts(nc_error(ctx)); break; } /* 에러는 한 번에 확인 */
|
|
91
|
+
nc_step_end(ctx); /* 임시 텐서 전부 해제, O(1) */
|
|
92
|
+
}
|
|
93
|
+
const char *names[] = {"w", "b"};
|
|
94
|
+
nc_save(ctx, "model.ncw", 2, names, params);
|
|
95
|
+
nc_free_ctx(ctx);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## 지원 플랫폼
|
|
99
|
+
|
|
100
|
+
| 타깃 (`tools/build.py --target`) | 대표 기기 | 커널 |
|
|
101
|
+
|---|---|---|
|
|
102
|
+
| `host` | 개발 PC (Windows / Linux / macOS) | x86: AVX2+FMA (런타임 감지), ARM: NEON |
|
|
103
|
+
| `aarch64`, `aarch64-static` | Pi 3/4/5, Orange Pi 5, RK35xx, Apple Silicon | NEON |
|
|
104
|
+
| `armv7`, `armv7-static` | Pi 2/3 (32비트 OS), 구형 Allwinner | NEON (런타임 확인) |
|
|
105
|
+
| `riscv64`, `riscv64-static` | VisionFive 2, Milk-V, BPI-F3 | 레퍼런스 (RVV 예정) |
|
|
106
|
+
|
|
107
|
+
`*-static`은 musl 정적 링크 바이너리라서 어떤 리눅스 기기에든 복사해서 바로 실행할 수 있습니다.
|
|
108
|
+
기기에서 직접 빌드할 때는 `cmake -B build && cmake --build build -j && ctest --test-dir build`.
|
|
109
|
+
|
|
110
|
+
## 핵심 설계
|
|
111
|
+
|
|
112
|
+
- **메모리:** 파라미터 등 영구 텐서와 스텝 아레나(활성값, 중간 그래디언트)를 나눕니다. `step_end()`가 아레나를 O(1)로
|
|
113
|
+
되돌리고, `trim()`이 남는 메모리를 OS에 반환합니다. Python에서는 영구 텐서를 마지막 참조가 사라질 때 자동으로 해제합니다
|
|
114
|
+
- **에러:** 연산은 abort하지 않습니다. 첫 에러를 기록하고 NULL을 전파하며, Python에서는 `NcError`가 됩니다
|
|
115
|
+
- **연산은 데이터로 기술:** 모든 연산이 `nc_op_def`(infer/view/forward/backward)로 등록되고 `nc__apply()`를 거칩니다
|
|
116
|
+
- **커널 디스패치:** 레퍼런스 테이블에서 시작해 CPU가 지원하는 계층(NEON, AVX2)이 항목별로 덮어씁니다.
|
|
117
|
+
`test_kernel_parity`가 모든 계층을 레퍼런스와 비교합니다
|
|
118
|
+
- **스레드:** 큰 GEMM만 행 또는 열 단위로 나눠 병렬 실행합니다. 출력 원소 하나는 스레드 하나가 계산하므로 결과가 스레드 수와
|
|
119
|
+
무관하게 비트 단위로 같습니다
|
|
120
|
+
|
|
121
|
+
## 디렉터리
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
engine/include/nc.h 공개 C API (NC_API로 표시된 함수만 공유 라이브러리에서 노출)
|
|
125
|
+
engine/src/core/ 컨텍스트, 메모리, 텐서, 레지스트리, 파일 입출력
|
|
126
|
+
engine/src/autograd/ nc__apply, 테이프, backward, gradcheck
|
|
127
|
+
engine/src/ops/ elementwise, linalg, reduce, shape, nn, conv, quant
|
|
128
|
+
engine/src/kernels/ 디스패치, ref/, neon/, x86/(AVX2)
|
|
129
|
+
engine/src/runtime/ CPU 감지, 스레드 풀
|
|
130
|
+
engine/tests/ C 테스트
|
|
131
|
+
newch/ Python 패키지 (tensor, net, optim, data, training, callbacks)
|
|
132
|
+
tests/ Python 테스트
|
|
133
|
+
examples/ train_spiral.c, mnist_cnn.py
|
|
134
|
+
docs/ PROGRESS.md (작업 요약), FORMAT.md (가중치 파일 포맷)
|
|
135
|
+
tools/build.py zig cc 기반 멀티 타깃 빌드
|
|
136
|
+
.github/workflows/ci.yml CI (Windows/Linux/macOS, QEMU ARM·RISC-V, 휠)
|
|
137
|
+
```
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# NCW1 텐서 파일 포맷
|
|
2
|
+
|
|
3
|
+
`nc_save` / `nc_load` (C), `save_tensors` / `load_tensors`, `save_weights` / `load_weights` (Python)가 쓰는 포맷입니다.
|
|
4
|
+
모든 정수는 리틀 엔디언입니다.
|
|
5
|
+
|
|
6
|
+
```
|
|
7
|
+
offset 크기 내용
|
|
8
|
+
0 4 매직 "NCW1"
|
|
9
|
+
4 u32 버전 (1)
|
|
10
|
+
8 u32 엔트리 수 n
|
|
11
|
+
12 ... 엔트리 n개
|
|
12
|
+
|
|
13
|
+
엔트리:
|
|
14
|
+
u32 이름 길이 L (바이트, 최대 4096)
|
|
15
|
+
L 이름 (UTF-8, 널 문자 없음)
|
|
16
|
+
u32 dtype: 0 = f32, 1 = i32, 3 = i8
|
|
17
|
+
u32 차원 수 d (최대 6)
|
|
18
|
+
i64 × d shape
|
|
19
|
+
u64 데이터 바이트 수 B (= 원소 수 × dtype 크기)
|
|
20
|
+
B 데이터 (row-major, 연속)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
- 이름은 `state_dict()` 키입니다 (`0.weight`, `1.running_mean` 등, PyTorch와 같은 규칙)
|
|
24
|
+
- 읽는 쪽은 요청하지 않은 엔트리를 건너뛰므로, 파일에 추가 텐서가 있어도 됩니다
|
|
25
|
+
- `nc_load`는 이름이 없거나 dtype/shape가 다르면 에러를 냅니다. Python `load_weights`는 `load_state_dict(strict=True)`와 같은 규칙입니다
|
|
26
|
+
- 양자화된 `Linear`는 `weight`(i8 `[out, in]`), `scale`(f32 `[out]`), `bias`(f32 `[out]`)로 저장됩니다
|