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