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.
- tributo_algorithms-0.1.0.dist-info/METADATA +328 -0
- tributo_algorithms-0.1.0.dist-info/RECORD +110 -0
- tributo_algorithms-0.1.0.dist-info/WHEEL +4 -0
- tributo_algorithms-0.1.0.dist-info/entry_points.txt +57 -0
- tributo_algorithms-0.1.0.dist-info/licenses/LICENSE +202 -0
- tributo_algorithms_boosting/__init__.py +42 -0
- tributo_algorithms_boosting/algorithm.py +825 -0
- tributo_algorithms_boosting/checkpointing.py +441 -0
- tributo_algorithms_boosting/contracts.py +232 -0
- tributo_algorithms_boosting/data_config.py +59 -0
- tributo_algorithms_boosting/descriptor.py +124 -0
- tributo_algorithms_boosting/lightgbm.py +511 -0
- tributo_algorithms_boosting/lightgbm_contracts.py +186 -0
- tributo_algorithms_boosting/lightgbm_descriptor.py +112 -0
- tributo_algorithms_boosting/native.py +557 -0
- tributo_algorithms_boosting/stages.py +150 -0
- tributo_algorithms_catboost/__init__.py +5 -0
- tributo_algorithms_catboost/algorithm.py +379 -0
- tributo_algorithms_catboost/contracts.py +145 -0
- tributo_algorithms_catboost/descriptor.py +121 -0
- tributo_algorithms_catboost/exporter.py +106 -0
- tributo_algorithms_catboost/flavor.py +191 -0
- tributo_algorithms_causal_core/__init__.py +41 -0
- tributo_algorithms_causal_core/algorithm.py +1193 -0
- tributo_algorithms_causal_core/contracts.py +136 -0
- tributo_algorithms_causal_core/descriptor.py +270 -0
- tributo_algorithms_causal_core/exporter.py +52 -0
- tributo_algorithms_causal_discovery/__init__.py +23 -0
- tributo_algorithms_causal_discovery/algorithm.py +526 -0
- tributo_algorithms_causal_discovery/contracts.py +97 -0
- tributo_algorithms_causal_discovery/descriptor.py +130 -0
- tributo_algorithms_causal_discovery/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/__init__.py +38 -0
- tributo_algorithms_causal_dowhy/algorithm.py +325 -0
- tributo_algorithms_causal_dowhy/contracts.py +209 -0
- tributo_algorithms_causal_dowhy/descriptor.py +106 -0
- tributo_algorithms_causal_dowhy/exporter.py +43 -0
- tributo_algorithms_causal_dowhy/gcm.py +634 -0
- tributo_algorithms_causal_dowhy/gcm_descriptor.py +110 -0
- tributo_algorithms_causal_dr/__init__.py +22 -0
- tributo_algorithms_causal_dr/algorithm.py +446 -0
- tributo_algorithms_causal_dr/contracts.py +94 -0
- tributo_algorithms_causal_dr/descriptor.py +104 -0
- tributo_algorithms_causal_xlearner/__init__.py +29 -0
- tributo_algorithms_causal_xlearner/algorithm.py +448 -0
- tributo_algorithms_causal_xlearner/contracts.py +97 -0
- tributo_algorithms_causal_xlearner/descriptor.py +120 -0
- tributo_algorithms_causal_xlearner/exporter.py +432 -0
- tributo_algorithms_causal_xlearner/flavor.py +120 -0
- tributo_algorithms_causal_xlearner/model.py +116 -0
- tributo_algorithms_classical/__init__.py +41 -0
- tributo_algorithms_classical/contracts.py +139 -0
- tributo_algorithms_classical/descriptors.py +370 -0
- tributo_algorithms_classical/exporter.py +166 -0
- tributo_algorithms_classical/isolation_forest.py +172 -0
- tributo_algorithms_classical/isolation_forest_descriptor.py +122 -0
- tributo_algorithms_classical/kmeans.py +315 -0
- tributo_algorithms_classical/kmeans_descriptor.py +147 -0
- tributo_algorithms_classical/linear_regression.py +206 -0
- tributo_algorithms_classical/logistic_regression.py +238 -0
- tributo_algorithms_classical/models.py +28 -0
- tributo_algorithms_classical/multinomial_nb.py +643 -0
- tributo_algorithms_classical/multinomial_nb_descriptor.py +183 -0
- tributo_algorithms_classical/pca.py +187 -0
- tributo_algorithms_classical/pca_descriptor.py +111 -0
- tributo_algorithms_classical/random_forest.py +304 -0
- tributo_algorithms_classical/sgd.py +331 -0
- tributo_algorithms_classical/sgd_contracts.py +121 -0
- tributo_algorithms_classical/sgd_descriptor.py +143 -0
- tributo_algorithms_classical/unsupervised_contracts.py +198 -0
- tributo_algorithms_classical/unsupervised_exporter.py +427 -0
- tributo_algorithms_classical/unsupervised_models.py +90 -0
- tributo_algorithms_graph_pyg/__init__.py +37 -0
- tributo_algorithms_graph_pyg/algorithm.py +883 -0
- tributo_algorithms_graph_pyg/contracts.py +260 -0
- tributo_algorithms_graph_pyg/descriptor.py +201 -0
- tributo_algorithms_multistage_torch/__init__.py +40 -0
- tributo_algorithms_multistage_torch/algorithm.py +532 -0
- tributo_algorithms_multistage_torch/contracts.py +220 -0
- tributo_algorithms_multistage_torch/descriptor.py +146 -0
- tributo_algorithms_multistage_torch/pretrain.py +570 -0
- tributo_algorithms_multistage_torch/pretrain_descriptor.py +153 -0
- tributo_algorithms_recsys_torch/__init__.py +35 -0
- tributo_algorithms_recsys_torch/contracts.py +295 -0
- tributo_algorithms_recsys_torch/descriptor.py +136 -0
- tributo_algorithms_recsys_torch/jagged.py +707 -0
- tributo_algorithms_recsys_torch/jagged_descriptor.py +130 -0
- tributo_algorithms_recsys_torch/recipe.py +192 -0
- tributo_algorithms_representation/__init__.py +20 -0
- tributo_algorithms_representation/contracts.py +117 -0
- tributo_algorithms_representation/descriptor.py +137 -0
- tributo_algorithms_representation/recipe.py +162 -0
- tributo_algorithms_tabular_torch/__init__.py +46 -0
- tributo_algorithms_tabular_torch/contracts.py +228 -0
- tributo_algorithms_tabular_torch/descriptor.py +223 -0
- tributo_algorithms_tabular_torch/priors.py +216 -0
- tributo_algorithms_tabular_torch/pu_metrics.py +269 -0
- tributo_algorithms_tabular_torch/pu_reducer.py +129 -0
- tributo_algorithms_tabular_torch/recipe.py +294 -0
- tributo_algorithms_timeseries/__init__.py +36 -0
- tributo_algorithms_timeseries/contracts.py +120 -0
- tributo_algorithms_timeseries/descriptor.py +137 -0
- tributo_algorithms_timeseries/recipe.py +195 -0
- tributo_algorithms_timeseries/rnn_contracts.py +170 -0
- tributo_algorithms_timeseries/rnn_descriptor.py +167 -0
- tributo_algorithms_timeseries/rnn_recipe.py +223 -0
- tributo_algorithms_transformers_nlp/__init__.py +20 -0
- tributo_algorithms_transformers_nlp/contracts.py +109 -0
- tributo_algorithms_transformers_nlp/descriptor.py +137 -0
- tributo_algorithms_transformers_nlp/recipe.py +235 -0
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
"""RayTorchAdapter for pretrain-then-finetune classification."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import tempfile
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, cast
|
|
13
|
+
|
|
14
|
+
from tributo.algorithms.api import (
|
|
15
|
+
AlgorithmConfigurationError,
|
|
16
|
+
AlgorithmExecutionError,
|
|
17
|
+
TorchAccumulationWindow,
|
|
18
|
+
TorchBackwardContext,
|
|
19
|
+
TorchCheckpointPayloadDraft,
|
|
20
|
+
TorchCheckpointRef,
|
|
21
|
+
TorchLossContribution,
|
|
22
|
+
TorchMetricContribution,
|
|
23
|
+
TorchMetricPolicy,
|
|
24
|
+
TorchMetricReductionContext,
|
|
25
|
+
apply_torch_loss_backward,
|
|
26
|
+
reduce_torch_metrics,
|
|
27
|
+
report_torch_checkpoint,
|
|
28
|
+
)
|
|
29
|
+
from tributo.algorithms.spi import (
|
|
30
|
+
RayTorchAdapter,
|
|
31
|
+
TorchArtifactContext,
|
|
32
|
+
TorchArtifactPlan,
|
|
33
|
+
TorchCheckpointContext,
|
|
34
|
+
TorchMetricPlan,
|
|
35
|
+
TorchRuntimeContext,
|
|
36
|
+
TorchStageContext,
|
|
37
|
+
TorchWorkerCheckpointContext,
|
|
38
|
+
)
|
|
39
|
+
from tributo.util.annotations import PublicAPI
|
|
40
|
+
|
|
41
|
+
STAGES = ("pretrain", "finetune")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _gradient_clip_norm(training: Mapping[str, Any]) -> float:
|
|
45
|
+
value = training.get("max_gradient_norm", 1.0)
|
|
46
|
+
if (
|
|
47
|
+
not isinstance(value, (int, float))
|
|
48
|
+
or isinstance(value, bool)
|
|
49
|
+
or not math.isfinite(float(value))
|
|
50
|
+
or float(value) <= 0
|
|
51
|
+
):
|
|
52
|
+
raise AlgorithmConfigurationError(
|
|
53
|
+
"training.max_gradient_norm must be positive and finite"
|
|
54
|
+
)
|
|
55
|
+
return float(value)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _encoder(input_features: int, hidden_features: int) -> Any:
|
|
59
|
+
import torch
|
|
60
|
+
|
|
61
|
+
if input_features < 1 or hidden_features < 1:
|
|
62
|
+
raise ValueError("pretrain model dimensions must be positive")
|
|
63
|
+
return torch.nn.Sequential(
|
|
64
|
+
torch.nn.Linear(input_features, hidden_features), torch.nn.ReLU()
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _pretrain_model(input_features: int, hidden_features: int) -> object:
|
|
69
|
+
import torch
|
|
70
|
+
|
|
71
|
+
class PretrainModel(torch.nn.Module):
|
|
72
|
+
def __init__(self) -> None:
|
|
73
|
+
super().__init__()
|
|
74
|
+
self.encoder = _encoder(input_features, hidden_features)
|
|
75
|
+
self.decoder = torch.nn.Linear(hidden_features, input_features)
|
|
76
|
+
|
|
77
|
+
def forward(self, features: object) -> object:
|
|
78
|
+
return self.decoder(self.encoder(cast(torch.Tensor, features)))
|
|
79
|
+
|
|
80
|
+
return PretrainModel()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _finetune_model(input_features: int, hidden_features: int) -> object:
|
|
84
|
+
import torch
|
|
85
|
+
|
|
86
|
+
class FinetuneModel(torch.nn.Module):
|
|
87
|
+
def __init__(self) -> None:
|
|
88
|
+
super().__init__()
|
|
89
|
+
self.encoder = _encoder(input_features, hidden_features)
|
|
90
|
+
self.classifier = torch.nn.Linear(hidden_features, 1)
|
|
91
|
+
|
|
92
|
+
def forward(self, features: object) -> object:
|
|
93
|
+
return self.classifier(self.encoder(cast(torch.Tensor, features)))
|
|
94
|
+
|
|
95
|
+
return FinetuneModel()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _state_digest(state: Mapping[str, object]) -> str:
|
|
99
|
+
digest = hashlib.sha256()
|
|
100
|
+
for name in sorted(state):
|
|
101
|
+
tensor = cast(Any, state[name]).detach().cpu().contiguous()
|
|
102
|
+
digest.update(name.encode())
|
|
103
|
+
digest.update(str(tensor.dtype).encode())
|
|
104
|
+
digest.update(str(tuple(tensor.shape)).encode())
|
|
105
|
+
digest.update(tensor.numpy().tobytes())
|
|
106
|
+
return digest.hexdigest()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _load_encoder_checkpoint(
|
|
110
|
+
checkpoint_context: TorchWorkerCheckpointContext, model: object
|
|
111
|
+
) -> None:
|
|
112
|
+
if checkpoint_context.checkpoint is None:
|
|
113
|
+
raise AlgorithmExecutionError("finetune stage requires pretrain Checkpoint")
|
|
114
|
+
import torch
|
|
115
|
+
|
|
116
|
+
opener = getattr(checkpoint_context.checkpoint.checkpoint, "as_directory", None)
|
|
117
|
+
if not callable(opener):
|
|
118
|
+
raise AlgorithmExecutionError("pretrain Checkpoint cannot be opened")
|
|
119
|
+
with opener() as directory:
|
|
120
|
+
path = Path(directory) / "encoder.pt"
|
|
121
|
+
if not path.is_file():
|
|
122
|
+
raise AlgorithmExecutionError("pretrain Checkpoint is missing encoder.pt")
|
|
123
|
+
target = cast(torch.nn.Module, getattr(model, "module", model))
|
|
124
|
+
cast(torch.nn.Module, target.encoder).load_state_dict(
|
|
125
|
+
torch.load(path, map_location="cpu", weights_only=True)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _stage_train_loop(
|
|
130
|
+
config: Mapping[str, Any], checkpoint_context: TorchWorkerCheckpointContext
|
|
131
|
+
) -> None:
|
|
132
|
+
import ray
|
|
133
|
+
import torch
|
|
134
|
+
import torch.distributed as dist
|
|
135
|
+
from ray import train
|
|
136
|
+
from ray.train.torch import get_device, prepare_model
|
|
137
|
+
|
|
138
|
+
stage = str(config.get("stage", "pretrain"))
|
|
139
|
+
if stage not in STAGES:
|
|
140
|
+
raise AlgorithmConfigurationError("pretrain-finetune stage is invalid")
|
|
141
|
+
feature_names = tuple(str(name) for name in config.get("feature_names", ()))
|
|
142
|
+
label_name = str(config.get("label_name", "label"))
|
|
143
|
+
if not feature_names:
|
|
144
|
+
raise AlgorithmConfigurationError(
|
|
145
|
+
"pretrain-finetune feature_names are required"
|
|
146
|
+
)
|
|
147
|
+
shard = train.get_dataset_shard("train")
|
|
148
|
+
raw_batches = list(
|
|
149
|
+
shard.iter_torch_batches(
|
|
150
|
+
batch_size=int(config.get("batch_size", 32)), drop_last=False
|
|
151
|
+
)
|
|
152
|
+
)
|
|
153
|
+
if not raw_batches:
|
|
154
|
+
raise AlgorithmExecutionError(f"{stage} shard is empty")
|
|
155
|
+
first_batch = raw_batches[0]
|
|
156
|
+
if not isinstance(first_batch, Mapping):
|
|
157
|
+
raise AlgorithmExecutionError("pretrain-finetune batch is not columnar")
|
|
158
|
+
if not feature_names:
|
|
159
|
+
feature_names = tuple(name for name in first_batch if name != label_name)
|
|
160
|
+
batches: list[tuple[object, object]] = []
|
|
161
|
+
for batch in raw_batches:
|
|
162
|
+
if not isinstance(batch, Mapping):
|
|
163
|
+
raise AlgorithmExecutionError("pretrain-finetune batch is not columnar")
|
|
164
|
+
features = torch.stack([batch[name].float() for name in feature_names], dim=1)
|
|
165
|
+
labels = batch[label_name].float().reshape(-1, 1)
|
|
166
|
+
if (
|
|
167
|
+
not torch.isfinite(features).all()
|
|
168
|
+
or not torch.isfinite(labels).all()
|
|
169
|
+
or not bool(((labels == 0) | (labels == 1)).all())
|
|
170
|
+
):
|
|
171
|
+
raise AlgorithmExecutionError(
|
|
172
|
+
"pretrain-finetune batch contains invalid values"
|
|
173
|
+
)
|
|
174
|
+
batches.append((features, labels))
|
|
175
|
+
if not batches:
|
|
176
|
+
raise AlgorithmExecutionError(f"{stage} shard is empty")
|
|
177
|
+
model_config = config.get("model", {})
|
|
178
|
+
training = config.get("training", {})
|
|
179
|
+
if not isinstance(model_config, Mapping) or not isinstance(training, Mapping):
|
|
180
|
+
raise AlgorithmConfigurationError(
|
|
181
|
+
"pretrain-finetune model/training config is invalid"
|
|
182
|
+
)
|
|
183
|
+
input_features = int(model_config["input_features"])
|
|
184
|
+
hidden_features = int(model_config["hidden_features"])
|
|
185
|
+
if len(feature_names) != input_features:
|
|
186
|
+
raise AlgorithmConfigurationError(
|
|
187
|
+
"pretrain-finetune feature binding does not match model.input_features"
|
|
188
|
+
)
|
|
189
|
+
device: Any = get_device()
|
|
190
|
+
if stage == "pretrain":
|
|
191
|
+
model = cast(torch.nn.Module, _pretrain_model(input_features, hidden_features))
|
|
192
|
+
else:
|
|
193
|
+
model = cast(torch.nn.Module, _finetune_model(input_features, hidden_features))
|
|
194
|
+
model = prepare_model(model)
|
|
195
|
+
optimizer = torch.optim.Adam(
|
|
196
|
+
model.parameters(), lr=float(training.get("learning_rate", 0.01))
|
|
197
|
+
)
|
|
198
|
+
max_gradient_norm = _gradient_clip_norm(training)
|
|
199
|
+
epochs = int(
|
|
200
|
+
training.get("pretrain_epochs" if stage == "pretrain" else "finetune_epochs", 1)
|
|
201
|
+
)
|
|
202
|
+
rank, world_size = (
|
|
203
|
+
train.get_context().get_world_rank(),
|
|
204
|
+
train.get_context().get_world_size(),
|
|
205
|
+
)
|
|
206
|
+
if checkpoint_context.checkpoint is not None:
|
|
207
|
+
if checkpoint_context.source == "stage_dependency":
|
|
208
|
+
if stage != "finetune":
|
|
209
|
+
raise AlgorithmExecutionError(
|
|
210
|
+
"pretrain stage cannot consume a Stage dependency Checkpoint"
|
|
211
|
+
)
|
|
212
|
+
_load_encoder_checkpoint(checkpoint_context, model)
|
|
213
|
+
else:
|
|
214
|
+
raise AlgorithmExecutionError(
|
|
215
|
+
f"pretrain-finetune checkpoint source {checkpoint_context.source!r} is invalid"
|
|
216
|
+
)
|
|
217
|
+
elif stage == "finetune":
|
|
218
|
+
raise AlgorithmExecutionError("finetune stage requires pretrain Checkpoint")
|
|
219
|
+
last_numerator = 0.0
|
|
220
|
+
last_rows = 0
|
|
221
|
+
for epoch in range(epochs):
|
|
222
|
+
optimizer.zero_grad(set_to_none=True)
|
|
223
|
+
numerator_total: torch.Tensor | None = None
|
|
224
|
+
rows = 0
|
|
225
|
+
for raw_features, raw_labels in batches:
|
|
226
|
+
features = cast(torch.Tensor, cast(Any, raw_features).to(device))
|
|
227
|
+
labels = cast(torch.Tensor, cast(Any, raw_labels).to(device))
|
|
228
|
+
output = cast(torch.Tensor, model(features))
|
|
229
|
+
numerator: torch.Tensor
|
|
230
|
+
if stage == "pretrain":
|
|
231
|
+
squared = (output - features) ** 2
|
|
232
|
+
numerator = cast(torch.Tensor, squared.sum())
|
|
233
|
+
normalizer = int(squared.numel())
|
|
234
|
+
else:
|
|
235
|
+
numerator = cast(
|
|
236
|
+
torch.Tensor,
|
|
237
|
+
torch.nn.functional.binary_cross_entropy_with_logits(
|
|
238
|
+
output, labels, reduction="sum"
|
|
239
|
+
),
|
|
240
|
+
)
|
|
241
|
+
normalizer = int(labels.shape[0])
|
|
242
|
+
numerator_total = (
|
|
243
|
+
numerator if numerator_total is None else numerator_total + numerator
|
|
244
|
+
)
|
|
245
|
+
rows += normalizer
|
|
246
|
+
if numerator_total is None:
|
|
247
|
+
raise AlgorithmExecutionError("pretrain-finetune produced no loss")
|
|
248
|
+
|
|
249
|
+
def reduce_normalizer(value: float) -> float:
|
|
250
|
+
tensor = torch.tensor(value, dtype=torch.float64, device=device)
|
|
251
|
+
if dist.is_initialized():
|
|
252
|
+
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
|
|
253
|
+
return float(tensor.item())
|
|
254
|
+
|
|
255
|
+
def finalize(scale: float) -> None:
|
|
256
|
+
for parameter in model.parameters():
|
|
257
|
+
if parameter.grad is not None:
|
|
258
|
+
parameter.grad.mul_(scale)
|
|
259
|
+
torch.nn.utils.clip_grad_norm_(model.parameters(), max_gradient_norm)
|
|
260
|
+
optimizer.step()
|
|
261
|
+
optimizer.zero_grad(set_to_none=True)
|
|
262
|
+
|
|
263
|
+
apply_torch_loss_backward(
|
|
264
|
+
TorchLossContribution(numerator_total, rows),
|
|
265
|
+
TorchAccumulationWindow(epoch, 1),
|
|
266
|
+
TorchBackwardContext(
|
|
267
|
+
world_size=world_size,
|
|
268
|
+
backward=lambda value: value.backward(),
|
|
269
|
+
reduce_normalizer=reduce_normalizer,
|
|
270
|
+
finalize_window=finalize,
|
|
271
|
+
),
|
|
272
|
+
)
|
|
273
|
+
last_numerator, last_rows = float(numerator_total.detach().item()), rows
|
|
274
|
+
|
|
275
|
+
def reduce_metric(
|
|
276
|
+
name: str, contribution: TorchMetricContribution, reducer: str
|
|
277
|
+
) -> float:
|
|
278
|
+
del name, reducer
|
|
279
|
+
state = torch.tensor(
|
|
280
|
+
[contribution.numerator, contribution.normalizer],
|
|
281
|
+
dtype=torch.float64,
|
|
282
|
+
device=device,
|
|
283
|
+
)
|
|
284
|
+
if dist.is_initialized():
|
|
285
|
+
dist.all_reduce(state, op=dist.ReduceOp.SUM)
|
|
286
|
+
return float(state[0].item() / state[1].item()) if state[1].item() > 0 else 0.0
|
|
287
|
+
|
|
288
|
+
reduced_loss = reduce_torch_metrics(
|
|
289
|
+
{"train_loss": TorchMetricContribution(last_numerator, last_rows)},
|
|
290
|
+
TorchMetricPolicy({"train_loss": "sum_count"}),
|
|
291
|
+
TorchMetricReductionContext(reduce_metric),
|
|
292
|
+
).values["train_loss"]
|
|
293
|
+
unwrapped = cast(
|
|
294
|
+
torch.nn.Module, model.module if hasattr(model, "module") else model
|
|
295
|
+
)
|
|
296
|
+
digest = _state_digest(cast(Mapping[str, object], unwrapped.state_dict()))
|
|
297
|
+
train_rows = sum(
|
|
298
|
+
int(cast(torch.Tensor, features).shape[0]) for features, _ in batches
|
|
299
|
+
)
|
|
300
|
+
worker = {
|
|
301
|
+
"worker_id": f"pretrain-{stage}-{rank}",
|
|
302
|
+
"node_id": str(ray.get_runtime_context().get_node_id()),
|
|
303
|
+
"rank": rank,
|
|
304
|
+
"world_size": world_size,
|
|
305
|
+
"shard_id": f"{stage}-{rank}",
|
|
306
|
+
"rows_processed": train_rows,
|
|
307
|
+
"input_rows": {"train": train_rows},
|
|
308
|
+
"batch_count": epochs,
|
|
309
|
+
"collective_steps": epochs,
|
|
310
|
+
"model_state_digest": digest,
|
|
311
|
+
"stage": stage,
|
|
312
|
+
}
|
|
313
|
+
workers: list[object] = [None] * world_size
|
|
314
|
+
if dist.is_initialized():
|
|
315
|
+
dist.all_gather_object(workers, worker)
|
|
316
|
+
else:
|
|
317
|
+
workers[0] = worker
|
|
318
|
+
with tempfile.TemporaryDirectory(prefix=f"tributo-pretrain-{stage}-") as directory:
|
|
319
|
+
root = Path(directory)
|
|
320
|
+
if stage == "pretrain":
|
|
321
|
+
torch.save(cast(Any, unwrapped).encoder.state_dict(), root / "encoder.pt")
|
|
322
|
+
torch.save(unwrapped.state_dict(), root / "model.pt")
|
|
323
|
+
(root / "model_config.json").write_text(
|
|
324
|
+
json.dumps(
|
|
325
|
+
{
|
|
326
|
+
"input_features": input_features,
|
|
327
|
+
"hidden_features": hidden_features,
|
|
328
|
+
"feature_names": list(feature_names),
|
|
329
|
+
"stage": stage,
|
|
330
|
+
},
|
|
331
|
+
sort_keys=True,
|
|
332
|
+
),
|
|
333
|
+
encoding="utf-8",
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
metric_name = "pretrain_loss" if stage == "pretrain" else "finetune_loss"
|
|
337
|
+
report_torch_checkpoint(
|
|
338
|
+
{
|
|
339
|
+
"train_loss": reduced_loss,
|
|
340
|
+
metric_name: reduced_loss,
|
|
341
|
+
"execution_workers": workers,
|
|
342
|
+
"model_state_digest": digest,
|
|
343
|
+
},
|
|
344
|
+
TorchCheckpointPayloadDraft(root),
|
|
345
|
+
checkpoint_context.stage,
|
|
346
|
+
epochs,
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
@PublicAPI(stability="alpha")
|
|
351
|
+
class DistributedPretrainFinetune(RayTorchAdapter):
|
|
352
|
+
"""Execute pretraining then finetuning through Core's component plan."""
|
|
353
|
+
|
|
354
|
+
def validate_environment(self, context: TorchRuntimeContext) -> None:
|
|
355
|
+
del context
|
|
356
|
+
try:
|
|
357
|
+
import torch
|
|
358
|
+
except ImportError as exc:
|
|
359
|
+
raise AlgorithmConfigurationError(
|
|
360
|
+
"pretrain-finetune requires PyTorch"
|
|
361
|
+
) from exc
|
|
362
|
+
if not torch.__version__:
|
|
363
|
+
raise AlgorithmConfigurationError(
|
|
364
|
+
"pretrain-finetune environment is invalid"
|
|
365
|
+
)
|
|
366
|
+
|
|
367
|
+
def bind_datasets(
|
|
368
|
+
self, datasets: Mapping[str, object], context: TorchStageContext
|
|
369
|
+
) -> Mapping[str, object]:
|
|
370
|
+
del context
|
|
371
|
+
if set(datasets) != {"train"}:
|
|
372
|
+
raise AlgorithmConfigurationError(
|
|
373
|
+
"pretrain-finetune requires train Dataset"
|
|
374
|
+
)
|
|
375
|
+
return dict(datasets)
|
|
376
|
+
|
|
377
|
+
def worker_config(self, context: TorchStageContext) -> Mapping[str, object]:
|
|
378
|
+
config = {
|
|
379
|
+
key: value
|
|
380
|
+
for key, value in context.runtime.algorithm_config.items()
|
|
381
|
+
if key not in {"ray", "output"}
|
|
382
|
+
}
|
|
383
|
+
config["stage"] = context.stage_id
|
|
384
|
+
binding = context.runtime.input_bindings.get("train")
|
|
385
|
+
if not isinstance(binding, Mapping):
|
|
386
|
+
raise AlgorithmConfigurationError(
|
|
387
|
+
"pretrain-finetune Stage context is missing the train binding"
|
|
388
|
+
)
|
|
389
|
+
feature_names = binding.get("feature_names")
|
|
390
|
+
label_name = binding.get("label_name")
|
|
391
|
+
if (
|
|
392
|
+
not isinstance(feature_names, (list, tuple))
|
|
393
|
+
or not feature_names
|
|
394
|
+
or not all(isinstance(name, str) and name for name in feature_names)
|
|
395
|
+
or not isinstance(label_name, str)
|
|
396
|
+
or not label_name
|
|
397
|
+
):
|
|
398
|
+
raise AlgorithmConfigurationError(
|
|
399
|
+
"pretrain-finetune train binding has an invalid typed layout"
|
|
400
|
+
)
|
|
401
|
+
config["feature_names"] = tuple(feature_names)
|
|
402
|
+
config["label_name"] = label_name
|
|
403
|
+
return config
|
|
404
|
+
|
|
405
|
+
def train_loop_per_worker(
|
|
406
|
+
self,
|
|
407
|
+
worker_config: Mapping[str, object],
|
|
408
|
+
checkpoint_context: TorchWorkerCheckpointContext,
|
|
409
|
+
) -> None:
|
|
410
|
+
_stage_train_loop(worker_config, checkpoint_context)
|
|
411
|
+
|
|
412
|
+
def checkpoint_source(
|
|
413
|
+
self, result: object, context: TorchCheckpointContext
|
|
414
|
+
) -> object:
|
|
415
|
+
del context
|
|
416
|
+
checkpoint = getattr(result, "checkpoint", None)
|
|
417
|
+
if checkpoint is None:
|
|
418
|
+
raise AlgorithmExecutionError("pretrain-finetune result has no checkpoint")
|
|
419
|
+
return checkpoint
|
|
420
|
+
|
|
421
|
+
def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
|
|
422
|
+
del context
|
|
423
|
+
return TorchMetricPlan(
|
|
424
|
+
{
|
|
425
|
+
"train_loss": "sum_count",
|
|
426
|
+
"pretrain_loss": "sum_count",
|
|
427
|
+
"finetune_loss": "sum_count",
|
|
428
|
+
}
|
|
429
|
+
)
|
|
430
|
+
|
|
431
|
+
def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
|
|
432
|
+
config = context.stage.runtime.algorithm_config.get("model", {})
|
|
433
|
+
features = (
|
|
434
|
+
int(config.get("input_features", 1)) if isinstance(config, Mapping) else 1
|
|
435
|
+
)
|
|
436
|
+
return TorchArtifactPlan(
|
|
437
|
+
source_kind="torch_module",
|
|
438
|
+
input_signature=(
|
|
439
|
+
{
|
|
440
|
+
"name": "float_input",
|
|
441
|
+
"dtype": "float32",
|
|
442
|
+
"shape": ("batch", features),
|
|
443
|
+
},
|
|
444
|
+
),
|
|
445
|
+
output_signature=(
|
|
446
|
+
{"name": "output", "dtype": "float32", "shape": ("batch", 1)},
|
|
447
|
+
),
|
|
448
|
+
targets=(
|
|
449
|
+
{
|
|
450
|
+
"name": "finetuned-model",
|
|
451
|
+
"format": "safetensors",
|
|
452
|
+
"exporter_id": "torch-safetensors-v1",
|
|
453
|
+
},
|
|
454
|
+
{
|
|
455
|
+
"name": "finetuned-inference",
|
|
456
|
+
"format": "onnx",
|
|
457
|
+
"exporter_id": "torch-onnx-v1",
|
|
458
|
+
"options": {"dynamo": False},
|
|
459
|
+
},
|
|
460
|
+
),
|
|
461
|
+
roles={"model": "finetuned-model", "inference": "finetuned-inference"},
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
@contextmanager
|
|
465
|
+
def open_export_source(
|
|
466
|
+
self, checkpoint_ref: TorchCheckpointRef, artifact_context: TorchArtifactContext
|
|
467
|
+
) -> Any:
|
|
468
|
+
import torch
|
|
469
|
+
from tributo.exporting.models import (
|
|
470
|
+
CheckpointField,
|
|
471
|
+
ExportCheckpointV1,
|
|
472
|
+
ExportSource,
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
opener = getattr(checkpoint_ref.checkpoint, "as_directory", None)
|
|
476
|
+
if not callable(opener):
|
|
477
|
+
raise AlgorithmExecutionError(
|
|
478
|
+
"pretrain-finetune checkpoint cannot be opened"
|
|
479
|
+
)
|
|
480
|
+
with opener() as directory:
|
|
481
|
+
root = Path(directory)
|
|
482
|
+
required_payloads = ("model_config.json", "model.pt")
|
|
483
|
+
missing_payloads = [
|
|
484
|
+
name
|
|
485
|
+
for name in required_payloads
|
|
486
|
+
if not (root / name).is_file() or (root / name).is_symlink()
|
|
487
|
+
]
|
|
488
|
+
if missing_payloads:
|
|
489
|
+
raise AlgorithmExecutionError(
|
|
490
|
+
"pretrain-finetune checkpoint is missing payloads: "
|
|
491
|
+
f"{missing_payloads}"
|
|
492
|
+
)
|
|
493
|
+
config = json.loads(
|
|
494
|
+
(root / "model_config.json").read_text(encoding="utf-8")
|
|
495
|
+
)
|
|
496
|
+
model = cast(
|
|
497
|
+
torch.nn.Module,
|
|
498
|
+
_finetune_model(
|
|
499
|
+
int(config["input_features"]), int(config["hidden_features"])
|
|
500
|
+
),
|
|
501
|
+
)
|
|
502
|
+
try:
|
|
503
|
+
model.load_state_dict(
|
|
504
|
+
torch.load(root / "model.pt", map_location="cpu", weights_only=True)
|
|
505
|
+
)
|
|
506
|
+
except (RuntimeError, TypeError, ValueError) as exc:
|
|
507
|
+
raise AlgorithmExecutionError(
|
|
508
|
+
"pretrain-finetune model payload is incompatible"
|
|
509
|
+
) from exc
|
|
510
|
+
model.eval()
|
|
511
|
+
yield ExportSource(
|
|
512
|
+
source_kind="torch_module",
|
|
513
|
+
model_object=model,
|
|
514
|
+
architecture_id=artifact_context.stage.runtime.implementation_id,
|
|
515
|
+
model_config_data=config,
|
|
516
|
+
feature_schema={"input_names": ["float_input"]},
|
|
517
|
+
sample_inputs={
|
|
518
|
+
"float_input": torch.zeros(
|
|
519
|
+
(2, int(config["input_features"])), dtype=torch.float32
|
|
520
|
+
)
|
|
521
|
+
},
|
|
522
|
+
metadata={
|
|
523
|
+
"framework": "pytorch",
|
|
524
|
+
"task_type": "binary_classification",
|
|
525
|
+
"component_stages": list(STAGES),
|
|
526
|
+
"producer_distribution": "tributo-algorithms",
|
|
527
|
+
},
|
|
528
|
+
source_fingerprint=_state_digest(
|
|
529
|
+
cast(Mapping[str, object], model.state_dict())
|
|
530
|
+
),
|
|
531
|
+
checkpoint_contract=ExportCheckpointV1(
|
|
532
|
+
trainer_type="pretrain_finetune_classifier",
|
|
533
|
+
architecture_id=artifact_context.stage.runtime.implementation_id,
|
|
534
|
+
input_schema=(
|
|
535
|
+
CheckpointField(
|
|
536
|
+
name="float_input",
|
|
537
|
+
dtype="float32",
|
|
538
|
+
shape=("batch", int(config["input_features"])),
|
|
539
|
+
),
|
|
540
|
+
),
|
|
541
|
+
output_schema=(
|
|
542
|
+
CheckpointField(
|
|
543
|
+
name="output", dtype="float32", shape=("batch", 1)
|
|
544
|
+
),
|
|
545
|
+
),
|
|
546
|
+
preprocessing={"type": "ordered_features"},
|
|
547
|
+
task_type="binary_classification",
|
|
548
|
+
framework="pytorch",
|
|
549
|
+
framework_version=torch.__version__,
|
|
550
|
+
),
|
|
551
|
+
)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def create_pretrain_finetune_algorithm(
|
|
555
|
+
*,
|
|
556
|
+
plan: object | None = None,
|
|
557
|
+
implementation: object | None = None,
|
|
558
|
+
artifacts: tuple[object, ...] = (),
|
|
559
|
+
) -> DistributedPretrainFinetune:
|
|
560
|
+
del plan, artifacts
|
|
561
|
+
if implementation is not DistributedPretrainFinetune:
|
|
562
|
+
raise AlgorithmConfigurationError("pretrain-finetune implementation drifted")
|
|
563
|
+
return DistributedPretrainFinetune()
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
__all__ = [
|
|
567
|
+
"DistributedPretrainFinetune",
|
|
568
|
+
"STAGES",
|
|
569
|
+
"create_pretrain_finetune_algorithm",
|
|
570
|
+
]
|