keras-tensorc 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- keras_tensorc/__init__.py +1 -0
- keras_tensorc/src/__init__.py +39 -0
- keras_tensorc/src/ops/__init__.py +44 -0
- keras_tensorc/src/ops/core.py +96 -0
- keras_tensorc/src/ops/nn.py +51 -0
- keras_tensorc/src/ops/numpy.py +35 -0
- keras_tensorc/src/random.py +44 -0
- keras_tensorc/src/trainer.py +270 -0
- keras_tensorc/src/variable.py +42 -0
- keras_tensorc/src/version.py +1 -0
- keras_tensorc-0.1.0.dist-info/METADATA +41 -0
- keras_tensorc-0.1.0.dist-info/RECORD +14 -0
- keras_tensorc-0.1.0.dist-info/WHEEL +5 -0
- keras_tensorc-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -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,14 @@
|
|
|
1
|
+
keras_tensorc/__init__.py,sha256=aCbrJE-m3EX5PaI6tT8ZSyN89B80bdMVEbZiqhkm2qw,50
|
|
2
|
+
keras_tensorc/src/__init__.py,sha256=NwVzd8DDWX308urC6ELgqkdtr-a7iwoHvSFE00YW8uE,1086
|
|
3
|
+
keras_tensorc/src/random.py,sha256=WZRNh7nk7PbhkAou0BkXgjyl9aVpYR_0gYqkyfc5U6I,1379
|
|
4
|
+
keras_tensorc/src/trainer.py,sha256=LS7OjR14Z6PGlVxzfs_3YXSJmAz-jYrhc2_maJtfwnM,12340
|
|
5
|
+
keras_tensorc/src/variable.py,sha256=c8FQKlX6lLQ88AX9Lu6ATstIPzWwjwzTCK_RL1OYAgA,1473
|
|
6
|
+
keras_tensorc/src/version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
|
|
7
|
+
keras_tensorc/src/ops/__init__.py,sha256=-tfDM6_ZTt3STHbciAAy6VXio33_GY3EmI4VPqXnmWI,1305
|
|
8
|
+
keras_tensorc/src/ops/core.py,sha256=kSdc37ij7aSradHDjb1pd9tmSLbmCKeW6egaEjXBQfo,3086
|
|
9
|
+
keras_tensorc/src/ops/nn.py,sha256=06jJ3YFaBikXMGmObqjRZRdcc1wGCH_t07wF5bsSU0A,2067
|
|
10
|
+
keras_tensorc/src/ops/numpy.py,sha256=a_erGZ--nl2iznzSQgTh7ZnEDRSReYJst-9WlL_-tQ4,757
|
|
11
|
+
keras_tensorc-0.1.0.dist-info/METADATA,sha256=aJ0fMdGl5Uh65lbQvZ1yC3BCbiWq0AAIjlr6Fr_DgaI,1833
|
|
12
|
+
keras_tensorc-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
13
|
+
keras_tensorc-0.1.0.dist-info/top_level.txt,sha256=SVcY_q5nkfnoaeOr6g9jBtpSv8pdiJLzIySGfHGxyKI,14
|
|
14
|
+
keras_tensorc-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
keras_tensorc
|