typeras 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.
typeras/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ from importlib.metadata import version
2
+
3
+ from typeras import callbacks as callbacks
4
+ from typeras import datasets as datasets
5
+ from typeras import layers as layers
6
+ from typeras import losses as losses
7
+ from typeras import metrics as metrics
8
+ from typeras import models as models
9
+ from typeras import optimizers as optimizers
10
+
11
+ __version__ = version("typeras")
@@ -0,0 +1,2 @@
1
+ from typeras.callbacks.callback import Callback as Callback
2
+ from typeras.callbacks.progress_bar import ProgressBar as ProgressBar
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC
4
+ from typing import TYPE_CHECKING
5
+
6
+ if TYPE_CHECKING:
7
+ from typeras.models.model import Model
8
+
9
+
10
+ class Callback(ABC):
11
+ def __init__(self) -> None:
12
+ self._model = None
13
+
14
+ @property
15
+ def model(self) -> Model:
16
+ if self._model is None:
17
+ raise RuntimeError
18
+ return self._model
19
+
20
+ def build(self, model: Model) -> None:
21
+ self._model = model
22
+
23
+ def on_train_epoch_end(self, epoch: int, logs: dict[str, float]) -> None:
24
+ pass
25
+
26
+ def on_test_end(self, logs: dict[str, float]) -> None:
27
+ pass
@@ -0,0 +1,16 @@
1
+ from typeras.callbacks.callback import Callback
2
+
3
+
4
+ class ProgressBar(Callback):
5
+ def __init__(self) -> None:
6
+ super().__init__()
7
+
8
+ def on_train_epoch_end(self, epoch: int, logs: dict[str, float]) -> None:
9
+ log = f"Epoch {epoch + 1:{len(str(self.model.epochs))}d}/{self.model.epochs}: "
10
+ log += " - ".join(f"{k}: {v:.4f}" for k, v in logs.items())
11
+ print(log)
12
+
13
+ def on_test_end(self, logs: dict[str, float]) -> None:
14
+ log = "Evaluation: "
15
+ log += " - ".join(f"{k}: {v:.4f}" for k, v in logs.items())
16
+ print(log)
@@ -0,0 +1 @@
1
+ from typeras.datasets import breast_cancer as breast_cancer
@@ -0,0 +1,36 @@
1
+ from pathlib import Path
2
+ from typing import Annotated
3
+
4
+ import polars as pl
5
+ import requests
6
+ from dltype import FloatTensor, IntTensor, dltyped
7
+ from torch import Tensor
8
+ from typeguard import typechecked
9
+
10
+ URL = "https://assets.startown.ai/datasets/breast-cancer/data.csv"
11
+
12
+
13
+ @dltyped()
14
+ @typechecked
15
+ def load_data(
16
+ path: str | Path = "~/.typeras/datasets/breast_cancer",
17
+ ) -> tuple[
18
+ Annotated[Tensor, FloatTensor["n_samples=569 n_features=30"]],
19
+ Annotated[Tensor, IntTensor["n_samples=569 n_targets=1"]],
20
+ ]:
21
+ path = Path(path).expanduser()
22
+ path.mkdir(parents=True, exist_ok=True)
23
+
24
+ data_file = path / "data.csv"
25
+ if not data_file.exists():
26
+ response = requests.get(URL, timeout=30)
27
+ response.raise_for_status()
28
+ data_file.write_text(response.text)
29
+
30
+ df = pl.read_csv(data_file)
31
+ df = df.with_columns(pl.col("diagnosis").replace(["B", "M"], [0, 1]).cast(pl.Int64))
32
+
33
+ x = df.select(pl.col(pl.Float64)).to_torch(dtype=pl.Float32)
34
+ y = df.get_column("diagnosis").to_torch().unsqueeze(1)
35
+
36
+ return x, y
@@ -0,0 +1,5 @@
1
+ from typeras.layers import activations as activations
2
+ from typeras.layers.activations.sigmoid import Sigmoid as Sigmoid
3
+ from typeras.layers.dense import Dense as Dense
4
+ from typeras.layers.identity import Identity as Identity
5
+ from typeras.layers.layer import Layer as Layer
@@ -0,0 +1 @@
1
+ from typeras.layers.activations.sigmoid import Sigmoid as Sigmoid
@@ -0,0 +1,20 @@
1
+ from typing import Annotated
2
+
3
+ from dltype import FloatTensor, dltyped
4
+ from torch import Tensor, nn
5
+ from typeguard import typechecked
6
+
7
+ from typeras.layers.layer import Layer
8
+
9
+
10
+ @typechecked
11
+ class Sigmoid(Layer):
12
+ def __init__(self, name: str = "sigmoid") -> None:
13
+ super().__init__(name)
14
+
15
+ @dltyped()
16
+ def call(
17
+ self,
18
+ x: Annotated[Tensor, FloatTensor["..."]],
19
+ ) -> Annotated[Tensor, FloatTensor["..."]]:
20
+ return nn.Sigmoid()(x)
@@ -0,0 +1,60 @@
1
+ from typing import Annotated
2
+
3
+ from dltype import FloatTensor, dltyped
4
+ from torch import Tensor, nn
5
+ from typeguard import typechecked
6
+
7
+ from typeras.layers.identity import Identity
8
+ from typeras.layers.layer import Layer
9
+
10
+
11
+ @typechecked
12
+ class Dense(Layer):
13
+ def __init__(
14
+ self,
15
+ units: int,
16
+ activation: Layer | None = None,
17
+ use_bias: bool = True,
18
+ name: str = "dense",
19
+ ) -> None:
20
+ super().__init__(name)
21
+ self._units = units
22
+ self._activation = activation or Identity()
23
+ self._use_bias = use_bias
24
+
25
+ self._linear = None
26
+
27
+ @property
28
+ def units(self) -> int:
29
+ return self._units
30
+
31
+ @property
32
+ def activation(self) -> Layer:
33
+ return self._activation
34
+
35
+ @property
36
+ def use_bias(self) -> bool:
37
+ return self._use_bias
38
+
39
+ @property
40
+ def linear(self) -> nn.Linear:
41
+ if self._linear is None:
42
+ raise RuntimeError
43
+ return self._linear
44
+
45
+ def build(self, input_shape: tuple[int, ...]) -> None:
46
+ if self._is_built:
47
+ return
48
+
49
+ self._linear = nn.Linear(input_shape[-1], self.units, self.use_bias)
50
+ self._is_built = True
51
+
52
+ @dltyped(scope_provider="self")
53
+ def call(
54
+ self,
55
+ x: Annotated[Tensor, FloatTensor["... in_features"]],
56
+ ) -> Annotated[Tensor, FloatTensor["... out_features"]]:
57
+ return self.activation(self.linear(x))
58
+
59
+ def get_dltype_scope(self) -> dict[str, int]:
60
+ return {"out_features": self.units}
@@ -0,0 +1,20 @@
1
+ from typing import Annotated
2
+
3
+ from dltype import FloatTensor, dltyped
4
+ from torch import Tensor, nn
5
+ from typeguard import typechecked
6
+
7
+ from typeras.layers.layer import Layer
8
+
9
+
10
+ @typechecked
11
+ class Identity(Layer):
12
+ def __init__(self, name: str = "identity") -> None:
13
+ super().__init__(name)
14
+
15
+ @dltyped()
16
+ def call(
17
+ self,
18
+ x: Annotated[Tensor, FloatTensor["..."]],
19
+ ) -> Annotated[Tensor, FloatTensor["..."]]:
20
+ return nn.Identity()(x)
@@ -0,0 +1,30 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ from torch import Tensor, nn
4
+
5
+
6
+ class Layer(ABC, nn.Module):
7
+ def __init__(self, name: str) -> None:
8
+ super().__init__()
9
+ self._name = name
10
+ self._is_built = False
11
+
12
+ @property
13
+ def name(self) -> str:
14
+ return self._name
15
+
16
+ @property
17
+ def is_built(self) -> bool:
18
+ return self._is_built
19
+
20
+ def build(self, input_shape: tuple[int, ...]) -> None:
21
+ if self._is_built:
22
+ return
23
+ self._is_built = True
24
+
25
+ @abstractmethod
26
+ def call(self, x: Tensor) -> Tensor: ...
27
+
28
+ def forward(self, x: Tensor) -> Tensor:
29
+ self.build(x.shape)
30
+ return self.call(x)
@@ -0,0 +1,2 @@
1
+ from typeras.losses.crossentropies import BinaryCrossentropy as BinaryCrossentropy
2
+ from typeras.losses.loss import Loss as Loss
@@ -0,0 +1,84 @@
1
+ from typing import Annotated
2
+
3
+ import torch
4
+ from dltype import FloatTensor, IntTensor, dltyped
5
+ from torch import Tensor, nn
6
+ from typeguard import typechecked
7
+
8
+ from typeras.losses.loss import Loss
9
+
10
+
11
+ @typechecked
12
+ class BinaryCrossentropy(Loss):
13
+ def __init__(
14
+ self,
15
+ from_logits: bool = False,
16
+ name: str = "binary_crossentropy",
17
+ ) -> None:
18
+ super().__init__(name)
19
+ self._from_logits = from_logits
20
+
21
+ self._value_batch = torch.tensor([])
22
+ self._value_sum = torch.tensor(0.0)
23
+ self._total = torch.tensor(0)
24
+ self._criterion = (
25
+ nn.BCELoss(reduction="none")
26
+ if not from_logits
27
+ else nn.BCEWithLogitsLoss(reduction="none")
28
+ )
29
+
30
+ @property
31
+ def from_logits(self) -> bool:
32
+ return self._from_logits
33
+
34
+ @property
35
+ @dltyped()
36
+ def value_batch(self) -> Annotated[Tensor, FloatTensor["batch_size n_features=1"]]:
37
+ return self._value_batch
38
+
39
+ @property
40
+ @dltyped()
41
+ def value_sum(self) -> Annotated[Tensor, FloatTensor[None]]:
42
+ return self._value_sum
43
+
44
+ @property
45
+ @dltyped()
46
+ def total(self) -> Annotated[Tensor, IntTensor[None]]:
47
+ return self._total
48
+
49
+ @property
50
+ def criterion(self) -> nn.BCELoss | nn.BCEWithLogitsLoss:
51
+ return self._criterion
52
+
53
+ @property
54
+ @dltyped()
55
+ def value(self) -> Annotated[Tensor, FloatTensor[None]]:
56
+ if self.total == 0:
57
+ return torch.tensor(0.0)
58
+ return self.value_sum / self.total
59
+
60
+ @dltyped()
61
+ def call(
62
+ self,
63
+ y_pred: Annotated[Tensor, FloatTensor["batch_size n_features=1"]],
64
+ y_true: Annotated[Tensor, IntTensor["batch_size n_features=1"]],
65
+ ) -> Annotated[Tensor, FloatTensor[None]]:
66
+ return self.criterion(y_pred, y_true.float()).mean()
67
+
68
+ @dltyped()
69
+ def update(
70
+ self,
71
+ y_pred: Annotated[Tensor, FloatTensor["batch_size n_features=1"]],
72
+ y_true: Annotated[Tensor, IntTensor["batch_size n_features=1"]],
73
+ ) -> None:
74
+ self._value_batch = self.criterion(y_pred, y_true.float())
75
+ self._value_sum += self.value_batch.detach().sum()
76
+ self._total += y_pred.size(0)
77
+
78
+ def reset(self) -> None:
79
+ self._value_batch = torch.tensor([])
80
+ self._value_sum = torch.tensor(0.0)
81
+ self._total = torch.tensor(0)
82
+
83
+ def backward(self) -> None:
84
+ self.value_batch.mean().backward()
typeras/losses/loss.py ADDED
@@ -0,0 +1,31 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ from torch import Tensor
4
+
5
+
6
+ class Loss(ABC):
7
+ def __init__(self, name: str) -> None:
8
+ self._name = name
9
+
10
+ def __call__(self, y_pred: Tensor, y_true: Tensor) -> Tensor:
11
+ return self.call(y_pred, y_true)
12
+
13
+ @property
14
+ def name(self) -> str:
15
+ return self._name
16
+
17
+ @property
18
+ @abstractmethod
19
+ def value(self) -> Tensor: ...
20
+
21
+ @abstractmethod
22
+ def call(self, y_pred: Tensor, y_true: Tensor) -> Tensor: ...
23
+
24
+ @abstractmethod
25
+ def update(self, y_pred: Tensor, y_true: Tensor) -> None: ...
26
+
27
+ @abstractmethod
28
+ def reset(self) -> None: ...
29
+
30
+ @abstractmethod
31
+ def backward(self) -> None: ...
@@ -0,0 +1,2 @@
1
+ from typeras.metrics.accuracies import Accuracy as Accuracy
2
+ from typeras.metrics.accuracies import BinaryAccuracy as BinaryAccuracy
@@ -0,0 +1,110 @@
1
+ from typing import Annotated
2
+
3
+ import torch
4
+ from dltype import FloatTensor, IntTensor, dltyped
5
+ from torch import Tensor
6
+ from typeguard import typechecked
7
+
8
+ from typeras.metrics.metric import Metric
9
+
10
+
11
+ @typechecked
12
+ class Accuracy(Metric):
13
+ def __init__(self, name: str = "accuracy") -> None:
14
+ super().__init__(name)
15
+ self._count = torch.tensor(0)
16
+ self._total = torch.tensor(0)
17
+
18
+ @property
19
+ @dltyped()
20
+ def count(self) -> Annotated[Tensor, IntTensor[None]]:
21
+ return self._count
22
+
23
+ @property
24
+ @dltyped()
25
+ def total(self) -> Annotated[Tensor, IntTensor[None]]:
26
+ return self._total
27
+
28
+ @property
29
+ @dltyped()
30
+ def value(self) -> Annotated[Tensor, FloatTensor[None]]:
31
+ if self.total == 0:
32
+ return torch.tensor(0.0)
33
+ return self.count / self.total
34
+
35
+ @dltyped()
36
+ def call(
37
+ self,
38
+ y_pred: Annotated[Tensor, IntTensor["batch_size n_features=1"]],
39
+ y_true: Annotated[Tensor, IntTensor["batch_size n_features=1"]],
40
+ ) -> Annotated[Tensor, FloatTensor[None]]:
41
+ count = (y_pred == y_true).long().sum()
42
+ total = y_pred.size(0)
43
+ return count / total
44
+
45
+ @dltyped()
46
+ def update(
47
+ self,
48
+ y_pred: Annotated[Tensor, IntTensor["batch_size n_features=1"]],
49
+ y_true: Annotated[Tensor, IntTensor["batch_size n_features=1"]],
50
+ ) -> None:
51
+ self._count += (y_pred == y_true).long().sum()
52
+ self._total += y_pred.size(0)
53
+
54
+ def reset(self) -> None:
55
+ self._count = torch.tensor(0)
56
+ self._total = torch.tensor(0)
57
+
58
+
59
+ @typechecked
60
+ class BinaryAccuracy(Metric):
61
+ def __init__(self, threshold: float = 0.5, name: str = "binary_accuracy") -> None:
62
+ super().__init__(name)
63
+ self._threshold = torch.tensor(float(threshold))
64
+ self._count = torch.tensor(0)
65
+ self._total = torch.tensor(0)
66
+
67
+ @property
68
+ @dltyped()
69
+ def threshold(self) -> Annotated[Tensor, FloatTensor[None]]:
70
+ return self._threshold
71
+
72
+ @property
73
+ @dltyped()
74
+ def count(self) -> Annotated[Tensor, IntTensor[None]]:
75
+ return self._count
76
+
77
+ @property
78
+ @dltyped()
79
+ def total(self) -> Annotated[Tensor, IntTensor[None]]:
80
+ return self._total
81
+
82
+ @property
83
+ @dltyped()
84
+ def value(self) -> Annotated[Tensor, FloatTensor[None]]:
85
+ if self.total == 0:
86
+ return torch.tensor(0.0)
87
+ return self.count / self.total
88
+
89
+ @dltyped()
90
+ def call(
91
+ self,
92
+ y_pred: Annotated[Tensor, FloatTensor["batch_size n_features=1"]],
93
+ y_true: Annotated[Tensor, IntTensor["batch_size n_features=1"]],
94
+ ) -> Annotated[Tensor, FloatTensor[None]]:
95
+ count = ((y_pred > self.threshold) == y_true).long().sum()
96
+ total = y_pred.size(0)
97
+ return count / total
98
+
99
+ @dltyped()
100
+ def update(
101
+ self,
102
+ y_pred: Annotated[Tensor, FloatTensor["batch_size n_features=1"]],
103
+ y_true: Annotated[Tensor, IntTensor["batch_size n_features=1"]],
104
+ ) -> None:
105
+ self._count += ((y_pred > self.threshold) == y_true).long().sum()
106
+ self._total += y_pred.size(0)
107
+
108
+ def reset(self) -> None:
109
+ self._count = torch.tensor(0)
110
+ self._total = torch.tensor(0)
@@ -0,0 +1,28 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ from torch import Tensor
4
+
5
+
6
+ class Metric(ABC):
7
+ def __init__(self, name: str) -> None:
8
+ self._name = name
9
+
10
+ def __call__(self, y_pred: Tensor, y_true: Tensor) -> Tensor:
11
+ return self.call(y_pred, y_true)
12
+
13
+ @property
14
+ def name(self) -> str:
15
+ return self._name
16
+
17
+ @property
18
+ @abstractmethod
19
+ def value(self) -> Tensor: ...
20
+
21
+ @abstractmethod
22
+ def call(self, y_pred: Tensor, y_true: Tensor) -> Tensor: ...
23
+
24
+ @abstractmethod
25
+ def update(self, y_pred: Tensor, y_true: Tensor) -> None: ...
26
+
27
+ @abstractmethod
28
+ def reset(self) -> None: ...
@@ -0,0 +1 @@
1
+ from typeras.models.model import Model as Model
@@ -0,0 +1,178 @@
1
+ from abc import ABC, abstractmethod
2
+ from collections.abc import Sequence
3
+ from typing import Annotated
4
+
5
+ import torch
6
+ from dltype import FloatTensor, IntTensor, dltyped
7
+ from torch import Tensor, nn
8
+ from torch.utils.data import DataLoader, TensorDataset
9
+ from typeguard import typechecked
10
+
11
+ from typeras.callbacks.callback import Callback
12
+ from typeras.losses.loss import Loss
13
+ from typeras.metrics.metric import Metric
14
+ from typeras.optimizers.optimizer import Optimizer
15
+
16
+
17
+ @typechecked
18
+ class Model(ABC, nn.Module):
19
+ def __init__(self, name: str) -> None:
20
+ super().__init__()
21
+ self._name = name
22
+ self._optimizer = None
23
+ self._loss = None
24
+ self._metrics = None
25
+ self._is_built = False
26
+ self._batch_size = 32
27
+ self._epochs = 1
28
+ self._callbacks = []
29
+
30
+ @property
31
+ def name(self) -> str:
32
+ return self._name
33
+
34
+ @property
35
+ def optimizer(self) -> Optimizer:
36
+ if self._optimizer is None:
37
+ raise RuntimeError
38
+ return self._optimizer
39
+
40
+ @property
41
+ def loss(self) -> Loss:
42
+ if self._loss is None:
43
+ raise RuntimeError
44
+ return self._loss
45
+
46
+ @property
47
+ def metrics(self) -> list[Metric]:
48
+ if self._metrics is None:
49
+ raise RuntimeError
50
+ return self._metrics
51
+
52
+ @property
53
+ def batch_size(self) -> int:
54
+ return self._batch_size
55
+
56
+ @property
57
+ def epochs(self) -> int:
58
+ return self._epochs
59
+
60
+ @property
61
+ def callbacks(self) -> list[Callback]:
62
+ return self._callbacks
63
+
64
+ def forward(
65
+ self,
66
+ x: Annotated[Tensor, FloatTensor["batch_size ..."]],
67
+ ) -> Annotated[Tensor, FloatTensor["batch_size ..."]]:
68
+ return self.call(x)
69
+
70
+ def build(self, input_shape: tuple[int, ...]) -> None:
71
+ if self._is_built:
72
+ return
73
+
74
+ with torch.no_grad():
75
+ self(torch.zeros((1, *input_shape[1:])))
76
+ self.optimizer.build(self.parameters())
77
+ self._is_built = True
78
+
79
+ @abstractmethod
80
+ def call(
81
+ self,
82
+ x: Annotated[Tensor, FloatTensor["batch_size ..."]],
83
+ ) -> Annotated[Tensor, FloatTensor["batch_size ..."]]: ...
84
+
85
+ def compile(
86
+ self,
87
+ optimizer: Optimizer,
88
+ loss: Loss,
89
+ metrics: Sequence[Metric] | None = None,
90
+ ) -> None:
91
+ self._optimizer = optimizer
92
+ self._loss = loss
93
+ self._metrics = list(metrics) if metrics is not None else []
94
+
95
+ @dltyped()
96
+ def fit(
97
+ self,
98
+ x: Annotated[Tensor, FloatTensor["batch_size ..."]],
99
+ y: Annotated[Tensor, IntTensor["batch_size ..."]],
100
+ batch_size: int = 32,
101
+ epochs: int = 1,
102
+ callbacks: Sequence[Callback] | None = None,
103
+ ) -> None:
104
+ self._batch_size = batch_size
105
+ self._epochs = epochs
106
+ self._callbacks = list(callbacks) if callbacks is not None else []
107
+
108
+ for callback in self.callbacks:
109
+ callback.build(self)
110
+
111
+ data_loader = DataLoader(
112
+ dataset=TensorDataset(x, y),
113
+ batch_size=batch_size,
114
+ shuffle=True,
115
+ )
116
+
117
+ self.build(x.shape)
118
+
119
+ for epoch in range(epochs):
120
+ self.train()
121
+
122
+ for x_train, y_train in data_loader:
123
+ y_pred = self(x_train)
124
+
125
+ self.loss.update(y_pred, y_train)
126
+ self.loss.backward()
127
+
128
+ self.optimizer.step()
129
+ self.optimizer.zero_grad()
130
+
131
+ for metric in self.metrics:
132
+ metric.update(y_pred, y_train)
133
+
134
+ logs = {
135
+ self.loss.name: self.loss.value.item(),
136
+ **{m.name: m.value.item() for m in self.metrics},
137
+ }
138
+ for callback in self.callbacks:
139
+ callback.on_train_epoch_end(epoch, logs)
140
+
141
+ self.loss.reset()
142
+ for metric in self.metrics:
143
+ metric.reset()
144
+
145
+ @dltyped()
146
+ def evaluate(
147
+ self,
148
+ x: Annotated[Tensor, FloatTensor["batch_size ..."]],
149
+ y: Annotated[Tensor, IntTensor["batch_size ..."]],
150
+ batch_size: int = 32,
151
+ ) -> None:
152
+ data_loader = DataLoader(
153
+ dataset=TensorDataset(x, y),
154
+ batch_size=batch_size,
155
+ shuffle=False,
156
+ )
157
+
158
+ self.build(x.shape)
159
+
160
+ self.eval()
161
+ with torch.no_grad():
162
+ for x_test, y_test in data_loader:
163
+ y_pred = self(x_test)
164
+
165
+ self.loss.update(y_pred, y_test)
166
+ for metric in self.metrics:
167
+ metric.update(y_pred, y_test)
168
+
169
+ logs = {
170
+ self.loss.name: self.loss.value.item(),
171
+ **{m.name: m.value.item() for m in self.metrics},
172
+ }
173
+ for callback in self.callbacks:
174
+ callback.on_test_end(logs)
175
+
176
+ self.loss.reset()
177
+ for metric in self.metrics:
178
+ metric.reset()
@@ -0,0 +1,2 @@
1
+ from typeras.optimizers.adam import Adam as Adam
2
+ from typeras.optimizers.optimizer import Optimizer as Optimizer
@@ -0,0 +1,25 @@
1
+ from collections.abc import Iterable
2
+ from typing import Annotated
3
+
4
+ import torch
5
+ from dltype import FloatTensor, dltyped
6
+ from torch import Tensor, nn, optim
7
+ from typeguard import typechecked
8
+
9
+ from typeras.optimizers.optimizer import Optimizer
10
+
11
+
12
+ @typechecked
13
+ class Adam(Optimizer):
14
+ def __init__(self, learning_rate: float = 1e-3, name: str = "adam") -> None:
15
+ super().__init__(name)
16
+ self._learning_rate = torch.tensor(learning_rate)
17
+
18
+ @property
19
+ @dltyped()
20
+ def learning_rate(self) -> Annotated[Tensor, FloatTensor[None]]:
21
+ return self._learning_rate
22
+
23
+ def build(self, params: Iterable[nn.Parameter]) -> None:
24
+ self._optimizer = optim.Adam(params, lr=self.learning_rate)
25
+ self._is_built = True
@@ -0,0 +1,36 @@
1
+ from abc import ABC, abstractmethod
2
+ from collections.abc import Iterable
3
+
4
+ from torch import nn, optim
5
+ from typeguard import typechecked
6
+
7
+
8
+ @typechecked
9
+ class Optimizer(ABC):
10
+ def __init__(self, name: str) -> None:
11
+ self._name = name
12
+ self._is_built = False
13
+ self._optimizer = None
14
+
15
+ @property
16
+ def name(self) -> str:
17
+ return self._name
18
+
19
+ @property
20
+ def is_built(self) -> bool:
21
+ return self._is_built
22
+
23
+ @property
24
+ def optimizer(self) -> optim.Optimizer:
25
+ if self._optimizer is None:
26
+ raise RuntimeError
27
+ return self._optimizer
28
+
29
+ @abstractmethod
30
+ def build(self, params: Iterable[nn.Parameter]) -> None: ...
31
+
32
+ def zero_grad(self) -> None:
33
+ self.optimizer.zero_grad()
34
+
35
+ def step(self) -> None:
36
+ self.optimizer.step()
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: typeras
3
+ Version: 0.1.0
4
+ Summary: A type-safe, Keras-like deep learning library built on PyTorch.
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.12
8
+ Requires-Dist: dltype>=0.16.0
9
+ Requires-Dist: numpy>=2.5.1
10
+ Requires-Dist: polars>=1.43.2
11
+ Requires-Dist: requests>=2.34.2
12
+ Requires-Dist: safetensors>=0.8.0
13
+ Requires-Dist: torch>=2.13.0
14
+ Requires-Dist: typeguard>=4.6.0
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Typeras
18
+
19
+ A type-safe, Keras-like deep learning library built on PyTorch.
@@ -0,0 +1,27 @@
1
+ typeras/__init__.py,sha256=P6xzZ3uqndqYdMKsWfs7skA61NXkSO7mFE6U5_XFZ8I,352
2
+ typeras/callbacks/__init__.py,sha256=0ImAGmeTCDrm-1kv4so0nWk-_nh7Pm1eHZQ87lWmplY,130
3
+ typeras/callbacks/callback.py,sha256=aC8E7HGDIw_rDfEKwDtNDcDJ44h29lKlg-LUWDIdZ88,605
4
+ typeras/callbacks/progress_bar.py,sha256=WVffckidDMjwS5lK0ECdQ7Y1CpKjIfdk8SSuhjq2yeg,568
5
+ typeras/datasets/__init__.py,sha256=vr8uRzr2buA4UnL9aX9AwHmRNFY8VMB8KTHf7_vcc3c,60
6
+ typeras/datasets/breast_cancer.py,sha256=KtOU5IPgL0CM6EVpdeF52dZA7x31l0SUQaGUzIL_Lrc,1053
7
+ typeras/layers/__init__.py,sha256=9Pa7oW0JmoCuy0cVv6JW_tX-0H2puhCrQ4qJisoZ-J4,273
8
+ typeras/layers/dense.py,sha256=j27dV3daNRtBiD9m0b25U6hWtA-zRBhGxY3Vep22viM,1510
9
+ typeras/layers/identity.py,sha256=GIHQeUycNvlCvNiFRD6G__0byNR3M1y2sZ6FbS_6Xfg,472
10
+ typeras/layers/layer.py,sha256=uJAtHab9kO3X8ZbnQI1sniy0UVktwkM8eJQMOf8LsPE,672
11
+ typeras/layers/activations/__init__.py,sha256=s26Ci6-xKxz5YNvTMCzO3nwR-zufcmRBpCEeRAwfQPQ,66
12
+ typeras/layers/activations/sigmoid.py,sha256=IHwFmnkFS2Xl-m2a1ZrVfOofxPt8gKQxukbnstjYPEg,469
13
+ typeras/losses/__init__.py,sha256=hD355TyHkQP1WisGIEodoagT7Zf9SHLxMx235BTf8O0,128
14
+ typeras/losses/crossentropies.py,sha256=kmVYL3sRF3JhBjYCaCo7MkvD2bC2BxmxXDvLFb4I0FQ,2421
15
+ typeras/losses/loss.py,sha256=VphqAbGzxBHDUd4daKAnAUjIUmh8W1qfWdWMb9qIxTo,681
16
+ typeras/metrics/__init__.py,sha256=Ebof2iLpl7LmI4xqelp-Gp5Xn9R-Prs1WpXymttLvsQ,132
17
+ typeras/metrics/accuracies.py,sha256=8rKw2_iASfii2UBioHhsW_woRjCbIO4IX1SM9G94sFs,3218
18
+ typeras/metrics/metric.py,sha256=LWs9e5kJTrihQOMd52Se33guTOwwkmDN7hh_fHlOcnk,626
19
+ typeras/models/__init__.py,sha256=Qa6GqjWcMJeM8eOwRuuHzqkbEgtklX1Enql-wCeidLE,48
20
+ typeras/models/model.py,sha256=Klr5lBMuma98G-nTfW8FfuG0SSy0V3YwIwDYHwYYgc0,4879
21
+ typeras/optimizers/__init__.py,sha256=PWbyBvaVYmNQC4l5VTKF-1H4CirxjtTS-OL9GVH38po,113
22
+ typeras/optimizers/adam.py,sha256=LJi2-JBmsAYHooGH2Ld5D7SYbw85RQGGNzowF5Y-BZA,744
23
+ typeras/optimizers/optimizer.py,sha256=DjMHwX0MiYB9uj5lB1kJ3KWmscCq3fbk5Bx5wA1_vvI,820
24
+ typeras-0.1.0.dist-info/METADATA,sha256=zri14iFvN-9zkuWVS-yqX-47HTOAJb71DaH1ZtIK_DM,531
25
+ typeras-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
26
+ typeras-0.1.0.dist-info/licenses/LICENSE,sha256=wP_qAjLl2mpvlTFrm0ZNc_QCz9CSIhbsiwCfJov433k,11338
27
+ typeras-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 StarTown
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.