tributo-algorithms 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.
Files changed (110) hide show
  1. tributo_algorithms-0.1.0.dist-info/METADATA +328 -0
  2. tributo_algorithms-0.1.0.dist-info/RECORD +110 -0
  3. tributo_algorithms-0.1.0.dist-info/WHEEL +4 -0
  4. tributo_algorithms-0.1.0.dist-info/entry_points.txt +57 -0
  5. tributo_algorithms-0.1.0.dist-info/licenses/LICENSE +202 -0
  6. tributo_algorithms_boosting/__init__.py +42 -0
  7. tributo_algorithms_boosting/algorithm.py +825 -0
  8. tributo_algorithms_boosting/checkpointing.py +441 -0
  9. tributo_algorithms_boosting/contracts.py +232 -0
  10. tributo_algorithms_boosting/data_config.py +59 -0
  11. tributo_algorithms_boosting/descriptor.py +124 -0
  12. tributo_algorithms_boosting/lightgbm.py +511 -0
  13. tributo_algorithms_boosting/lightgbm_contracts.py +186 -0
  14. tributo_algorithms_boosting/lightgbm_descriptor.py +112 -0
  15. tributo_algorithms_boosting/native.py +557 -0
  16. tributo_algorithms_boosting/stages.py +150 -0
  17. tributo_algorithms_catboost/__init__.py +5 -0
  18. tributo_algorithms_catboost/algorithm.py +379 -0
  19. tributo_algorithms_catboost/contracts.py +145 -0
  20. tributo_algorithms_catboost/descriptor.py +121 -0
  21. tributo_algorithms_catboost/exporter.py +106 -0
  22. tributo_algorithms_catboost/flavor.py +191 -0
  23. tributo_algorithms_causal_core/__init__.py +41 -0
  24. tributo_algorithms_causal_core/algorithm.py +1193 -0
  25. tributo_algorithms_causal_core/contracts.py +136 -0
  26. tributo_algorithms_causal_core/descriptor.py +270 -0
  27. tributo_algorithms_causal_core/exporter.py +52 -0
  28. tributo_algorithms_causal_discovery/__init__.py +23 -0
  29. tributo_algorithms_causal_discovery/algorithm.py +526 -0
  30. tributo_algorithms_causal_discovery/contracts.py +97 -0
  31. tributo_algorithms_causal_discovery/descriptor.py +130 -0
  32. tributo_algorithms_causal_discovery/exporter.py +43 -0
  33. tributo_algorithms_causal_dowhy/__init__.py +38 -0
  34. tributo_algorithms_causal_dowhy/algorithm.py +325 -0
  35. tributo_algorithms_causal_dowhy/contracts.py +209 -0
  36. tributo_algorithms_causal_dowhy/descriptor.py +106 -0
  37. tributo_algorithms_causal_dowhy/exporter.py +43 -0
  38. tributo_algorithms_causal_dowhy/gcm.py +634 -0
  39. tributo_algorithms_causal_dowhy/gcm_descriptor.py +110 -0
  40. tributo_algorithms_causal_dr/__init__.py +22 -0
  41. tributo_algorithms_causal_dr/algorithm.py +446 -0
  42. tributo_algorithms_causal_dr/contracts.py +94 -0
  43. tributo_algorithms_causal_dr/descriptor.py +104 -0
  44. tributo_algorithms_causal_xlearner/__init__.py +29 -0
  45. tributo_algorithms_causal_xlearner/algorithm.py +448 -0
  46. tributo_algorithms_causal_xlearner/contracts.py +97 -0
  47. tributo_algorithms_causal_xlearner/descriptor.py +120 -0
  48. tributo_algorithms_causal_xlearner/exporter.py +432 -0
  49. tributo_algorithms_causal_xlearner/flavor.py +120 -0
  50. tributo_algorithms_causal_xlearner/model.py +116 -0
  51. tributo_algorithms_classical/__init__.py +41 -0
  52. tributo_algorithms_classical/contracts.py +139 -0
  53. tributo_algorithms_classical/descriptors.py +370 -0
  54. tributo_algorithms_classical/exporter.py +166 -0
  55. tributo_algorithms_classical/isolation_forest.py +172 -0
  56. tributo_algorithms_classical/isolation_forest_descriptor.py +122 -0
  57. tributo_algorithms_classical/kmeans.py +315 -0
  58. tributo_algorithms_classical/kmeans_descriptor.py +147 -0
  59. tributo_algorithms_classical/linear_regression.py +206 -0
  60. tributo_algorithms_classical/logistic_regression.py +238 -0
  61. tributo_algorithms_classical/models.py +28 -0
  62. tributo_algorithms_classical/multinomial_nb.py +643 -0
  63. tributo_algorithms_classical/multinomial_nb_descriptor.py +183 -0
  64. tributo_algorithms_classical/pca.py +187 -0
  65. tributo_algorithms_classical/pca_descriptor.py +111 -0
  66. tributo_algorithms_classical/random_forest.py +304 -0
  67. tributo_algorithms_classical/sgd.py +331 -0
  68. tributo_algorithms_classical/sgd_contracts.py +121 -0
  69. tributo_algorithms_classical/sgd_descriptor.py +143 -0
  70. tributo_algorithms_classical/unsupervised_contracts.py +198 -0
  71. tributo_algorithms_classical/unsupervised_exporter.py +427 -0
  72. tributo_algorithms_classical/unsupervised_models.py +90 -0
  73. tributo_algorithms_graph_pyg/__init__.py +37 -0
  74. tributo_algorithms_graph_pyg/algorithm.py +883 -0
  75. tributo_algorithms_graph_pyg/contracts.py +260 -0
  76. tributo_algorithms_graph_pyg/descriptor.py +201 -0
  77. tributo_algorithms_multistage_torch/__init__.py +40 -0
  78. tributo_algorithms_multistage_torch/algorithm.py +532 -0
  79. tributo_algorithms_multistage_torch/contracts.py +220 -0
  80. tributo_algorithms_multistage_torch/descriptor.py +146 -0
  81. tributo_algorithms_multistage_torch/pretrain.py +570 -0
  82. tributo_algorithms_multistage_torch/pretrain_descriptor.py +153 -0
  83. tributo_algorithms_recsys_torch/__init__.py +35 -0
  84. tributo_algorithms_recsys_torch/contracts.py +295 -0
  85. tributo_algorithms_recsys_torch/descriptor.py +136 -0
  86. tributo_algorithms_recsys_torch/jagged.py +707 -0
  87. tributo_algorithms_recsys_torch/jagged_descriptor.py +130 -0
  88. tributo_algorithms_recsys_torch/recipe.py +192 -0
  89. tributo_algorithms_representation/__init__.py +20 -0
  90. tributo_algorithms_representation/contracts.py +117 -0
  91. tributo_algorithms_representation/descriptor.py +137 -0
  92. tributo_algorithms_representation/recipe.py +162 -0
  93. tributo_algorithms_tabular_torch/__init__.py +46 -0
  94. tributo_algorithms_tabular_torch/contracts.py +228 -0
  95. tributo_algorithms_tabular_torch/descriptor.py +223 -0
  96. tributo_algorithms_tabular_torch/priors.py +216 -0
  97. tributo_algorithms_tabular_torch/pu_metrics.py +269 -0
  98. tributo_algorithms_tabular_torch/pu_reducer.py +129 -0
  99. tributo_algorithms_tabular_torch/recipe.py +294 -0
  100. tributo_algorithms_timeseries/__init__.py +36 -0
  101. tributo_algorithms_timeseries/contracts.py +120 -0
  102. tributo_algorithms_timeseries/descriptor.py +137 -0
  103. tributo_algorithms_timeseries/recipe.py +195 -0
  104. tributo_algorithms_timeseries/rnn_contracts.py +170 -0
  105. tributo_algorithms_timeseries/rnn_descriptor.py +167 -0
  106. tributo_algorithms_timeseries/rnn_recipe.py +223 -0
  107. tributo_algorithms_transformers_nlp/__init__.py +20 -0
  108. tributo_algorithms_transformers_nlp/contracts.py +109 -0
  109. tributo_algorithms_transformers_nlp/descriptor.py +137 -0
  110. tributo_algorithms_transformers_nlp/recipe.py +235 -0
