keras-tensorc 0.1.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.
- keras_tensorc-0.1.0/PKG-INFO +41 -0
- keras_tensorc-0.1.0/README.md +32 -0
- keras_tensorc-0.1.0/keras_tensorc/__init__.py +1 -0
- keras_tensorc-0.1.0/keras_tensorc/src/__init__.py +39 -0
- keras_tensorc-0.1.0/keras_tensorc/src/ops/__init__.py +44 -0
- keras_tensorc-0.1.0/keras_tensorc/src/ops/core.py +96 -0
- keras_tensorc-0.1.0/keras_tensorc/src/ops/nn.py +51 -0
- keras_tensorc-0.1.0/keras_tensorc/src/ops/numpy.py +35 -0
- keras_tensorc-0.1.0/keras_tensorc/src/random.py +44 -0
- keras_tensorc-0.1.0/keras_tensorc/src/trainer.py +270 -0
- keras_tensorc-0.1.0/keras_tensorc/src/variable.py +42 -0
- keras_tensorc-0.1.0/keras_tensorc/src/version.py +1 -0
- keras_tensorc-0.1.0/keras_tensorc.egg-info/PKG-INFO +41 -0
- keras_tensorc-0.1.0/keras_tensorc.egg-info/SOURCES.txt +21 -0
- keras_tensorc-0.1.0/keras_tensorc.egg-info/dependency_links.txt +1 -0
- keras_tensorc-0.1.0/keras_tensorc.egg-info/requires.txt +2 -0
- keras_tensorc-0.1.0/keras_tensorc.egg-info/top_level.txt +1 -0
- keras_tensorc-0.1.0/pyproject.toml +14 -0
- keras_tensorc-0.1.0/setup.cfg +4 -0
- keras_tensorc-0.1.0/tests/test_adam.py +96 -0
- keras_tensorc-0.1.0/tests/test_conv2d.py +65 -0
- keras_tensorc-0.1.0/tests/test_dense_fit.py +189 -0
- keras_tensorc-0.1.0/tests/test_functional.py +29 -0
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: keras-tensorc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Experimental Keras backend powered by TensorC
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: numpy>=1.20
|
|
8
|
+
Requires-Dist: tensorc>=0.17.0
|
|
9
|
+
|
|
10
|
+
# Keras backend experimental para TensorC
|
|
11
|
+
|
|
12
|
+
Prototipo de backend enchufable para Keras. Requiere el código actual de Keras
|
|
13
|
+
con soporte de backends no oficiales; la versión estable de Keras aún no expone
|
|
14
|
+
este punto de extensión. No es compatible con `KERAS_BACKEND=tensorc` en Keras
|
|
15
|
+
3.15.x.
|
|
16
|
+
|
|
17
|
+
La API de backends enchufables todavía está en desarrollo y Keras no publica
|
|
18
|
+
esa versión en PyPI. Instala primero Keras desde su repositorio y luego este
|
|
19
|
+
paquete (que instala TensorC y NumPy):
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
python -m pip install git+https://github.com/keras-team/keras.git
|
|
23
|
+
python -m pip install keras-tensorc
|
|
24
|
+
KERAS_BACKEND=tensorc KERAS_ALLOW_UNOFFICIAL_BACKEND=1 \
|
|
25
|
+
python integrations/keras-tensorc/examples/dense_fit.py
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
La dependencia de Keras se instala por separado porque la versión estable de
|
|
29
|
+
PyPI aún no admite este backend experimental.
|
|
30
|
+
|
|
31
|
+
El prototipo cubre `Sequential` y `Input → Dense → Model` con datos NumPy, CPU y
|
|
32
|
+
`float32`. También admite `Conv2D` en formato channels-last, con sesgo, strides
|
|
33
|
+
y padding `valid`/`same`; grupos, dilatación y channels-first no están
|
|
34
|
+
implementados. Para entrenamiento admite MSE, SGD sin momentum y Adam con
|
|
35
|
+
betas/epsilon predeterminados; `fit` ejecuta
|
|
36
|
+
callbacks, respeta `model.stop_training`, soporta validación NumPy y las
|
|
37
|
+
métricas `"mae"`/`"mean_absolute_error"`. Los momentos de Adam se conservan
|
|
38
|
+
entre llamadas a `fit` en el mismo proceso. El roundtrip `.keras` está probado
|
|
39
|
+
para `Sequential(Dense)`; guardar el modelo no guarda los momentos de Adam para
|
|
40
|
+
reanudar el entrenamiento. Sample/class weights y datasets siguen fuera de
|
|
41
|
+
alcance.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Keras backend experimental para TensorC
|
|
2
|
+
|
|
3
|
+
Prototipo de backend enchufable para Keras. Requiere el código actual de Keras
|
|
4
|
+
con soporte de backends no oficiales; la versión estable de Keras aún no expone
|
|
5
|
+
este punto de extensión. No es compatible con `KERAS_BACKEND=tensorc` en Keras
|
|
6
|
+
3.15.x.
|
|
7
|
+
|
|
8
|
+
La API de backends enchufables todavía está en desarrollo y Keras no publica
|
|
9
|
+
esa versión en PyPI. Instala primero Keras desde su repositorio y luego este
|
|
10
|
+
paquete (que instala TensorC y NumPy):
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
python -m pip install git+https://github.com/keras-team/keras.git
|
|
14
|
+
python -m pip install keras-tensorc
|
|
15
|
+
KERAS_BACKEND=tensorc KERAS_ALLOW_UNOFFICIAL_BACKEND=1 \
|
|
16
|
+
python integrations/keras-tensorc/examples/dense_fit.py
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
La dependencia de Keras se instala por separado porque la versión estable de
|
|
20
|
+
PyPI aún no admite este backend experimental.
|
|
21
|
+
|
|
22
|
+
El prototipo cubre `Sequential` y `Input → Dense → Model` con datos NumPy, CPU y
|
|
23
|
+
`float32`. También admite `Conv2D` en formato channels-last, con sesgo, strides
|
|
24
|
+
y padding `valid`/`same`; grupos, dilatación y channels-first no están
|
|
25
|
+
implementados. Para entrenamiento admite MSE, SGD sin momentum y Adam con
|
|
26
|
+
betas/epsilon predeterminados; `fit` ejecuta
|
|
27
|
+
callbacks, respeta `model.stop_training`, soporta validación NumPy y las
|
|
28
|
+
métricas `"mae"`/`"mean_absolute_error"`. Los momentos de Adam se conservan
|
|
29
|
+
entre llamadas a `fit` en el mismo proceso. El roundtrip `.keras` está probado
|
|
30
|
+
para `Sequential(Dense)`; guardar el modelo no guarda los momentos de Adam para
|
|
31
|
+
reanudar el entrenamiento. Sample/class weights y datasets siguen fuera de
|
|
32
|
+
alcance.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from keras_tensorc.src.version import __version__
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
from keras.src.backend.common.name_scope import name_scope
|
|
2
|
+
|
|
3
|
+
from keras_tensorc.src import ops
|
|
4
|
+
from keras_tensorc.src import random
|
|
5
|
+
from keras_tensorc.src.ops.core import cast
|
|
6
|
+
from keras_tensorc.src.ops.core import compute_output_spec
|
|
7
|
+
from keras_tensorc.src.ops.core import convert_to_numpy
|
|
8
|
+
from keras_tensorc.src.ops.core import convert_to_tensor
|
|
9
|
+
from keras_tensorc.src.ops.core import device_scope
|
|
10
|
+
from keras_tensorc.src.ops.core import is_tensor
|
|
11
|
+
from keras_tensorc.src.ops.core import shape
|
|
12
|
+
from keras_tensorc.src.variable import Variable
|
|
13
|
+
|
|
14
|
+
SUPPORTS_COMPLEX_DTYPES = False
|
|
15
|
+
SUPPORTS_GRADIENT = True
|
|
16
|
+
SUPPORTS_RAGGED_TENSORS = False
|
|
17
|
+
SUPPORTS_SPARSE_TENSORS = False
|
|
18
|
+
IS_THREAD_SAFE = False
|
|
19
|
+
distribution_lib = None
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"IS_THREAD_SAFE",
|
|
23
|
+
"SUPPORTS_COMPLEX_DTYPES",
|
|
24
|
+
"SUPPORTS_GRADIENT",
|
|
25
|
+
"SUPPORTS_RAGGED_TENSORS",
|
|
26
|
+
"SUPPORTS_SPARSE_TENSORS",
|
|
27
|
+
"Variable",
|
|
28
|
+
"compute_output_spec",
|
|
29
|
+
"convert_to_numpy",
|
|
30
|
+
"convert_to_tensor",
|
|
31
|
+
"cast",
|
|
32
|
+
"device_scope",
|
|
33
|
+
"distribution_lib",
|
|
34
|
+
"is_tensor",
|
|
35
|
+
"name_scope",
|
|
36
|
+
"ops",
|
|
37
|
+
"random",
|
|
38
|
+
"shape",
|
|
39
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from keras_tensorc.src.ops import core
|
|
2
|
+
from keras_tensorc.src.ops import nn
|
|
3
|
+
from keras_tensorc.src.ops import numpy
|
|
4
|
+
from keras_tensorc.src.ops.core import cast
|
|
5
|
+
from keras_tensorc.src.ops.core import compute_output_spec
|
|
6
|
+
from keras_tensorc.src.ops.core import convert_to_numpy
|
|
7
|
+
from keras_tensorc.src.ops.core import convert_to_tensor
|
|
8
|
+
from keras_tensorc.src.ops.core import grad
|
|
9
|
+
from keras_tensorc.src.ops.core import is_tensor
|
|
10
|
+
from keras_tensorc.src.ops.core import shape
|
|
11
|
+
from keras_tensorc.src.ops.core import stop_gradient
|
|
12
|
+
from types import SimpleNamespace
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _unsupported(name):
|
|
16
|
+
def call(*args, **kwargs):
|
|
17
|
+
raise NotImplementedError("TensorC Keras backend does not implement ops.%s" % name)
|
|
18
|
+
|
|
19
|
+
return call
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class _MissingOps:
|
|
23
|
+
def __init__(self, namespace):
|
|
24
|
+
self.namespace = namespace
|
|
25
|
+
|
|
26
|
+
def __getattr__(self, name):
|
|
27
|
+
return _unsupported("%s.%s" % (self.namespace, name))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
math = _MissingOps("math")
|
|
31
|
+
linalg = _MissingOps("linalg")
|
|
32
|
+
image = _MissingOps("image")
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"cast", "compute_output_spec", "convert_to_numpy", "convert_to_tensor",
|
|
36
|
+
"core", "grad", "image", "is_tensor", "linalg", "math", "nn",
|
|
37
|
+
"numpy", "shape", "stop_gradient",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def __getattr__(name):
|
|
42
|
+
if name in __all__:
|
|
43
|
+
return globals()[name]
|
|
44
|
+
return _unsupported(name)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
import tensorc
|
|
4
|
+
from keras.src.backend.common.keras_tensor import KerasTensor
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _tensor(value, requires_grad=False):
|
|
8
|
+
if isinstance(value, tensorc.Tensor):
|
|
9
|
+
return value
|
|
10
|
+
if hasattr(value, "value") and isinstance(value.value, tensorc.Tensor):
|
|
11
|
+
return value.value
|
|
12
|
+
array = np.ascontiguousarray(value, dtype=np.float32)
|
|
13
|
+
return tensorc.Tensor(array, requires_grad=requires_grad)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def convert_to_tensor(x, dtype=None, sparse=None, ragged=None):
|
|
17
|
+
del sparse, ragged
|
|
18
|
+
if dtype not in (None, "float32", np.float32):
|
|
19
|
+
raise NotImplementedError("TensorC Keras prototype supports float32 only")
|
|
20
|
+
return _tensor(x)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def convert_to_numpy(x):
|
|
24
|
+
if hasattr(x, "value") and isinstance(x.value, tensorc.Tensor):
|
|
25
|
+
x = x.value
|
|
26
|
+
if isinstance(x, tensorc.Tensor):
|
|
27
|
+
return np.asarray(x.data, dtype=np.float32).reshape(x.shape)
|
|
28
|
+
return np.asarray(x)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def is_tensor(x):
|
|
32
|
+
return isinstance(x, tensorc.Tensor) or (
|
|
33
|
+
hasattr(x, "value") and isinstance(x.value, tensorc.Tensor)
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def shape(x):
|
|
38
|
+
return tuple(x.shape) if is_tensor(x) else np.shape(x)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def cast(x, dtype):
|
|
42
|
+
if dtype not in ("float32", np.float32):
|
|
43
|
+
raise NotImplementedError("TensorC Keras prototype supports float32 only")
|
|
44
|
+
return _tensor(x)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def stop_gradient(x):
|
|
48
|
+
return convert_to_tensor(convert_to_numpy(x))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def compute_output_spec(fn, *args, **kwargs):
|
|
52
|
+
shapes = [getattr(arg, "shape", None) for arg in args]
|
|
53
|
+
shapes = [shape if shape is not None else np.shape(arg)
|
|
54
|
+
for arg, shape in zip(args, shapes)]
|
|
55
|
+
if hasattr(fn, "compute_output_shape") and shapes:
|
|
56
|
+
return KerasTensor(fn.compute_output_shape(shapes[0]), dtype="float32")
|
|
57
|
+
raise NotImplementedError("symbolic output inference is not implemented")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def grad(fn, argnums=0):
|
|
61
|
+
def gradient(*args, **kwargs):
|
|
62
|
+
indexes = (argnums,) if isinstance(argnums, int) else tuple(argnums)
|
|
63
|
+
mutable = list(args)
|
|
64
|
+
watched = []
|
|
65
|
+
for index in indexes:
|
|
66
|
+
watched.append(_tensor(args[index], requires_grad=True))
|
|
67
|
+
mutable[index] = watched[-1]
|
|
68
|
+
output = _tensor(fn(*mutable, **kwargs))
|
|
69
|
+
if np.prod(output.shape, dtype=np.int64) != 1:
|
|
70
|
+
raise NotImplementedError("TensorC grad currently requires scalar output")
|
|
71
|
+
output.backward()
|
|
72
|
+
gradients = [
|
|
73
|
+
tensorc.Tensor(
|
|
74
|
+
np.asarray(value.grad or np.zeros(value.shape), dtype=np.float32)
|
|
75
|
+
.reshape(value.shape)
|
|
76
|
+
)
|
|
77
|
+
for value in watched
|
|
78
|
+
]
|
|
79
|
+
return gradients[0] if isinstance(argnums, int) else tuple(gradients)
|
|
80
|
+
|
|
81
|
+
return gradient
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def device_scope(device_name):
|
|
85
|
+
if not str(device_name).startswith("cpu"):
|
|
86
|
+
raise NotImplementedError("TensorC Keras prototype supports CPU only")
|
|
87
|
+
from contextlib import nullcontext
|
|
88
|
+
|
|
89
|
+
return nullcontext()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def __getattr__(name):
|
|
93
|
+
def unsupported(*args, **kwargs):
|
|
94
|
+
raise NotImplementedError("TensorC Keras backend does not implement core.%s" % name)
|
|
95
|
+
|
|
96
|
+
return unsupported
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from keras.src.utils.argument_validation import standardize_tuple
|
|
2
|
+
from tensorc import Tensor
|
|
3
|
+
|
|
4
|
+
from keras_tensorc.src.ops.core import _tensor
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def relu(x):
|
|
8
|
+
return _tensor(x).relu()
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def conv(inputs, kernel, strides=1, padding="valid", data_format=None, dilation_rate=1):
|
|
12
|
+
inputs, kernel = _tensor(inputs), _tensor(kernel)
|
|
13
|
+
if (
|
|
14
|
+
data_format not in (None, "channels_last")
|
|
15
|
+
or len(inputs.shape) != 4
|
|
16
|
+
or len(kernel.shape) != 4
|
|
17
|
+
):
|
|
18
|
+
raise NotImplementedError("TensorC Keras backend supports channels-last Conv2D only")
|
|
19
|
+
if inputs.shape[-1] != kernel.shape[-2]:
|
|
20
|
+
raise NotImplementedError("TensorC Keras backend does not support grouped Conv2D")
|
|
21
|
+
if standardize_tuple(dilation_rate, 2, "dilation_rate") != (1, 1):
|
|
22
|
+
raise NotImplementedError("TensorC Keras backend does not support dilated Conv2D")
|
|
23
|
+
strides = standardize_tuple(strides, 2, "strides")
|
|
24
|
+
inputs = inputs.permute((0, 3, 1, 2))
|
|
25
|
+
kernel = kernel.permute((3, 2, 0, 1))
|
|
26
|
+
symmetric_padding = [0, 0]
|
|
27
|
+
if padding == "same":
|
|
28
|
+
for index, (size, kernel_size, stride) in enumerate(
|
|
29
|
+
zip(inputs.shape[2:], kernel.shape[2:], strides)
|
|
30
|
+
):
|
|
31
|
+
output_size = (size + stride - 1) // stride
|
|
32
|
+
total_padding = max(0, (output_size - 1) * stride + kernel_size - size)
|
|
33
|
+
symmetric_padding[index], extra = divmod(total_padding, 2)
|
|
34
|
+
if extra:
|
|
35
|
+
# Keras puts odd padding on the bottom or right.
|
|
36
|
+
axis = index + 2
|
|
37
|
+
shape = list(inputs.shape)
|
|
38
|
+
shape[axis] = 1
|
|
39
|
+
inputs = inputs.concat(Tensor.zeros(shape), axis=axis)
|
|
40
|
+
elif padding != "valid":
|
|
41
|
+
raise ValueError("Conv2D padding must be 'valid' or 'same'")
|
|
42
|
+
|
|
43
|
+
outputs = inputs.conv2d(kernel, stride=strides, padding=tuple(symmetric_padding))
|
|
44
|
+
return outputs.permute((0, 2, 3, 1))
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def __getattr__(name):
|
|
48
|
+
def unsupported(*args, **kwargs):
|
|
49
|
+
raise NotImplementedError("TensorC Keras backend does not implement nn.%s" % name)
|
|
50
|
+
|
|
51
|
+
return unsupported
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
from keras_tensorc.src.ops.core import _tensor
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def add(x1, x2):
|
|
7
|
+
return _tensor(x1).add(_tensor(x2))
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def multiply(x1, x2):
|
|
11
|
+
return _tensor(x1).mul(_tensor(x2))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def matmul(x1, x2):
|
|
15
|
+
return _tensor(x1).matmul(_tensor(x2))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def reshape(x, newshape):
|
|
19
|
+
# shortcut: Supports explicit dimensions until a caller needs shape inference.
|
|
20
|
+
return _tensor(x).reshape(newshape)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def zeros(shape, dtype="float32"):
|
|
24
|
+
return _tensor(np.zeros(shape, dtype=dtype))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def ones(shape, dtype="float32"):
|
|
28
|
+
return _tensor(np.ones(shape, dtype=dtype))
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def __getattr__(name):
|
|
32
|
+
def unsupported(*args, **kwargs):
|
|
33
|
+
raise NotImplementedError("TensorC Keras backend does not implement numpy.%s" % name)
|
|
34
|
+
|
|
35
|
+
return unsupported
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
from keras.src.random.seed_generator import SeedGenerator
|
|
3
|
+
|
|
4
|
+
from keras_tensorc.src.ops.core import _tensor
|
|
5
|
+
from keras_tensorc.src.ops.core import convert_to_numpy
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def seed_dtype():
|
|
9
|
+
return "float32"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def make_default_seed():
|
|
13
|
+
return int(np.random.randint(1, 1_000_000_000))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def uniform(shape, minval=0.0, maxval=1.0, dtype="float32", seed=None):
|
|
17
|
+
if dtype not in ("float32", np.float32):
|
|
18
|
+
raise NotImplementedError("TensorC Keras prototype supports float32 only")
|
|
19
|
+
if hasattr(seed, "shape"):
|
|
20
|
+
seed = int(np.asarray(convert_to_numpy(seed), dtype=np.float32).sum())
|
|
21
|
+
return _tensor(
|
|
22
|
+
np.random.default_rng(seed).uniform(minval, maxval, size=shape).astype(
|
|
23
|
+
np.float32
|
|
24
|
+
)
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def normal(shape, mean=0.0, stddev=1.0, dtype="float32", seed=None):
|
|
29
|
+
if dtype not in ("float32", np.float32):
|
|
30
|
+
raise NotImplementedError("TensorC Keras prototype supports float32 only")
|
|
31
|
+
if hasattr(seed, "shape"):
|
|
32
|
+
seed = int(np.asarray(convert_to_numpy(seed), dtype=np.float32).sum())
|
|
33
|
+
return _tensor(
|
|
34
|
+
np.random.default_rng(seed).normal(mean, stddev, size=shape).astype(
|
|
35
|
+
np.float32
|
|
36
|
+
)
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def __getattr__(name):
|
|
41
|
+
def unsupported(*args, **kwargs):
|
|
42
|
+
raise NotImplementedError("TensorC Keras backend does not implement random.%s" % name)
|
|
43
|
+
|
|
44
|
+
return unsupported
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
from numbers import Real
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
import tensorc
|
|
6
|
+
from keras.src.callbacks import callback_list as callbacks_module
|
|
7
|
+
from keras.src.trainers.data_adapters import data_adapter_utils
|
|
8
|
+
from keras.src.trainers.trainer import BaseTrainer
|
|
9
|
+
|
|
10
|
+
from keras_tensorc.src.ops.core import convert_to_numpy
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Trainer(BaseTrainer):
|
|
14
|
+
def _adam_step(self, loss, learning_rate):
|
|
15
|
+
optimizer = self.optimizer
|
|
16
|
+
params = tuple(variable.value for variable in self.trainable_variables)
|
|
17
|
+
state = getattr(optimizer, "_tensorc_adam", None)
|
|
18
|
+
if state is None:
|
|
19
|
+
if not params:
|
|
20
|
+
return
|
|
21
|
+
if optimizer.built or optimizer.iterations.numpy().item():
|
|
22
|
+
raise NotImplementedError(
|
|
23
|
+
"TensorC Adam requires a fresh or in-memory optimizer"
|
|
24
|
+
)
|
|
25
|
+
native_adam = tensorc.Adam(params, learning_rate, epsilon_hat=1e-7)
|
|
26
|
+
optimizer._tensorc_adam = (params, native_adam)
|
|
27
|
+
else:
|
|
28
|
+
previous_params, native_adam = state
|
|
29
|
+
if params != previous_params:
|
|
30
|
+
raise ValueError("TensorC Adam requires the same trainable variables")
|
|
31
|
+
native_adam.set_lr(learning_rate)
|
|
32
|
+
loss.backward()
|
|
33
|
+
native_adam.step()
|
|
34
|
+
for param in params:
|
|
35
|
+
param.zero_grad()
|
|
36
|
+
optimizer.iterations.assign(optimizer.iterations.numpy() + 1)
|
|
37
|
+
|
|
38
|
+
def fit(
|
|
39
|
+
self,
|
|
40
|
+
x=None,
|
|
41
|
+
y=None,
|
|
42
|
+
batch_size=32,
|
|
43
|
+
epochs=1,
|
|
44
|
+
verbose="auto",
|
|
45
|
+
callbacks=None,
|
|
46
|
+
validation_split=0.0,
|
|
47
|
+
validation_data=None,
|
|
48
|
+
shuffle=True,
|
|
49
|
+
class_weight=None,
|
|
50
|
+
sample_weight=None,
|
|
51
|
+
initial_epoch=0,
|
|
52
|
+
steps_per_epoch=None,
|
|
53
|
+
validation_steps=None,
|
|
54
|
+
validation_batch_size=None,
|
|
55
|
+
validation_freq=1,
|
|
56
|
+
):
|
|
57
|
+
from keras.src.optimizers.adam import Adam
|
|
58
|
+
from keras.src.optimizers.sgd import SGD
|
|
59
|
+
|
|
60
|
+
self._assert_compile_called("fit")
|
|
61
|
+
if any(value is not None for value in (
|
|
62
|
+
class_weight, sample_weight, steps_per_epoch, validation_steps
|
|
63
|
+
)):
|
|
64
|
+
raise NotImplementedError("sample/class weights and explicit steps are not supported yet")
|
|
65
|
+
if not isinstance(validation_freq, int) or validation_freq <= 0:
|
|
66
|
+
raise NotImplementedError("validation_freq must be a positive integer")
|
|
67
|
+
loss = getattr(self._compile_loss, "_user_loss", None)
|
|
68
|
+
if not (loss == "mse" or loss == "mean_squared_error"):
|
|
69
|
+
raise NotImplementedError("the TensorC Keras prototype supports MSE only")
|
|
70
|
+
if getattr(self._compile_loss, "_user_loss_weights", None) is not None:
|
|
71
|
+
raise NotImplementedError("loss_weights are not supported yet")
|
|
72
|
+
if getattr(self._compile_metrics, "_user_weighted_metrics", None):
|
|
73
|
+
raise NotImplementedError("weighted_metrics are not supported yet")
|
|
74
|
+
optimizer = self.optimizer
|
|
75
|
+
use_adam = type(optimizer) is Adam
|
|
76
|
+
if use_adam:
|
|
77
|
+
hyperparameters = (optimizer.beta_1, optimizer.beta_2, optimizer.epsilon)
|
|
78
|
+
unsupported = (
|
|
79
|
+
optimizer.weight_decay,
|
|
80
|
+
optimizer.clipnorm,
|
|
81
|
+
optimizer.clipvalue,
|
|
82
|
+
optimizer.global_clipnorm,
|
|
83
|
+
optimizer.loss_scale_factor,
|
|
84
|
+
optimizer.gradient_accumulation_steps,
|
|
85
|
+
)
|
|
86
|
+
if (
|
|
87
|
+
not all(isinstance(value, Real) for value in hyperparameters)
|
|
88
|
+
or hyperparameters != (0.9, 0.999, 1e-7)
|
|
89
|
+
or any(option is not None for option in unsupported)
|
|
90
|
+
or optimizer.amsgrad
|
|
91
|
+
or optimizer.use_ema
|
|
92
|
+
or callable(optimizer._learning_rate)
|
|
93
|
+
):
|
|
94
|
+
raise NotImplementedError(
|
|
95
|
+
"TensorC Adam requires default betas and epsilon, a scalar "
|
|
96
|
+
"learning rate, and no optimizer extensions"
|
|
97
|
+
)
|
|
98
|
+
elif type(optimizer) is SGD:
|
|
99
|
+
unsupported = (
|
|
100
|
+
optimizer.weight_decay,
|
|
101
|
+
optimizer.clipnorm,
|
|
102
|
+
optimizer.clipvalue,
|
|
103
|
+
optimizer.global_clipnorm,
|
|
104
|
+
optimizer.loss_scale_factor,
|
|
105
|
+
optimizer.gradient_accumulation_steps,
|
|
106
|
+
)
|
|
107
|
+
if (
|
|
108
|
+
optimizer.momentum != 0
|
|
109
|
+
or optimizer.nesterov
|
|
110
|
+
or any(option is not None for option in unsupported)
|
|
111
|
+
or optimizer.use_ema
|
|
112
|
+
or callable(optimizer._learning_rate)
|
|
113
|
+
):
|
|
114
|
+
raise NotImplementedError(
|
|
115
|
+
"TensorC SGD requires zero momentum and no optimizer extensions"
|
|
116
|
+
)
|
|
117
|
+
else:
|
|
118
|
+
raise NotImplementedError("TensorC supports plain SGD and default Adam")
|
|
119
|
+
metric_name = None
|
|
120
|
+
metrics = getattr(self._compile_metrics, "_user_metrics", None)
|
|
121
|
+
if metrics:
|
|
122
|
+
metrics = metrics if isinstance(metrics, (list, tuple)) else [metrics]
|
|
123
|
+
if len(metrics) != 1 or metrics[0] not in ("mae", "mean_absolute_error"):
|
|
124
|
+
raise NotImplementedError("the TensorC Keras prototype supports MAE only")
|
|
125
|
+
metric_name = metrics[0]
|
|
126
|
+
|
|
127
|
+
x = np.asarray(x, dtype=np.float32)
|
|
128
|
+
y = np.asarray(y, dtype=np.float32)
|
|
129
|
+
if x.ndim < 2 or y.ndim < 2 or x.shape[0] != y.shape[0] or not x.shape[0]:
|
|
130
|
+
raise ValueError("x and y must have matching non-empty batch dimensions")
|
|
131
|
+
val_x = val_y = None
|
|
132
|
+
if validation_data is not None and validation_split:
|
|
133
|
+
raise ValueError("validation_data and validation_split cannot be used together")
|
|
134
|
+
if validation_data is not None:
|
|
135
|
+
if not isinstance(validation_data, (tuple, list)) or len(validation_data) != 2:
|
|
136
|
+
raise NotImplementedError("validation_data must be an (x, y) NumPy pair")
|
|
137
|
+
val_x, val_y = (np.asarray(value, dtype=np.float32) for value in validation_data)
|
|
138
|
+
elif validation_split:
|
|
139
|
+
if not 0 < validation_split < 1:
|
|
140
|
+
raise ValueError("validation_split must be between 0 and 1")
|
|
141
|
+
split_at = int(len(x) * (1 - validation_split))
|
|
142
|
+
if not 0 < split_at < len(x):
|
|
143
|
+
raise ValueError("validation_split must leave training and validation samples")
|
|
144
|
+
val_x, val_y = x[split_at:], y[split_at:]
|
|
145
|
+
x, y = x[:split_at], y[:split_at]
|
|
146
|
+
if val_x is not None and (
|
|
147
|
+
val_x.ndim < 2 or val_y.ndim < 2 or val_x.shape[0] != val_y.shape[0]
|
|
148
|
+
or not val_x.shape[0]
|
|
149
|
+
):
|
|
150
|
+
raise ValueError("validation x and y must have matching non-empty batch dimensions")
|
|
151
|
+
batch_size = int(batch_size or len(x))
|
|
152
|
+
if batch_size <= 0:
|
|
153
|
+
raise ValueError("batch_size must be positive")
|
|
154
|
+
validation_batch_size = int(validation_batch_size or batch_size)
|
|
155
|
+
if validation_batch_size <= 0:
|
|
156
|
+
raise ValueError("validation_batch_size must be positive")
|
|
157
|
+
|
|
158
|
+
steps = (len(x) + batch_size - 1) // batch_size
|
|
159
|
+
if not isinstance(callbacks, callbacks_module.CallbackList):
|
|
160
|
+
callbacks = callbacks_module.CallbackList(
|
|
161
|
+
callbacks,
|
|
162
|
+
add_history=True,
|
|
163
|
+
add_progbar=verbose != 0,
|
|
164
|
+
verbose=verbose,
|
|
165
|
+
epochs=epochs,
|
|
166
|
+
steps=steps,
|
|
167
|
+
model=self,
|
|
168
|
+
)
|
|
169
|
+
self.stop_training = False
|
|
170
|
+
callbacks.on_train_begin()
|
|
171
|
+
logs = {}
|
|
172
|
+
for epoch in range(initial_epoch, epochs):
|
|
173
|
+
callbacks.on_epoch_begin(epoch)
|
|
174
|
+
order = np.arange(len(x))
|
|
175
|
+
if shuffle:
|
|
176
|
+
np.random.shuffle(order)
|
|
177
|
+
total = 0.0
|
|
178
|
+
metric_total = 0.0
|
|
179
|
+
seen = 0
|
|
180
|
+
for batch, start in enumerate(range(0, len(x), batch_size)):
|
|
181
|
+
callbacks.on_train_batch_begin(batch)
|
|
182
|
+
rows = order[start : start + batch_size]
|
|
183
|
+
xb = tensorc.Tensor(np.ascontiguousarray(x[rows]))
|
|
184
|
+
yb = tensorc.Tensor(np.ascontiguousarray(y[rows]))
|
|
185
|
+
prediction = self(xb, training=True)
|
|
186
|
+
loss_tensor = prediction.mse_loss(yb)
|
|
187
|
+
count = len(rows)
|
|
188
|
+
total += float(loss_tensor.data[0]) * count
|
|
189
|
+
batch_metrics = {"loss": float(loss_tensor.data[0])}
|
|
190
|
+
if metric_name:
|
|
191
|
+
batch_metric = np.mean(
|
|
192
|
+
np.abs(convert_to_numpy(prediction) - y[rows])
|
|
193
|
+
)
|
|
194
|
+
metric_total += float(batch_metric) * count
|
|
195
|
+
batch_metrics[metric_name] = float(batch_metric)
|
|
196
|
+
seen += count
|
|
197
|
+
logs = batch_metrics
|
|
198
|
+
learning_rate = float(
|
|
199
|
+
np.asarray(convert_to_numpy(self.optimizer.learning_rate)).item()
|
|
200
|
+
)
|
|
201
|
+
if use_adam:
|
|
202
|
+
self._adam_step(loss_tensor, learning_rate)
|
|
203
|
+
else:
|
|
204
|
+
loss_tensor.backward()
|
|
205
|
+
for variable in self.trainable_variables:
|
|
206
|
+
variable.value.sgd_step(learning_rate)
|
|
207
|
+
variable.value.zero_grad()
|
|
208
|
+
optimizer.iterations.assign(optimizer.iterations.numpy() + 1)
|
|
209
|
+
callbacks.on_train_batch_end(batch, logs)
|
|
210
|
+
if self.stop_training:
|
|
211
|
+
break
|
|
212
|
+
logs = {"loss": total / seen}
|
|
213
|
+
if metric_name:
|
|
214
|
+
logs[metric_name] = metric_total / seen
|
|
215
|
+
if val_x is not None and (epoch + 1) % validation_freq == 0:
|
|
216
|
+
callbacks.on_test_begin()
|
|
217
|
+
val_total = 0.0
|
|
218
|
+
val_metric_total = 0.0
|
|
219
|
+
val_seen = 0
|
|
220
|
+
for batch, start in enumerate(range(0, len(val_x), validation_batch_size)):
|
|
221
|
+
callbacks.on_test_batch_begin(batch)
|
|
222
|
+
rows = slice(start, start + validation_batch_size)
|
|
223
|
+
prediction = self(
|
|
224
|
+
tensorc.Tensor(np.ascontiguousarray(val_x[rows])),
|
|
225
|
+
training=False,
|
|
226
|
+
)
|
|
227
|
+
loss_value = float(
|
|
228
|
+
prediction.mse_loss(
|
|
229
|
+
tensorc.Tensor(np.ascontiguousarray(val_y[rows]))
|
|
230
|
+
).data[0]
|
|
231
|
+
)
|
|
232
|
+
count = len(val_x[rows])
|
|
233
|
+
val_total += loss_value * count
|
|
234
|
+
val_batch_logs = {"loss": loss_value}
|
|
235
|
+
if metric_name:
|
|
236
|
+
val_metric = float(np.mean(np.abs(
|
|
237
|
+
convert_to_numpy(prediction) - val_y[rows]
|
|
238
|
+
)))
|
|
239
|
+
val_metric_total += val_metric * count
|
|
240
|
+
val_batch_logs[metric_name] = val_metric
|
|
241
|
+
val_seen += count
|
|
242
|
+
callbacks.on_test_batch_end(batch, val_batch_logs)
|
|
243
|
+
val_logs = {"loss": val_total / val_seen}
|
|
244
|
+
if metric_name:
|
|
245
|
+
val_logs[metric_name] = val_metric_total / val_seen
|
|
246
|
+
callbacks.on_test_end(val_logs)
|
|
247
|
+
logs.update({f"val_{name}": value for name, value in val_logs.items()})
|
|
248
|
+
callbacks.on_epoch_end(epoch, logs)
|
|
249
|
+
if self.stop_training:
|
|
250
|
+
break
|
|
251
|
+
callbacks.on_train_end(logs)
|
|
252
|
+
return self.history
|
|
253
|
+
|
|
254
|
+
def predict(self, x, batch_size=None, verbose="auto", steps=None, callbacks=None):
|
|
255
|
+
del verbose
|
|
256
|
+
if steps is not None or callbacks:
|
|
257
|
+
raise NotImplementedError("steps and callbacks are not supported yet")
|
|
258
|
+
x = np.asarray(x, dtype=np.float32)
|
|
259
|
+
batch_size = int(batch_size or len(x))
|
|
260
|
+
outputs = []
|
|
261
|
+
for start in range(0, len(x), batch_size):
|
|
262
|
+
batch = tensorc.Tensor(np.ascontiguousarray(x[start : start + batch_size]))
|
|
263
|
+
outputs.append(convert_to_numpy(self(batch, training=False)))
|
|
264
|
+
return np.concatenate(outputs, axis=0)
|
|
265
|
+
|
|
266
|
+
def test_step(self, data):
|
|
267
|
+
x, y, _ = data_adapter_utils.unpack_x_y_sample_weight(data)
|
|
268
|
+
prediction = self(tensorc.Tensor(np.ascontiguousarray(x)), training=False)
|
|
269
|
+
loss = prediction.mse_loss(tensorc.Tensor(np.ascontiguousarray(y)))
|
|
270
|
+
return {"loss": float(loss.data[0])}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
import tensorc
|
|
4
|
+
from keras.src.backend.common import KerasVariable
|
|
5
|
+
|
|
6
|
+
from keras_tensorc.src.ops.core import _tensor
|
|
7
|
+
from keras_tensorc.src.ops.core import convert_to_numpy
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Variable(KerasVariable):
|
|
11
|
+
def _initialize(self, value):
|
|
12
|
+
if self.dtype != "float32":
|
|
13
|
+
if self.trainable:
|
|
14
|
+
raise NotImplementedError(
|
|
15
|
+
"trainable TensorC Keras variables must use float32"
|
|
16
|
+
)
|
|
17
|
+
self._value = np.asarray(convert_to_numpy(value), dtype=self.dtype)
|
|
18
|
+
return
|
|
19
|
+
self._value = _tensor(
|
|
20
|
+
convert_to_numpy(value), requires_grad=self.trainable
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
def _direct_assign(self, value):
|
|
24
|
+
if not isinstance(self._value, tensorc.Tensor):
|
|
25
|
+
self._value[...] = convert_to_numpy(value)
|
|
26
|
+
return
|
|
27
|
+
self._value.copy_(_tensor(value))
|
|
28
|
+
|
|
29
|
+
def _convert_to_tensor(self, value, dtype=None):
|
|
30
|
+
if dtype not in (None, "float32", np.float32):
|
|
31
|
+
if self.trainable:
|
|
32
|
+
raise NotImplementedError(
|
|
33
|
+
"trainable TensorC Keras variables must use float32"
|
|
34
|
+
)
|
|
35
|
+
return np.asarray(convert_to_numpy(value), dtype=dtype)
|
|
36
|
+
return _tensor(value)
|
|
37
|
+
|
|
38
|
+
def __array__(self, dtype=None, *, copy=None):
|
|
39
|
+
value = convert_to_numpy(self.value)
|
|
40
|
+
if copy is None:
|
|
41
|
+
return np.asarray(value, dtype=dtype)
|
|
42
|
+
return np.array(value, dtype=dtype, copy=copy)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: keras-tensorc
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Experimental Keras backend powered by TensorC
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: numpy>=1.20
|
|
8
|
+
Requires-Dist: tensorc>=0.17.0
|
|
9
|
+
|
|
10
|
+
# Keras backend experimental para TensorC
|
|
11
|
+
|
|
12
|
+
Prototipo de backend enchufable para Keras. Requiere el código actual de Keras
|
|
13
|
+
con soporte de backends no oficiales; la versión estable de Keras aún no expone
|
|
14
|
+
este punto de extensión. No es compatible con `KERAS_BACKEND=tensorc` en Keras
|
|
15
|
+
3.15.x.
|
|
16
|
+
|
|
17
|
+
La API de backends enchufables todavía está en desarrollo y Keras no publica
|
|
18
|
+
esa versión en PyPI. Instala primero Keras desde su repositorio y luego este
|
|
19
|
+
paquete (que instala TensorC y NumPy):
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
python -m pip install git+https://github.com/keras-team/keras.git
|
|
23
|
+
python -m pip install keras-tensorc
|
|
24
|
+
KERAS_BACKEND=tensorc KERAS_ALLOW_UNOFFICIAL_BACKEND=1 \
|
|
25
|
+
python integrations/keras-tensorc/examples/dense_fit.py
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
La dependencia de Keras se instala por separado porque la versión estable de
|
|
29
|
+
PyPI aún no admite este backend experimental.
|
|
30
|
+
|
|
31
|
+
El prototipo cubre `Sequential` y `Input → Dense → Model` con datos NumPy, CPU y
|
|
32
|
+
`float32`. También admite `Conv2D` en formato channels-last, con sesgo, strides
|
|
33
|
+
y padding `valid`/`same`; grupos, dilatación y channels-first no están
|
|
34
|
+
implementados. Para entrenamiento admite MSE, SGD sin momentum y Adam con
|
|
35
|
+
betas/epsilon predeterminados; `fit` ejecuta
|
|
36
|
+
callbacks, respeta `model.stop_training`, soporta validación NumPy y las
|
|
37
|
+
métricas `"mae"`/`"mean_absolute_error"`. Los momentos de Adam se conservan
|
|
38
|
+
entre llamadas a `fit` en el mismo proceso. El roundtrip `.keras` está probado
|
|
39
|
+
para `Sequential(Dense)`; guardar el modelo no guarda los momentos de Adam para
|
|
40
|
+
reanudar el entrenamiento. Sample/class weights y datasets siguen fuera de
|
|
41
|
+
alcance.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
keras_tensorc/__init__.py
|
|
4
|
+
keras_tensorc.egg-info/PKG-INFO
|
|
5
|
+
keras_tensorc.egg-info/SOURCES.txt
|
|
6
|
+
keras_tensorc.egg-info/dependency_links.txt
|
|
7
|
+
keras_tensorc.egg-info/requires.txt
|
|
8
|
+
keras_tensorc.egg-info/top_level.txt
|
|
9
|
+
keras_tensorc/src/__init__.py
|
|
10
|
+
keras_tensorc/src/random.py
|
|
11
|
+
keras_tensorc/src/trainer.py
|
|
12
|
+
keras_tensorc/src/variable.py
|
|
13
|
+
keras_tensorc/src/version.py
|
|
14
|
+
keras_tensorc/src/ops/__init__.py
|
|
15
|
+
keras_tensorc/src/ops/core.py
|
|
16
|
+
keras_tensorc/src/ops/nn.py
|
|
17
|
+
keras_tensorc/src/ops/numpy.py
|
|
18
|
+
tests/test_adam.py
|
|
19
|
+
tests/test_conv2d.py
|
|
20
|
+
tests/test_dense_fit.py
|
|
21
|
+
tests/test_functional.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
keras_tensorc
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=64"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "keras-tensorc"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Experimental Keras backend powered by TensorC"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
dependencies = ["numpy>=1.20", "tensorc>=0.17.0"]
|
|
12
|
+
|
|
13
|
+
[tool.setuptools.packages.find]
|
|
14
|
+
include = ["keras_tensorc*"]
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import math
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
import pytest
|
|
6
|
+
import tensorc
|
|
7
|
+
|
|
8
|
+
os.environ["KERAS_BACKEND"] = "tensorc"
|
|
9
|
+
os.environ["KERAS_ALLOW_UNOFFICIAL_BACKEND"] = "1"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@pytest.mark.parametrize("epsilon_hat", [None, 1e-7])
|
|
13
|
+
def test_native_adam_epsilon(epsilon_hat):
|
|
14
|
+
weight = tensorc.Tensor([0.0], requires_grad=True)
|
|
15
|
+
optimizer = tensorc.Adam([weight], 0.001, epsilon_hat=epsilon_hat)
|
|
16
|
+
expected = momentum = velocity = 0.0
|
|
17
|
+
|
|
18
|
+
for step, gradient in enumerate([1e-6, -3e-6, 2e-6], start=1):
|
|
19
|
+
weight.mul(tensorc.Tensor([gradient])).sum().backward()
|
|
20
|
+
assert optimizer.step() == 1
|
|
21
|
+
weight.zero_grad()
|
|
22
|
+
|
|
23
|
+
momentum = 0.9 * momentum + 0.1 * gradient
|
|
24
|
+
velocity = 0.999 * velocity + 0.001 * gradient**2
|
|
25
|
+
if epsilon_hat is None:
|
|
26
|
+
expected -= 0.001 * momentum / (1 - 0.9**step) / (
|
|
27
|
+
math.sqrt(velocity / (1 - 0.999**step)) + 1e-8
|
|
28
|
+
)
|
|
29
|
+
else:
|
|
30
|
+
alpha = 0.001 * math.sqrt(1 - 0.999**step) / (1 - 0.9**step)
|
|
31
|
+
expected -= alpha * momentum / (math.sqrt(velocity) + epsilon_hat)
|
|
32
|
+
assert weight.data[0] == pytest.approx(expected, abs=3e-8)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_native_adam_large_epsilon_hat_preserves_nonzero_update():
|
|
36
|
+
epsilon_hat = 1e38
|
|
37
|
+
gradient = 1e10
|
|
38
|
+
weight = tensorc.Tensor([0.0], requires_grad=True)
|
|
39
|
+
optimizer = tensorc.Adam([weight], 1.0, epsilon_hat=epsilon_hat)
|
|
40
|
+
weight.mul(tensorc.Tensor([gradient])).sum().backward()
|
|
41
|
+
assert optimizer.step() == 1
|
|
42
|
+
|
|
43
|
+
scaled_gradient = math.sqrt(1 - 0.999) * gradient
|
|
44
|
+
expected = -scaled_gradient / (scaled_gradient + epsilon_hat)
|
|
45
|
+
assert weight.data[0] == pytest.approx(expected, rel=3e-5, abs=0.0)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def test_keras_adam_updates_dense_weights_across_fit_calls():
|
|
49
|
+
import keras
|
|
50
|
+
|
|
51
|
+
x = np.linspace(-1, 1, 16, dtype="float32").reshape(-1, 1)
|
|
52
|
+
y = 2 * x + 0.5
|
|
53
|
+
|
|
54
|
+
def compiled_model():
|
|
55
|
+
model = keras.Sequential([
|
|
56
|
+
keras.Input(shape=(1,)),
|
|
57
|
+
keras.layers.Dense(1, kernel_initializer="zeros"),
|
|
58
|
+
])
|
|
59
|
+
model.compile(optimizer=keras.optimizers.Adam(0.05), loss="mse")
|
|
60
|
+
return model
|
|
61
|
+
|
|
62
|
+
model = compiled_model()
|
|
63
|
+
continuous = compiled_model()
|
|
64
|
+
initial = model.get_weights()
|
|
65
|
+
first = model.fit(x, y, epochs=3, batch_size=8, shuffle=False, verbose=0)
|
|
66
|
+
second = model.fit(x, y, epochs=7, batch_size=8, shuffle=False, verbose=0)
|
|
67
|
+
continuous.fit(x, y, epochs=10, batch_size=8, shuffle=False, verbose=0)
|
|
68
|
+
|
|
69
|
+
assert second.history["loss"][-1] < first.history["loss"][0]
|
|
70
|
+
assert int(model.optimizer.iterations.numpy()) == 20
|
|
71
|
+
for before, after, expected in zip(
|
|
72
|
+
initial, model.get_weights(), continuous.get_weights()
|
|
73
|
+
):
|
|
74
|
+
assert not np.array_equal(before, after)
|
|
75
|
+
np.testing.assert_allclose(after, expected, rtol=1e-6)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@pytest.mark.parametrize(
|
|
79
|
+
"config",
|
|
80
|
+
[
|
|
81
|
+
{"beta_1": 0.8},
|
|
82
|
+
{"epsilon": 1e-8},
|
|
83
|
+
{"amsgrad": True},
|
|
84
|
+
{"clipnorm": 1.0},
|
|
85
|
+
{"learning_rate": lambda: 0.05},
|
|
86
|
+
],
|
|
87
|
+
)
|
|
88
|
+
def test_keras_adam_rejects_unsupported_options(config):
|
|
89
|
+
import keras
|
|
90
|
+
|
|
91
|
+
x = np.ones((2, 1), dtype="float32")
|
|
92
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
93
|
+
model.compile(optimizer=keras.optimizers.Adam(**config), loss="mse")
|
|
94
|
+
|
|
95
|
+
with pytest.raises(NotImplementedError, match="Adam"):
|
|
96
|
+
model.fit(x, x, verbose=0)
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
os.environ["KERAS_BACKEND"] = "tensorc"
|
|
4
|
+
os.environ["KERAS_ALLOW_UNOFFICIAL_BACKEND"] = "1"
|
|
5
|
+
|
|
6
|
+
import keras
|
|
7
|
+
import numpy as np
|
|
8
|
+
import tensorc
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_conv2d_channels_last_with_bias_and_strides():
|
|
12
|
+
x = np.arange(24, dtype="float32").reshape(1, 3, 4, 2)
|
|
13
|
+
kernel = np.zeros((2, 2, 2, 2), dtype="float32")
|
|
14
|
+
kernel[0, 0, 0, 0] = 1
|
|
15
|
+
kernel[1, 1, 1, 0] = 2
|
|
16
|
+
kernel[0, 1, 1, 1] = -1
|
|
17
|
+
kernel[1, 0, 0, 1] = 3
|
|
18
|
+
layer = keras.layers.Conv2D(
|
|
19
|
+
2,
|
|
20
|
+
(2, 2),
|
|
21
|
+
strides=(1, 2),
|
|
22
|
+
data_format="channels_last",
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
layer.build(x.shape)
|
|
26
|
+
layer.set_weights([kernel, np.array([1, -2], dtype="float32")])
|
|
27
|
+
|
|
28
|
+
result = keras.ops.convert_to_numpy(layer(x))
|
|
29
|
+
|
|
30
|
+
assert result.shape == (1, 2, 2, 2)
|
|
31
|
+
np.testing.assert_array_equal(
|
|
32
|
+
result, [[[[23, 19], [35, 27]], [[47, 35], [59, 43]]]]
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def test_conv2d_same_padding_preserves_input_gradients():
|
|
37
|
+
x = tensorc.Tensor(
|
|
38
|
+
np.arange(1, 10, dtype="float32").reshape(1, 3, 3, 1),
|
|
39
|
+
requires_grad=True,
|
|
40
|
+
)
|
|
41
|
+
layer = keras.layers.Conv2D(
|
|
42
|
+
1, 4, strides=2, padding="same", use_bias=False, kernel_initializer="ones"
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
result = layer(x)
|
|
46
|
+
result.sum().backward()
|
|
47
|
+
|
|
48
|
+
assert result.shape == (1, 2, 2, 1)
|
|
49
|
+
np.testing.assert_array_equal(
|
|
50
|
+
keras.ops.convert_to_numpy(result)[0, :, :, 0], [[45, 33], [39, 28]]
|
|
51
|
+
)
|
|
52
|
+
np.testing.assert_array_equal(x.grad, [1, 2, 2, 2, 4, 4, 2, 4, 4])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_conv2d_fit_updates_kernel_and_bias():
|
|
56
|
+
x = np.ones((2, 2, 2, 1), dtype="float32")
|
|
57
|
+
layer = keras.layers.Conv2D(1, 1, kernel_initializer="zeros")
|
|
58
|
+
model = keras.Sequential([keras.Input(shape=x.shape[1:]), layer])
|
|
59
|
+
model.compile(optimizer=keras.optimizers.SGD(0.1), loss="mse")
|
|
60
|
+
|
|
61
|
+
history = model.fit(x, 3 * x, epochs=2, batch_size=2, shuffle=False, verbose=0)
|
|
62
|
+
|
|
63
|
+
np.testing.assert_allclose(history.history["loss"], [9, 3.24], rtol=1e-6)
|
|
64
|
+
np.testing.assert_allclose(keras.ops.convert_to_numpy(layer.kernel), 0.96, rtol=1e-6)
|
|
65
|
+
np.testing.assert_allclose(keras.ops.convert_to_numpy(layer.bias), 0.96, rtol=1e-6)
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import tempfile
|
|
3
|
+
|
|
4
|
+
os.environ["KERAS_BACKEND"] = "tensorc"
|
|
5
|
+
os.environ["KERAS_ALLOW_UNOFFICIAL_BACKEND"] = "1"
|
|
6
|
+
|
|
7
|
+
import keras
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def test_keras_dense_trains_on_tensorc():
|
|
13
|
+
x = np.linspace(-1, 1, 16, dtype="float32").reshape(-1, 1)
|
|
14
|
+
y = 2 * x + 0.5
|
|
15
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
16
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse")
|
|
17
|
+
|
|
18
|
+
history = model.fit(x, y, epochs=30, batch_size=16, shuffle=False, verbose=0)
|
|
19
|
+
|
|
20
|
+
assert history.history["loss"][-1] < history.history["loss"][0]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_fit_runs_callbacks_and_honors_stop_training():
|
|
24
|
+
x = np.linspace(-1, 1, 16, dtype="float32").reshape(-1, 1)
|
|
25
|
+
y = 2 * x + 0.5
|
|
26
|
+
|
|
27
|
+
class StopAfterFirstEpoch(keras.callbacks.Callback):
|
|
28
|
+
def __init__(self):
|
|
29
|
+
super().__init__()
|
|
30
|
+
self.events = []
|
|
31
|
+
|
|
32
|
+
def on_train_begin(self, logs=None):
|
|
33
|
+
self.events.append("train_begin")
|
|
34
|
+
|
|
35
|
+
def on_epoch_end(self, epoch, logs=None):
|
|
36
|
+
self.events.append(("epoch_end", epoch, "loss" in logs))
|
|
37
|
+
self.model.stop_training = True
|
|
38
|
+
|
|
39
|
+
def on_train_end(self, logs=None):
|
|
40
|
+
self.events.append("train_end")
|
|
41
|
+
|
|
42
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
43
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse")
|
|
44
|
+
callback = StopAfterFirstEpoch()
|
|
45
|
+
|
|
46
|
+
history = model.fit(x, y, epochs=5, batch_size=8, verbose=0, callbacks=[callback])
|
|
47
|
+
|
|
48
|
+
assert callback.events == ["train_begin", ("epoch_end", 0, True), "train_end"]
|
|
49
|
+
assert history.epoch == [0]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def test_sgd_iterations_are_updated_before_batch_callbacks():
|
|
53
|
+
x = np.ones((4, 1), dtype="float32")
|
|
54
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
55
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse")
|
|
56
|
+
|
|
57
|
+
class RecordIterations(keras.callbacks.Callback):
|
|
58
|
+
def __init__(self):
|
|
59
|
+
super().__init__()
|
|
60
|
+
self.iterations = []
|
|
61
|
+
|
|
62
|
+
def on_train_batch_end(self, batch, logs=None):
|
|
63
|
+
self.iterations.append(int(self.model.optimizer.iterations.numpy()))
|
|
64
|
+
|
|
65
|
+
callback = RecordIterations()
|
|
66
|
+
model.fit(x, x, epochs=1, batch_size=2, verbose=0, callbacks=[callback])
|
|
67
|
+
|
|
68
|
+
assert callback.iterations == [1, 2]
|
|
69
|
+
assert int(model.optimizer.iterations.numpy()) == 2
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@pytest.mark.parametrize(
|
|
73
|
+
"fit_kwargs",
|
|
74
|
+
[
|
|
75
|
+
{"sample_weight": np.ones(2, dtype="float32")},
|
|
76
|
+
{"class_weight": {}},
|
|
77
|
+
],
|
|
78
|
+
)
|
|
79
|
+
def test_fit_rejects_unsupported_weights_even_when_empty(fit_kwargs):
|
|
80
|
+
x = np.ones((2, 1), dtype="float32")
|
|
81
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
82
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse")
|
|
83
|
+
|
|
84
|
+
with pytest.raises(NotImplementedError, match="weights"):
|
|
85
|
+
model.fit(x, x, verbose=0, **fit_kwargs)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@pytest.mark.parametrize(
|
|
89
|
+
"compile_kwargs, unsupported",
|
|
90
|
+
[
|
|
91
|
+
({"loss_weights": [0.0]}, "loss_weights"),
|
|
92
|
+
({"weighted_metrics": ["mae"]}, "weighted_metrics"),
|
|
93
|
+
],
|
|
94
|
+
)
|
|
95
|
+
def test_fit_rejects_ignored_compile_options(compile_kwargs, unsupported):
|
|
96
|
+
x = np.ones((2, 1), dtype="float32")
|
|
97
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
98
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse", **compile_kwargs)
|
|
99
|
+
|
|
100
|
+
with pytest.raises(NotImplementedError, match=unsupported):
|
|
101
|
+
model.fit(x, x, verbose=0)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@pytest.mark.parametrize(
|
|
105
|
+
"sgd_kwargs",
|
|
106
|
+
[
|
|
107
|
+
{"clipvalue": 0.1},
|
|
108
|
+
{"weight_decay": 0.1},
|
|
109
|
+
{"nesterov": True},
|
|
110
|
+
{"use_ema": True},
|
|
111
|
+
],
|
|
112
|
+
)
|
|
113
|
+
def test_fit_rejects_unsupported_sgd_options(sgd_kwargs):
|
|
114
|
+
x = np.ones((2, 1), dtype="float32")
|
|
115
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
116
|
+
model.compile(
|
|
117
|
+
optimizer=keras.optimizers.SGD(0.05, **sgd_kwargs), loss="mse"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
with pytest.raises(NotImplementedError, match="SGD"):
|
|
121
|
+
model.fit(x, x, verbose=0)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def test_fit_reports_mae_metric():
|
|
125
|
+
x = np.linspace(-1, 1, 16, dtype="float32").reshape(-1, 1)
|
|
126
|
+
y = 2 * x + 0.5
|
|
127
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
128
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse", metrics=["mae"])
|
|
129
|
+
|
|
130
|
+
history = model.fit(x, y, epochs=2, batch_size=16, shuffle=False, verbose=0)
|
|
131
|
+
|
|
132
|
+
assert "mae" in history.history
|
|
133
|
+
assert len(history.history["mae"]) == 2
|
|
134
|
+
assert np.isfinite(history.history["mae"]).all()
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def test_keras_archive_round_trip():
|
|
138
|
+
x = np.linspace(-1, 1, 16, dtype="float32").reshape(-1, 1)
|
|
139
|
+
y = 2 * x + 0.5
|
|
140
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
141
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse")
|
|
142
|
+
model.fit(x, y, epochs=2, batch_size=16, shuffle=False, verbose=0)
|
|
143
|
+
expected = model.predict(x, verbose=0)
|
|
144
|
+
|
|
145
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
146
|
+
path = os.path.join(directory, "model.keras")
|
|
147
|
+
model.save(path)
|
|
148
|
+
restored = keras.models.load_model(path)
|
|
149
|
+
|
|
150
|
+
np.testing.assert_allclose(restored.predict(x, verbose=0), expected)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def test_fit_reports_validation_loss():
|
|
154
|
+
x = np.linspace(-1, 1, 20, dtype="float32").reshape(-1, 1)
|
|
155
|
+
y = 2 * x + 0.5
|
|
156
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
157
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse")
|
|
158
|
+
|
|
159
|
+
history = model.fit(
|
|
160
|
+
x, y, epochs=2, batch_size=8, validation_split=0.2, shuffle=False, verbose=0
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
assert "val_loss" in history.history
|
|
164
|
+
assert len(history.history["val_loss"]) == 2
|
|
165
|
+
assert np.isfinite(history.history["val_loss"]).all()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def test_fit_accepts_validation_pair_and_frequency():
|
|
169
|
+
x = np.linspace(-1, 1, 20, dtype="float32").reshape(-1, 1)
|
|
170
|
+
y = 2 * x + 0.5
|
|
171
|
+
model = keras.Sequential([keras.layers.Dense(1)])
|
|
172
|
+
model.compile(optimizer=keras.optimizers.SGD(0.05), loss="mse")
|
|
173
|
+
|
|
174
|
+
history = model.fit(
|
|
175
|
+
x[:16], y[:16], epochs=2, batch_size=8,
|
|
176
|
+
validation_data=(x[16:], y[16:]), validation_freq=2, verbose=0
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
assert len(history.history["val_loss"]) == 1
|
|
180
|
+
assert np.isfinite(history.history["val_loss"][0])
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
if __name__ == "__main__":
|
|
184
|
+
test_keras_dense_trains_on_tensorc()
|
|
185
|
+
test_fit_runs_callbacks_and_honors_stop_training()
|
|
186
|
+
test_fit_reports_mae_metric()
|
|
187
|
+
test_keras_archive_round_trip()
|
|
188
|
+
test_fit_reports_validation_loss()
|
|
189
|
+
test_fit_accepts_validation_pair_and_frequency()
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
os.environ["KERAS_BACKEND"] = "tensorc"
|
|
4
|
+
os.environ["KERAS_ALLOW_UNOFFICIAL_BACKEND"] = "1"
|
|
5
|
+
|
|
6
|
+
import keras
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_functional_dense_predicts_and_trains():
|
|
11
|
+
inputs = keras.Input(shape=(1,), dtype="float32")
|
|
12
|
+
outputs = keras.layers.Dense(1, kernel_initializer="ones")(inputs)
|
|
13
|
+
model = keras.Model(inputs, outputs)
|
|
14
|
+
x = np.array([[-1], [0], [1]], dtype="float32")
|
|
15
|
+
y = 2 * x + 1
|
|
16
|
+
|
|
17
|
+
assert keras.backend.backend() == "tensorc"
|
|
18
|
+
assert model.output_shape == (None, 1)
|
|
19
|
+
np.testing.assert_allclose(keras.ops.convert_to_numpy(model(x)), x)
|
|
20
|
+
np.testing.assert_allclose(model.predict(x, batch_size=2, verbose=0), x)
|
|
21
|
+
model.compile(optimizer=keras.optimizers.SGD(0.1), loss="mse")
|
|
22
|
+
initial_kernel, initial_bias = model.get_weights()
|
|
23
|
+
history = model.fit(x, y, epochs=2, batch_size=3, shuffle=False, verbose=0)
|
|
24
|
+
|
|
25
|
+
kernel, bias = model.get_weights()
|
|
26
|
+
assert not np.array_equal(kernel, initial_kernel)
|
|
27
|
+
assert not np.array_equal(bias, initial_bias)
|
|
28
|
+
assert history.history["loss"][1] < history.history["loss"][0]
|
|
29
|
+
assert np.mean((model.predict(x, verbose=0) - y) ** 2) < history.history["loss"][1]
|