livnn 0.0.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.
- livnn-0.0.1/PKG-INFO +9 -0
- livnn-0.0.1/livnn/__init__.py +0 -0
- livnn-0.0.1/livnn/activation.py +92 -0
- livnn-0.0.1/livnn/core.pxd +131 -0
- livnn-0.0.1/livnn/core.pyx +424 -0
- livnn-0.0.1/livnn/dataset.py +16 -0
- livnn-0.0.1/livnn/dataset_base.pxd +39 -0
- livnn-0.0.1/livnn/dataset_base.pyx +143 -0
- livnn-0.0.1/livnn/layer.py +178 -0
- livnn-0.0.1/livnn/layer_base.py +237 -0
- livnn-0.0.1/livnn/loss.py +52 -0
- livnn-0.0.1/livnn/nn.py +166 -0
- livnn-0.0.1/livnn/optim.py +68 -0
- livnn-0.0.1/livnn/tensor.py +115 -0
- livnn-0.0.1/livnn/tensor_base.pxd +48 -0
- livnn-0.0.1/livnn/tensor_base.pyx +167 -0
- livnn-0.0.1/livnn.egg-info/PKG-INFO +9 -0
- livnn-0.0.1/livnn.egg-info/SOURCES.txt +25 -0
- livnn-0.0.1/livnn.egg-info/dependency_links.txt +1 -0
- livnn-0.0.1/livnn.egg-info/top_level.txt +1 -0
- livnn-0.0.1/pyproject.toml +60 -0
- livnn-0.0.1/setup.cfg +4 -0
- livnn-0.0.1/tests/test_dataset.py +33 -0
- livnn-0.0.1/tests/test_layer.py +53 -0
- livnn-0.0.1/tests/test_nn.py +229 -0
- livnn-0.0.1/tests/test_storage.py +44 -0
- livnn-0.0.1/tests/test_tensor.py +120 -0
livnn-0.0.1/PKG-INFO
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: livnn
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: livnn - is a tiny neural network (NN) framework and library
|
|
5
|
+
License-Expression: BSD-2-Clause
|
|
6
|
+
Project-URL: github, https://github.com/rmind/livnn
|
|
7
|
+
Keywords: neural network,cnn
|
|
8
|
+
Requires-Python: >=3.11
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
File without changes
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Use is subject to license terms, as specified in the LICENSE file.
|
|
3
|
+
#
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
from livnn.core import ActivationID, LayerType
|
|
8
|
+
from livnn.layer import Layer
|
|
9
|
+
|
|
10
|
+
#
|
|
11
|
+
# Activation pseudo-layers.
|
|
12
|
+
#
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Sigmoid(Layer):
|
|
16
|
+
"""
|
|
17
|
+
Sigmoid, the standard logistic function: transforms a continuous real
|
|
18
|
+
number into the range of (0, 1).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, label: Optional[str] = None):
|
|
22
|
+
super().__init__(
|
|
23
|
+
LayerType.ACTIVATION,
|
|
24
|
+
activation=ActivationID.SIGMOID,
|
|
25
|
+
label=label,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Tanh(Layer):
|
|
30
|
+
"""
|
|
31
|
+
Hyperbolic tangent function.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, label: Optional[str] = None):
|
|
35
|
+
super().__init__(
|
|
36
|
+
LayerType.ACTIVATION,
|
|
37
|
+
activation=ActivationID.TANH,
|
|
38
|
+
label=label,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SiLU(Layer):
|
|
43
|
+
"""
|
|
44
|
+
Sigmoid-weighted linear unit (SiLU).
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(self, label: Optional[str] = None):
|
|
48
|
+
super().__init__(
|
|
49
|
+
LayerType.ACTIVATION,
|
|
50
|
+
activation=ActivationID.SILU,
|
|
51
|
+
label=label,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ReLU(Layer):
|
|
56
|
+
"""
|
|
57
|
+
Rectified Linear Unit (ReLU): simply a threshold at zero.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(self, label: Optional[str] = None):
|
|
61
|
+
super().__init__(
|
|
62
|
+
LayerType.ACTIVATION,
|
|
63
|
+
activation=ActivationID.RELU,
|
|
64
|
+
label=label,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class LeakyReLU(Layer):
|
|
69
|
+
"""
|
|
70
|
+
Leaky ReLU: give a small positive slope for negative inputs, instead
|
|
71
|
+
of cutting them off at zero.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(self, label: Optional[str] = None):
|
|
75
|
+
super().__init__(
|
|
76
|
+
LayerType.ACTIVATION,
|
|
77
|
+
activation=ActivationID.LEAKY_RELU,
|
|
78
|
+
label=label,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class SELU(Layer):
|
|
83
|
+
"""
|
|
84
|
+
SELU: Scaled Exponential Linear Unit.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
def __init__(self, label: Optional[str] = None):
|
|
88
|
+
super().__init__(
|
|
89
|
+
LayerType.ACTIVATION,
|
|
90
|
+
activation=ActivationID.SELU,
|
|
91
|
+
label=label,
|
|
92
|
+
)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright (c) 2026 Mindaugas Rasiukevicius <rmind at noxt eu>
|
|
3
|
+
# All rights reserved.
|
|
4
|
+
#
|
|
5
|
+
# Use is subject to license terms, as specified in the LICENSE file.
|
|
6
|
+
#
|
|
7
|
+
|
|
8
|
+
from libc.string cimport memset
|
|
9
|
+
from libc.stdint cimport uint32_t
|
|
10
|
+
from libcpp cimport bool
|
|
11
|
+
|
|
12
|
+
from livnn.tensor_base cimport tensor_t, TensorBase
|
|
13
|
+
from livnn.dataset_base cimport dataset_t
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
cdef extern from "<livnn/nn.h>":
|
|
17
|
+
ctypedef enum activation_id_t:
|
|
18
|
+
FUNC_NONE
|
|
19
|
+
FUNC_SIGMOID
|
|
20
|
+
FUNC_TANH
|
|
21
|
+
FUNC_SILU
|
|
22
|
+
FUNC_RELU
|
|
23
|
+
FUNC_LEAKY_RELU
|
|
24
|
+
FUNC_SELU
|
|
25
|
+
|
|
26
|
+
ctypedef enum lossfunc_id_t:
|
|
27
|
+
L_NONE
|
|
28
|
+
L_BINARY_CROSS_ENTROPY
|
|
29
|
+
L_MEAN_SQUARED_ERROR
|
|
30
|
+
|
|
31
|
+
ctypedef enum optimizer_id_t:
|
|
32
|
+
OPTIM_NONE
|
|
33
|
+
OPTIM_SGD
|
|
34
|
+
OPTIM_ADAMW
|
|
35
|
+
|
|
36
|
+
ctypedef enum weight_init_func_t:
|
|
37
|
+
WI_NONE
|
|
38
|
+
WI_GLOROT_UNIFORM
|
|
39
|
+
WI_KAIMING_NORMAL
|
|
40
|
+
|
|
41
|
+
ctypedef struct weight_init_t:
|
|
42
|
+
weight_init_func_t param_init
|
|
43
|
+
|
|
44
|
+
ctypedef struct layer_spec_t:
|
|
45
|
+
char *type
|
|
46
|
+
char *label
|
|
47
|
+
|
|
48
|
+
const weight_init_t *weight_init
|
|
49
|
+
|
|
50
|
+
# Convolutional layer:
|
|
51
|
+
unsigned kernel_size
|
|
52
|
+
unsigned filters
|
|
53
|
+
int padding
|
|
54
|
+
unsigned stride
|
|
55
|
+
|
|
56
|
+
# Linear:
|
|
57
|
+
unsigned outputs
|
|
58
|
+
|
|
59
|
+
# Batch normalization:
|
|
60
|
+
float decay
|
|
61
|
+
float epsilon
|
|
62
|
+
bool force_stats_calc
|
|
63
|
+
|
|
64
|
+
# Activation function:
|
|
65
|
+
activation_id_t activation
|
|
66
|
+
|
|
67
|
+
# Aggregations and scalar operations:
|
|
68
|
+
char *operation
|
|
69
|
+
float c
|
|
70
|
+
|
|
71
|
+
# Loss function:
|
|
72
|
+
lossfunc_id_t loss
|
|
73
|
+
|
|
74
|
+
ctypedef struct layer_links_t:
|
|
75
|
+
unsigned layer
|
|
76
|
+
int links4[4]
|
|
77
|
+
const int *links
|
|
78
|
+
|
|
79
|
+
ctypedef struct optim_spec_t:
|
|
80
|
+
optimizer_id_t algo
|
|
81
|
+
float learning_rate
|
|
82
|
+
float l2_reg_strength
|
|
83
|
+
float sgd_momentum "sgd.momentum"
|
|
84
|
+
float adamw_weight_decay "adamw.weight_decay"
|
|
85
|
+
float adamw_beta1 "adamw.beta1"
|
|
86
|
+
float adamw_beta2 "adamw.beta2"
|
|
87
|
+
float adamw_epsilon "adamw.epsilon"
|
|
88
|
+
bool adamw_coupled "adamw.coupled"
|
|
89
|
+
|
|
90
|
+
ctypedef struct nn_spec_t:
|
|
91
|
+
uint32_t flags
|
|
92
|
+
unsigned input_width "input.width"
|
|
93
|
+
unsigned input_height "input.height"
|
|
94
|
+
unsigned input_channels "input.channels"
|
|
95
|
+
unsigned training_batch_size "training.batch_size"
|
|
96
|
+
unsigned training_epochs "training.epochs"
|
|
97
|
+
optim_spec_t optimizer "training.optimizer"
|
|
98
|
+
const layer_spec_t *layers
|
|
99
|
+
size_t nlayers
|
|
100
|
+
const layer_links_t *links
|
|
101
|
+
size_t nlinks
|
|
102
|
+
|
|
103
|
+
ctypedef struct nn_t
|
|
104
|
+
ctypedef struct layer_t
|
|
105
|
+
|
|
106
|
+
nn_t *nn_create(const nn_spec_t *)
|
|
107
|
+
void nn_destroy(nn_t *)
|
|
108
|
+
int nn_init(nn_t *, bool)
|
|
109
|
+
|
|
110
|
+
int nn_load(nn_t *, const char *)
|
|
111
|
+
int nn_save(nn_t *, const char *)
|
|
112
|
+
|
|
113
|
+
int nn_run(nn_t *, tensor_t *)
|
|
114
|
+
int nn_train(nn_t *, dataset_t *)
|
|
115
|
+
|
|
116
|
+
int nn_feed_forward(nn_t *, layer_t *, tensor_t *)
|
|
117
|
+
int nn_backprop(nn_t *, layer_t *, tensor_t *)
|
|
118
|
+
|
|
119
|
+
layer_t *nn_lookup_layer(nn_t *, unsigned)
|
|
120
|
+
tensor_t *layer_get_output(const layer_t *)
|
|
121
|
+
tensor_t *layer_get_gradient(const layer_t *, unsigned)
|
|
122
|
+
tensor_t *layer_get_weights(const layer_t *, unsigned)
|
|
123
|
+
tensor_t *layer_get_local_grads(const layer_t *, unsigned)
|
|
124
|
+
|
|
125
|
+
ctypedef enum nn_err_t:
|
|
126
|
+
NN_ERR_SUCCESS
|
|
127
|
+
NN_ERR_FATAL
|
|
128
|
+
NN_ERR_SYSTEM
|
|
129
|
+
NN_ERR_INVALID
|
|
130
|
+
|
|
131
|
+
nn_err_t nn_get_error(const nn_t *, const char **)
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright (c) 2026 Mindaugas Rasiukevicius <rmind at noxt eu>
|
|
3
|
+
# All rights reserved.
|
|
4
|
+
#
|
|
5
|
+
# Use is subject to license terms, as specified in the LICENSE file.
|
|
6
|
+
#
|
|
7
|
+
|
|
8
|
+
import cython
|
|
9
|
+
from cpython.mem cimport PyMem_Malloc, PyMem_Free
|
|
10
|
+
from typing import Optional
|
|
11
|
+
from enum import IntEnum, StrEnum
|
|
12
|
+
|
|
13
|
+
from libc.string cimport memcpy, memset
|
|
14
|
+
from libc.stdint cimport uintptr_t
|
|
15
|
+
from libc.errno cimport errno
|
|
16
|
+
from libcpp cimport bool
|
|
17
|
+
|
|
18
|
+
from os import strerror
|
|
19
|
+
|
|
20
|
+
from livnn.tensor_base cimport TensorBase
|
|
21
|
+
from livnn.dataset_base cimport DatasetBase
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class LivnnFatalError(Exception):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class LivnnSystemError(OSError):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class LivnnInvalidValueError(ValueError):
|
|
33
|
+
pass
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
cdef inline void *pymalloc(size_t n) except NULL:
|
|
37
|
+
cdef void *p = PyMem_Malloc(n)
|
|
38
|
+
if p is NULL:
|
|
39
|
+
raise MemoryError()
|
|
40
|
+
return p
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class LayerType(StrEnum):
|
|
44
|
+
AGGREGATION = "aggregation"
|
|
45
|
+
SCALAR = "scalar"
|
|
46
|
+
CONV2D = "conv2d"
|
|
47
|
+
LINEAR = "linear"
|
|
48
|
+
BATCH_NORM = "batch-norm"
|
|
49
|
+
ACTIVATION = "activation"
|
|
50
|
+
MAX_POOL = "max-pool"
|
|
51
|
+
AVG_POOL = "avg-pool"
|
|
52
|
+
SOFTMAX_CCE_LOSS = "softmax-loss"
|
|
53
|
+
SIGMOID_BCE_LOSS = "sigmoid-bce-loss",
|
|
54
|
+
LOSS = "loss"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class WeightInitID(IntEnum):
|
|
58
|
+
GLOROT_UNIFORM = WI_GLOROT_UNIFORM
|
|
59
|
+
KAIMING_NORMAL = WI_KAIMING_NORMAL
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@cython.final
|
|
63
|
+
cdef class ActivationID:
|
|
64
|
+
SIGMOID = FUNC_SIGMOID
|
|
65
|
+
TANH = FUNC_TANH
|
|
66
|
+
SILU = FUNC_SILU
|
|
67
|
+
RELU = FUNC_RELU
|
|
68
|
+
LEAKY_RELU = FUNC_LEAKY_RELU
|
|
69
|
+
SELU = FUNC_SELU
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@cython.final
|
|
73
|
+
cdef class LossFuncID:
|
|
74
|
+
BINARY_CROSS_ENTROPY = L_BINARY_CROSS_ENTROPY
|
|
75
|
+
MEAN_SQUARED_ERROR = L_MEAN_SQUARED_ERROR
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@cython.final
|
|
79
|
+
cdef class OptimizerID:
|
|
80
|
+
SGD = OPTIM_SGD
|
|
81
|
+
ADAMW = OPTIM_ADAMW
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@cython.final
|
|
85
|
+
cdef class OptimSpec:
|
|
86
|
+
cdef optim_spec_t spec
|
|
87
|
+
|
|
88
|
+
def __cinit__(
|
|
89
|
+
self,
|
|
90
|
+
algo: int,
|
|
91
|
+
learning_rate: Optional[float] = None,
|
|
92
|
+
l2_reg_strength: Optional[float] = None,
|
|
93
|
+
sgd_momentum: Optional[float] = None,
|
|
94
|
+
adamw_weight_decay: Optional[float] = None,
|
|
95
|
+
adamw_beta1: Optional[float] = None,
|
|
96
|
+
adamw_beta2: Optional[float] = None,
|
|
97
|
+
adamw_epsilon: Optional[float] = None,
|
|
98
|
+
adamw_coupled: Optional[bool] = None,
|
|
99
|
+
):
|
|
100
|
+
memset(&self.spec, 0, sizeof(optim_spec_t))
|
|
101
|
+
self.spec.algo = algo
|
|
102
|
+
|
|
103
|
+
if learning_rate is not None:
|
|
104
|
+
self.spec.learning_rate = learning_rate
|
|
105
|
+
|
|
106
|
+
if l2_reg_strength is not None:
|
|
107
|
+
self.spec.l2_reg_strength = l2_reg_strength
|
|
108
|
+
|
|
109
|
+
if sgd_momentum is not None:
|
|
110
|
+
self.spec.sgd_momentum = sgd_momentum
|
|
111
|
+
|
|
112
|
+
if adamw_weight_decay is not None:
|
|
113
|
+
self.spec.adamw_weight_decay = adamw_weight_decay
|
|
114
|
+
|
|
115
|
+
if adamw_beta1 is not None:
|
|
116
|
+
self.spec.adamw_beta1 = adamw_beta1
|
|
117
|
+
|
|
118
|
+
if adamw_beta2 is not None:
|
|
119
|
+
self.spec.adamw_beta2 = adamw_beta2
|
|
120
|
+
|
|
121
|
+
if adamw_epsilon is not None:
|
|
122
|
+
self.spec.adamw_epsilon = adamw_epsilon
|
|
123
|
+
|
|
124
|
+
if adamw_coupled is not None:
|
|
125
|
+
self.spec.adamw_coupled = adamw_coupled
|
|
126
|
+
|
|
127
|
+
cdef const optim_spec_t *getptr(self):
|
|
128
|
+
return &self.spec
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@cython.final
|
|
132
|
+
cdef class LayerSpec:
|
|
133
|
+
cdef layer_spec_t spec
|
|
134
|
+
cdef weight_init_t weight_init
|
|
135
|
+
cdef int index
|
|
136
|
+
|
|
137
|
+
# Store copies
|
|
138
|
+
cdef bytes _type
|
|
139
|
+
cdef bytes _label
|
|
140
|
+
cdef bytes _operation
|
|
141
|
+
|
|
142
|
+
def __cinit__(
|
|
143
|
+
self,
|
|
144
|
+
type: str | LayerType,
|
|
145
|
+
label: Optional[str] = None,
|
|
146
|
+
weight_init: Optional[WeightInitID] = None,
|
|
147
|
+
kernel_size: Optional[int] = None,
|
|
148
|
+
filters: Optional[int] = None,
|
|
149
|
+
padding: Optional[int] = None,
|
|
150
|
+
stride: Optional[int] = None,
|
|
151
|
+
outputs: Optional[int] = None,
|
|
152
|
+
decay: Optional[float] = None,
|
|
153
|
+
epsilon: Optional[float] = None,
|
|
154
|
+
force_stats_calc: Optional[bool] = None,
|
|
155
|
+
activation: Optional[int] = None,
|
|
156
|
+
operation: Optional[str] = None,
|
|
157
|
+
c: Optional[float] = None,
|
|
158
|
+
loss: Optional[int] = None,
|
|
159
|
+
):
|
|
160
|
+
memset(&self.spec, 0, sizeof(layer_spec_t))
|
|
161
|
+
self.index = -1
|
|
162
|
+
|
|
163
|
+
if kernel_size is not None:
|
|
164
|
+
self.spec.kernel_size = kernel_size
|
|
165
|
+
|
|
166
|
+
if filters is not None:
|
|
167
|
+
self.spec.filters = filters
|
|
168
|
+
|
|
169
|
+
if padding is not None:
|
|
170
|
+
self.spec.padding = padding
|
|
171
|
+
|
|
172
|
+
if stride is not None:
|
|
173
|
+
self.spec.stride = stride
|
|
174
|
+
|
|
175
|
+
if outputs is not None:
|
|
176
|
+
self.spec.outputs = outputs
|
|
177
|
+
|
|
178
|
+
if decay is not None:
|
|
179
|
+
self.spec.decay = decay
|
|
180
|
+
|
|
181
|
+
if epsilon is not None:
|
|
182
|
+
self.spec.epsilon = epsilon
|
|
183
|
+
|
|
184
|
+
if force_stats_calc is not None:
|
|
185
|
+
self.spec.force_stats_calc = force_stats_calc
|
|
186
|
+
|
|
187
|
+
if activation is not None:
|
|
188
|
+
self.spec.activation = activation
|
|
189
|
+
|
|
190
|
+
if operation is not None:
|
|
191
|
+
self._operation = str(operation).encode()
|
|
192
|
+
self.spec.operation = self._operation
|
|
193
|
+
|
|
194
|
+
if c is not None:
|
|
195
|
+
self.spec.c = c
|
|
196
|
+
|
|
197
|
+
if loss is not None:
|
|
198
|
+
self.spec.loss = loss
|
|
199
|
+
|
|
200
|
+
self._type = str(type).encode()
|
|
201
|
+
self.spec.type = self._type
|
|
202
|
+
|
|
203
|
+
if label:
|
|
204
|
+
self._label = str(label).encode()
|
|
205
|
+
self.spec.label = self._label
|
|
206
|
+
|
|
207
|
+
if weight_init is not None:
|
|
208
|
+
memset(&self.weight_init, 0, sizeof(weight_init_t))
|
|
209
|
+
self.weight_init.param_init = weight_init
|
|
210
|
+
self.spec.weight_init = &self.weight_init
|
|
211
|
+
|
|
212
|
+
def __dealloc__(self):
|
|
213
|
+
...
|
|
214
|
+
|
|
215
|
+
cpdef set_index(self, index: int):
|
|
216
|
+
self.index = index
|
|
217
|
+
|
|
218
|
+
cdef const layer_spec_t *getptr(self):
|
|
219
|
+
return &self.spec
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@cython.final
|
|
223
|
+
cdef class NNSpec:
|
|
224
|
+
|
|
225
|
+
cdef nn_spec_t spec
|
|
226
|
+
cdef layer_spec_t *layers
|
|
227
|
+
cdef layer_links_t *links
|
|
228
|
+
cdef unsigned nlinks
|
|
229
|
+
cdef object layers_ref
|
|
230
|
+
|
|
231
|
+
def __cinit__(
|
|
232
|
+
self,
|
|
233
|
+
width: int,
|
|
234
|
+
height: int,
|
|
235
|
+
channels: int,
|
|
236
|
+
batch_size: int,
|
|
237
|
+
epochs: int,
|
|
238
|
+
optimizer: OptimSpec,
|
|
239
|
+
layers: tuple[LayerSpec],
|
|
240
|
+
links: tuple[tuple[LayerSpec, tuple[LayerSpec]]],
|
|
241
|
+
):
|
|
242
|
+
memset(&self.spec, 0, sizeof(nn_spec_t))
|
|
243
|
+
|
|
244
|
+
self.spec.input_width = width
|
|
245
|
+
self.spec.input_height = height
|
|
246
|
+
self.spec.input_channels = channels
|
|
247
|
+
self.spec.training_batch_size = batch_size
|
|
248
|
+
self.spec.training_epochs = epochs
|
|
249
|
+
|
|
250
|
+
optim = <OptimSpec?>optimizer
|
|
251
|
+
memcpy(&self.spec.optimizer, optim.getptr(), sizeof(optim_spec_t))
|
|
252
|
+
|
|
253
|
+
self._copy_graph(layers, links)
|
|
254
|
+
self.layers_ref = layers # acquire reference
|
|
255
|
+
|
|
256
|
+
cdef int _copy_graph(
|
|
257
|
+
self,
|
|
258
|
+
layers: tuple[LayerSpec],
|
|
259
|
+
links: tuple[tuple[LayerSpec, tuple[LayerSpec]]],
|
|
260
|
+
) except -1:
|
|
261
|
+
#
|
|
262
|
+
# Copy over the layers.
|
|
263
|
+
#
|
|
264
|
+
self.layers = <layer_spec_t *>pymalloc(
|
|
265
|
+
len(layers) * sizeof(layer_spec_t)
|
|
266
|
+
)
|
|
267
|
+
for i, layer in enumerate(layers):
|
|
268
|
+
nn_layer = <LayerSpec?>layer
|
|
269
|
+
memcpy(&self.layers[i], nn_layer.getptr(), sizeof(layer_spec_t))
|
|
270
|
+
|
|
271
|
+
#
|
|
272
|
+
# Prepare the adjacency lists.
|
|
273
|
+
#
|
|
274
|
+
self.links = <layer_links_t *>pymalloc(
|
|
275
|
+
len(links) * sizeof(layer_links_t)
|
|
276
|
+
)
|
|
277
|
+
memset(self.links, 0, len(links) * sizeof(layer_links_t))
|
|
278
|
+
self.nlinks = len(links)
|
|
279
|
+
|
|
280
|
+
#
|
|
281
|
+
# Set the layer links; allocate and set the targets. Note: keep
|
|
282
|
+
# in order such that there would be no leaks after __dealloc__.
|
|
283
|
+
#
|
|
284
|
+
for i, (layer, targets) in enumerate(links):
|
|
285
|
+
link_spec = <layer_links_t *>&self.links[i]
|
|
286
|
+
link_spec.layer = layer
|
|
287
|
+
|
|
288
|
+
link_indexes = <int *>pymalloc(len(targets) * sizeof(int))
|
|
289
|
+
link_spec.links = link_indexes
|
|
290
|
+
|
|
291
|
+
for j, target_idx in enumerate(targets):
|
|
292
|
+
link_indexes[j] = target_idx
|
|
293
|
+
|
|
294
|
+
self.spec.layers = self.layers
|
|
295
|
+
self.spec.nlayers = len(layers)
|
|
296
|
+
|
|
297
|
+
self.spec.links = self.links
|
|
298
|
+
self.spec.nlinks = len(links)
|
|
299
|
+
|
|
300
|
+
return 0
|
|
301
|
+
|
|
302
|
+
def __dealloc__(self):
|
|
303
|
+
for i in range(self.nlinks):
|
|
304
|
+
link_spec = <layer_links_t *>&self.links[i]
|
|
305
|
+
PyMem_Free(<void *><uintptr_t>link_spec.links) # un-const
|
|
306
|
+
PyMem_Free(self.links)
|
|
307
|
+
PyMem_Free(self.layers)
|
|
308
|
+
self.layers_ref = None # release reference
|
|
309
|
+
|
|
310
|
+
cdef nn_spec_t *getptr(self):
|
|
311
|
+
return &self.spec
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
@cython.final
|
|
315
|
+
cdef class NN:
|
|
316
|
+
|
|
317
|
+
ERROR_MAP = {
|
|
318
|
+
NN_ERR_FATAL: LivnnFatalError,
|
|
319
|
+
NN_ERR_SYSTEM: LivnnSystemError,
|
|
320
|
+
NN_ERR_INVALID: LivnnInvalidValueError,
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
cdef nn_t *nn
|
|
324
|
+
cdef NNSpec spec_ref
|
|
325
|
+
|
|
326
|
+
def __cinit__(self, spec: NNSpec):
|
|
327
|
+
self.spec_ref = <NNSpec?>spec
|
|
328
|
+
self.nn = nn_create(self.spec_ref.getptr())
|
|
329
|
+
if self.nn is NULL:
|
|
330
|
+
raise OSError(errno, strerror(errno))
|
|
331
|
+
|
|
332
|
+
def __dealloc__(self):
|
|
333
|
+
if self.nn is not NULL:
|
|
334
|
+
nn_destroy(self.nn)
|
|
335
|
+
self.spec_ref = None # release the reference
|
|
336
|
+
|
|
337
|
+
cdef _throw_error(self):
|
|
338
|
+
cdef const char *c_errmsg
|
|
339
|
+
cdef bytes py_errmsg
|
|
340
|
+
|
|
341
|
+
errcode = nn_get_error(self.nn, &c_errmsg)
|
|
342
|
+
if errcode:
|
|
343
|
+
py_errmsg = c_errmsg
|
|
344
|
+
exc = self.ERROR_MAP.get(errcode) or RuntimeError
|
|
345
|
+
raise exc(py_errmsg.decode("utf-8"))
|
|
346
|
+
|
|
347
|
+
raise RuntimeError("unknown internal error")
|
|
348
|
+
|
|
349
|
+
def init(self, *, training: bool = False):
|
|
350
|
+
if nn_init(self.nn, training):
|
|
351
|
+
return self._throw_error()
|
|
352
|
+
|
|
353
|
+
def load(self, path: str):
|
|
354
|
+
if nn_load(self.nn, path.encode()):
|
|
355
|
+
return self._throw_error()
|
|
356
|
+
|
|
357
|
+
def save(self, path: str):
|
|
358
|
+
if nn_save(self.nn, path.encode()):
|
|
359
|
+
return self._throw_error()
|
|
360
|
+
|
|
361
|
+
def run(self, tensor: TensorBase):
|
|
362
|
+
if nn_run(self.nn, tensor.ref):
|
|
363
|
+
return self._throw_error()
|
|
364
|
+
|
|
365
|
+
def train(self, dataset):
|
|
366
|
+
cdef DatasetBase ds = <DatasetBase?>dataset
|
|
367
|
+
if nn_train(self.nn, ds.get_obj()):
|
|
368
|
+
return self._throw_error()
|
|
369
|
+
|
|
370
|
+
cdef layer_t *get_layer(self, index: int):
|
|
371
|
+
c_layer = nn_lookup_layer(self.nn, index)
|
|
372
|
+
if c_layer is NULL:
|
|
373
|
+
raise ValueError("invalid layer index")
|
|
374
|
+
return c_layer
|
|
375
|
+
|
|
376
|
+
def get_layer_output(
|
|
377
|
+
self,
|
|
378
|
+
layer: LayerSpec,
|
|
379
|
+
cls: type
|
|
380
|
+
) -> TensorBase | None:
|
|
381
|
+
c_layer = self.get_layer(layer.index)
|
|
382
|
+
c_tensor = layer_get_output(c_layer)
|
|
383
|
+
return TensorBase.from_tensor(cls, c_tensor)
|
|
384
|
+
|
|
385
|
+
def get_layer_gradient(
|
|
386
|
+
self,
|
|
387
|
+
layer: LayerSpec,
|
|
388
|
+
cls: type,
|
|
389
|
+
edge_layer: Optional[LayerSpec] = None,
|
|
390
|
+
) -> TensorBase | None:
|
|
391
|
+
c_layer = self.get_layer(layer.index)
|
|
392
|
+
edge_layer_idx = edge_layer.index if edge_layer else <unsigned>(-1)
|
|
393
|
+
c_tensor = layer_get_gradient(c_layer, edge_layer_idx)
|
|
394
|
+
return TensorBase.from_tensor(cls, c_tensor) if c_tensor else None
|
|
395
|
+
|
|
396
|
+
def get_layer_weights_param(
|
|
397
|
+
self,
|
|
398
|
+
layer: LayerSpec,
|
|
399
|
+
cls: type,
|
|
400
|
+
param_id: int
|
|
401
|
+
) -> TensorBase | None:
|
|
402
|
+
c_layer = self.get_layer(layer.index)
|
|
403
|
+
c_tensor = layer_get_weights(c_layer, param_id)
|
|
404
|
+
return TensorBase.from_tensor(cls, c_tensor) if c_tensor else None
|
|
405
|
+
|
|
406
|
+
def get_layer_local_grad(
|
|
407
|
+
self,
|
|
408
|
+
layer: LayerSpec,
|
|
409
|
+
cls: type,
|
|
410
|
+
param_id: int
|
|
411
|
+
) -> TensorBase | None:
|
|
412
|
+
c_layer = self.get_layer(layer.index)
|
|
413
|
+
c_tensor = layer_get_local_grads(c_layer, param_id)
|
|
414
|
+
return TensorBase.from_tensor(cls, c_tensor) if c_tensor else None
|
|
415
|
+
|
|
416
|
+
def forward(self, layer: LayerSpec, tensor: TensorBase):
|
|
417
|
+
c_layer = self.get_layer(layer.index)
|
|
418
|
+
if nn_feed_forward(self.nn, c_layer, tensor.ref):
|
|
419
|
+
return self._throw_error()
|
|
420
|
+
|
|
421
|
+
def backprop(self, layer: LayerSpec, tensor: TensorBase):
|
|
422
|
+
c_layer = self.get_layer(layer.index)
|
|
423
|
+
if nn_backprop(self.nn, c_layer, tensor.ref):
|
|
424
|
+
return self._throw_error()
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Use is subject to license terms, as specified in the LICENSE file.
|
|
3
|
+
#
|
|
4
|
+
|
|
5
|
+
from livnn.dataset_base import DatasetBase, DatasetItem
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class Dataset(DatasetBase):
|
|
9
|
+
def add(self, item: DatasetItem | list[DatasetItem]):
|
|
10
|
+
"""
|
|
11
|
+
Add an item to the dataset.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
items = item if isinstance(item, (list, tuple)) else (item,)
|
|
15
|
+
for item in items:
|
|
16
|
+
super().add(item)
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
#
|
|
2
|
+
# Copyright (c) 2026 Mindaugas Rasiukevicius <rmind at noxt eu>
|
|
3
|
+
# All rights reserved.
|
|
4
|
+
#
|
|
5
|
+
# Use is subject to license terms, as specified in the LICENSE file.
|
|
6
|
+
#
|
|
7
|
+
|
|
8
|
+
from livnn.tensor_base cimport tensor_t, tensor_dims_t
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
cdef extern from "<livnn/dataset.h>":
|
|
12
|
+
ctypedef struct dataset_t
|
|
13
|
+
ctypedef struct dataset_batch_t
|
|
14
|
+
|
|
15
|
+
ctypedef enum targets_repr_t:
|
|
16
|
+
DS_TARGETS_IDX
|
|
17
|
+
DS_TARGETS_VEC
|
|
18
|
+
|
|
19
|
+
ctypedef struct targets_val_t:
|
|
20
|
+
targets_repr_t repr
|
|
21
|
+
unsigned idx
|
|
22
|
+
const float *vec
|
|
23
|
+
|
|
24
|
+
dataset_t *dataset_create(unsigned, const tensor_dims_t *, unsigned)
|
|
25
|
+
void dataset_destroy(dataset_t *)
|
|
26
|
+
|
|
27
|
+
int dataset_add_item(dataset_t *, const float *, const size_t,
|
|
28
|
+
const targets_val_t *)
|
|
29
|
+
void dataset_finish(dataset_t *, unsigned)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
cdef class DatasetBase:
|
|
33
|
+
cdef dataset_t *ds
|
|
34
|
+
cdef unsigned batch_size
|
|
35
|
+
cdef tensor_dims_t dims
|
|
36
|
+
cdef size_t item_size
|
|
37
|
+
cdef unsigned target_count
|
|
38
|
+
|
|
39
|
+
cdef dataset_t *get_obj(self)
|