@@ -0,0 +1,235 @@
1
+ """Typed TorchRecipe for pre-tokenized Transformer classification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any, cast
7
+
8
+ from tributo.algorithms.api.torch_runtime import (
9
+ TorchLossContribution,
10
+ TorchMetricContribution,
11
+ )
12
+ from tributo.algorithms.spi import (
13
+ TorchArtifactContext,
14
+ TorchArtifactPlan,
15
+ TorchBatch,
16
+ TorchBatchContext,
17
+ TorchBuildContext,
18
+ TorchMetricPlan,
19
+ TorchModuleSet,
20
+ TorchOptimizationPlan,
21
+ TorchRecipe,
22
+ TorchRuntimeContext,
23
+ TorchStepContext,
24
+ TorchStepResult,
25
+ )
26
+
27
+
28
+ def _integer_tensor(value: object, field_name: str) -> Any:
29
+ import torch
30
+
31
+ tensor = torch.as_tensor(value)
32
+ if tensor.dtype == torch.bool or tensor.is_floating_point() or tensor.is_complex():
33
+ raise ValueError(f"{field_name} must contain integer values")
34
+ return tensor.to(dtype=torch.int64)
35
+
36
+
37
+ def _model(
38
+ *, vocab_size: int, sequence_length: int, hidden_size: int, heads: int
39
+ ) -> object:
40
+ import torch
41
+
42
+ if (
43
+ vocab_size < 2
44
+ or sequence_length < 1
45
+ or hidden_size < 1
46
+ or heads < 1
47
+ or hidden_size % heads
48
+ ):
49
+ raise ValueError("Transformer dimensions are invalid")
50
+
51
+ class TokenTransformerClassifier(torch.nn.Module):
52
+ def __init__(self) -> None:
53
+ super().__init__()
54
+ self.sequence_length = sequence_length
55
+ self.embedding = torch.nn.Embedding(vocab_size, hidden_size, padding_idx=0)
56
+ layer = torch.nn.TransformerEncoderLayer(
57
+ d_model=hidden_size,
58
+ nhead=heads,
59
+ dim_feedforward=hidden_size * 2,
60
+ batch_first=True,
61
+ dropout=0.0,
62
+ )
63
+ self.encoder = torch.nn.TransformerEncoder(layer, num_layers=1)
64
+ self.output = torch.nn.Linear(hidden_size, 1)
65
+
66
+ def forward(self, values: object) -> object:
67
+ tokens = cast(torch.Tensor, values)
68
+ if tokens.ndim != 2 or tokens.shape[1] != sequence_length:
69
+ raise ValueError(
70
+ "Transformer input must have shape [batch, sequence_length]"
71
+ )
72
+ if bool((tokens < 0).any()) or bool((tokens >= vocab_size).any()):
73
+ raise ValueError("Transformer token IDs are out of range")
74
+ padding_mask = tokens.eq(0)
75
+ if bool(padding_mask.all(dim=1).any()):
76
+ raise ValueError("Transformer rows must contain a non-padding token")
77
+ encoded = self.encoder(
78
+ self.embedding(tokens), src_key_padding_mask=padding_mask
79
+ )
80
+ valid = (~padding_mask).to(encoded.dtype).unsqueeze(-1)
81
+ pooled = (encoded * valid).sum(dim=1) / valid.sum(dim=1).clamp_min(1.0)
82
+ return self.output(pooled)
83
+
84
+ return TokenTransformerClassifier()
85
+
86
+
87
+ def _batch(batch: object, context: TorchBatchContext) -> TorchBatch:
88
+ import torch
89
+
90
+ if not isinstance(batch, Mapping):
91
+ raise ValueError("Transformer batch must be columnar")
92
+ feature_names = context.feature_names or tuple(
93
+ name for name in batch if name not in {context.label_name, context.weight_name}
94
+ )
95
+ label_name = context.label_name or ("label" if "label" in batch else None)
96
+ if not feature_names or label_name is None:
97
+ raise ValueError("Transformer requires input_ids and label")
98
+ if context.weight_name is not None:
99
+ raise ValueError("Transformer does not support sample-weight binding")
100
+ if len(feature_names) == 1 and feature_names[0] == "input_ids":
101
+ tokens = _integer_tensor(batch[feature_names[0]], "Transformer token IDs")
102
+ else:
103
+ tokens = torch.stack(
104
+ [
105
+ _integer_tensor(batch[name], "Transformer token IDs")
106
+ for name in feature_names
107
+ ],
108
+ dim=1,
109
+ )
110
+ targets = torch.as_tensor(batch[label_name], dtype=torch.float32).reshape(-1, 1)
111
+ if bool((tokens < 0).any()) or not torch.isfinite(targets).all():
112
+ raise ValueError("Transformer inputs are malformed")
113
+ if not bool(((targets == 0) | (targets == 1)).all()):
114
+ raise ValueError("Transformer labels must be 0 or 1")
115
+ if bool(tokens.eq(0).all(dim=1).any()):
116
+ raise ValueError("Transformer rows must contain a non-padding token")
117
+ rows = int(tokens.shape[0])
118
+ return TorchBatch(
119
+ keyword={"input_ids": tokens},
120
+ targets=targets,
121
+ local_rows=rows,
122
+ )
123
+
124
+
125
+ def _accuracy(predictions: object, targets: object) -> TorchMetricContribution:
126
+ import torch
127
+
128
+ logits = cast(torch.Tensor, predictions).reshape(-1)
129
+ labels = cast(torch.Tensor, targets).reshape(-1)
130
+ return TorchMetricContribution(
131
+ float((torch.sigmoid(logits) >= 0.5).eq(labels >= 0.5).sum().item()),
132
+ int(labels.numel()),
133
+ )
134
+
135
+
136
+ class TokenTransformerRecipe(TorchRecipe):
137
+ """Train a Transformer over pre-tokenized integer IDs with derived padding mask."""
138
+
139
+ def build_modules(self, context: TorchBuildContext) -> TorchModuleSet:
140
+ import torch
141
+
142
+ config = context.runtime.algorithm_config.get("model", {})
143
+ if not isinstance(config, Mapping):
144
+ raise ValueError("Transformer model config must be a mapping")
145
+ return TorchModuleSet(
146
+ {
147
+ "model": _model(
148
+ vocab_size=int(config.get("vocab_size", 128)),
149
+ sequence_length=int(config.get("sequence_length", 8)),
150
+ hidden_size=int(config.get("hidden_size", 16)),
151
+ heads=int(config.get("heads", 2)),
152
+ ),
153
+ "loss": torch.nn.Identity(),
154
+ }
155
+ )
156
+
157
+ def adapt_batch(self, batch: object, context: TorchBatchContext) -> TorchBatch:
158
+ return _batch(batch, context)
159
+
160
+ def training_step(
161
+ self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
162
+ ) -> TorchStepResult:
163
+ del context
164
+ import torch
165
+
166
+ predictions = cast(torch.nn.Module, modules["model"])(
167
+ batch.keyword["input_ids"]
168
+ )
169
+ targets = cast(torch.Tensor, batch.targets)
170
+ numerator = torch.nn.functional.binary_cross_entropy_with_logits(
171
+ predictions, targets, reduction="sum"
172
+ )
173
+ return TorchStepResult(
174
+ outputs={"output": predictions},
175
+ loss=TorchLossContribution(numerator, batch.local_rows),
176
+ metrics={"accuracy": _accuracy(predictions, targets)},
177
+ )
178
+
179
+ def validation_step(
180
+ self, modules: TorchModuleSet, batch: TorchBatch, context: TorchStepContext
181
+ ) -> TorchStepResult:
182
+ return self.training_step(modules, batch, context)
183
+
184
+ def configure_optimizers(
185
+ self, modules: TorchModuleSet, context: TorchBuildContext
186
+ ) -> TorchOptimizationPlan:
187
+ import torch
188
+
189
+ config = context.runtime.algorithm_config.get("optimizer", {})
190
+ if not isinstance(config, Mapping):
191
+ raise ValueError("Transformer optimizer config must be a mapping")
192
+ return TorchOptimizationPlan(
193
+ optimizer=torch.optim.AdamW(
194
+ cast(torch.nn.Module, modules["model"]).parameters(),
195
+ lr=float(config.get("learning_rate", 0.001)),
196
+ weight_decay=float(config.get("weight_decay", 0.0)),
197
+ ),
198
+ gradient_accumulation_steps=config.get("accumulation_steps", 1),
199
+ max_gradient_norm=config.get("max_gradient_norm", 1.0),
200
+ )
201
+
202
+ def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
203
+ del context
204
+ return TorchMetricPlan({"accuracy": "sum_count", "train_loss": "sum_count"})
205
+
206
+ def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
207
+ config = context.stage.runtime.algorithm_config.get("model", {})
208
+ sequence_length = (
209
+ int(config.get("sequence_length", 8)) if isinstance(config, Mapping) else 8
210
+ )
211
+ return TorchArtifactPlan(
212
+ source_kind="torch_module",
213
+ input_signature=(
214
+ {
215
+ "name": "input_ids",
216
+ "dtype": "int64",
217
+ "shape": ("batch", sequence_length),
218
+ },
219
+ ),
220
+ output_signature=(
221
+ {"name": "output", "dtype": "float32", "shape": ("batch", 1)},
222
+ ),
223
+ targets=(
224
+ {
225
+ "name": "onnx-model",
226
+ "format": "onnx",
227
+ "exporter_id": "torch-onnx-v1",
228
+ "options": {"dynamo": False},
229
+ },
230
+ ),
231
+ roles={"inference": "onnx-model"},
232
+ )
233
+
234
+
235
+ __all__ = ["TokenTransformerRecipe"]