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,883 @@
1
+ """RayTorchAdapter implementations for bounded PyG graph classifiers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import math
8
+ import operator
9
+ import tempfile
10
+ from collections.abc import Mapping
11
+ from contextlib import contextmanager
12
+ from pathlib import Path
13
+ from typing import Any, cast
14
+
15
+ from tributo.algorithms.api import (
16
+ AlgorithmConfigurationError,
17
+ AlgorithmExecutionError,
18
+ TorchAccumulationWindow,
19
+ TorchBackwardContext,
20
+ TorchCheckpointPayloadDraft,
21
+ TorchCheckpointRef,
22
+ TorchLossContribution,
23
+ TorchMetricContribution,
24
+ TorchMetricPolicy,
25
+ TorchMetricReductionContext,
26
+ apply_torch_loss_backward,
27
+ reduce_torch_metrics,
28
+ report_torch_checkpoint,
29
+ )
30
+ from tributo.algorithms.spi import (
31
+ RayTorchAdapter,
32
+ TorchArtifactContext,
33
+ TorchArtifactPlan,
34
+ TorchCheckpointContext,
35
+ TorchRuntimeContext,
36
+ TorchStageContext,
37
+ TorchWorkerCheckpointContext,
38
+ )
39
+ from tributo.util.annotations import PublicAPI
40
+
41
+
42
+ def _integer_values(values: object, field_name: str) -> list[int]:
43
+ import numpy as np
44
+
45
+ result: list[int] = []
46
+ for raw_value in cast(Any, values):
47
+ if isinstance(raw_value, (bool, np.bool_)):
48
+ raise AlgorithmExecutionError(f"{field_name} must contain integer values")
49
+ try:
50
+ result.append(operator.index(raw_value))
51
+ except TypeError as exc:
52
+ raise AlgorithmExecutionError(
53
+ f"{field_name} must contain integer values"
54
+ ) from exc
55
+ return result
56
+
57
+
58
+ def _gradient_clip_norm(training: Mapping[str, Any]) -> float:
59
+ value = training.get("max_gradient_norm", 1.0)
60
+ if (
61
+ not isinstance(value, (int, float))
62
+ or isinstance(value, bool)
63
+ or not math.isfinite(float(value))
64
+ or float(value) <= 0
65
+ ):
66
+ raise AlgorithmConfigurationError(
67
+ "training.max_gradient_norm must be positive and finite"
68
+ )
69
+ return float(value)
70
+
71
+
72
+ def _build_model(
73
+ input_features: int,
74
+ hidden_features: int,
75
+ num_classes: int,
76
+ *,
77
+ model_kind: str = "graphsage",
78
+ num_relations: int = 1,
79
+ ) -> object:
80
+ import torch
81
+
82
+ if min(input_features, hidden_features, num_classes, num_relations) < 1:
83
+ raise ValueError("graph model dimensions must be positive")
84
+ if model_kind == "rgcn":
85
+ from torch_geometric.nn import RGCNConv
86
+
87
+ class RGCN(torch.nn.Module):
88
+ def __init__(self) -> None:
89
+ super().__init__()
90
+ self.conv1 = RGCNConv(input_features, hidden_features, num_relations)
91
+ self.conv2 = RGCNConv(hidden_features, num_classes, num_relations)
92
+
93
+ def forward(
94
+ self, x: object, edge_index: object, edge_type: object
95
+ ) -> object:
96
+ values = self.conv1(x, edge_index, edge_type).relu()
97
+ return self.conv2(values, edge_index, edge_type)
98
+
99
+ return RGCN()
100
+ if model_kind != "graphsage":
101
+ raise ValueError(f"unsupported graph model kind: {model_kind}")
102
+ from torch_geometric.nn import SAGEConv
103
+
104
+ class GraphSAGE(torch.nn.Module):
105
+ def __init__(self) -> None:
106
+ super().__init__()
107
+ self.conv1 = SAGEConv(input_features, hidden_features)
108
+ self.conv2 = SAGEConv(hidden_features, num_classes)
109
+
110
+ def forward(self, x: object, edge_index: object) -> object:
111
+ values = self.conv1(x, edge_index).relu()
112
+ return self.conv2(values, edge_index)
113
+
114
+ return GraphSAGE()
115
+
116
+
117
+ def _node_lookup_model(model: object, logits: object) -> object:
118
+ import torch
119
+
120
+ trained = cast(torch.nn.Module, model)
121
+
122
+ class NodeLookupModel(torch.nn.Module):
123
+ def __init__(self) -> None:
124
+ super().__init__()
125
+ self.conv1 = cast(Any, trained).conv1
126
+ self.conv2 = cast(Any, trained).conv2
127
+ self.register_buffer(
128
+ "inference_logits",
129
+ cast(torch.Tensor, logits).detach().float(),
130
+ persistent=False,
131
+ )
132
+
133
+ def forward(self, node_id: object) -> object:
134
+ values = cast(torch.Tensor, node_id)
135
+ if (
136
+ values.dtype == torch.bool
137
+ or values.is_floating_point()
138
+ or values.is_complex()
139
+ ):
140
+ raise ValueError("graph node IDs must contain integer values")
141
+ values = values.to(dtype=torch.long)
142
+ stored = cast(torch.Tensor, self.inference_logits)
143
+ valid = values.ge(0).logical_and(values.lt(stored.shape[0]))
144
+ safe = values.clamp(min=0, max=stored.shape[0] - 1)
145
+ selected = stored[safe]
146
+ masked = torch.where(
147
+ valid.unsqueeze(-1), selected, torch.zeros_like(selected)
148
+ )
149
+ return torch.cat((masked, valid.unsqueeze(-1).float()), dim=1)
150
+
151
+ return NodeLookupModel()
152
+
153
+
154
+ def _columns(iterator: object, names: tuple[str, ...]) -> dict[str, list[object]]:
155
+ method = getattr(iterator, "iter_batches", None)
156
+ if not callable(method):
157
+ raise AlgorithmExecutionError("graph dataset shard is not iterable")
158
+ output: dict[str, list[object]] = {name: [] for name in names}
159
+ for batch in method(batch_format="numpy"):
160
+ if not isinstance(batch, Mapping):
161
+ raise AlgorithmExecutionError("graph dataset produced a non-columnar batch")
162
+ for name in names:
163
+ if name not in batch:
164
+ raise AlgorithmExecutionError(f"graph dataset is missing {name!r}")
165
+ value = batch[name]
166
+ values = value.tolist() if hasattr(value, "tolist") else value
167
+ if not isinstance(values, (list, tuple)):
168
+ raise AlgorithmExecutionError(
169
+ f"graph column {name!r} is not a sequence"
170
+ )
171
+ output[name].extend(values)
172
+ return output
173
+
174
+
175
+ def _dataset_column_names(dataset: object) -> tuple[str, ...]:
176
+ schema = getattr(dataset, "schema", None)
177
+ if callable(schema):
178
+ value = schema()
179
+ names = getattr(value, "names", None)
180
+ if isinstance(names, (list, tuple)) and all(
181
+ isinstance(name, str) for name in names
182
+ ):
183
+ return tuple(names)
184
+ return ()
185
+
186
+
187
+ def _state_digest(state: Mapping[str, object]) -> str:
188
+ digest = hashlib.sha256()
189
+ for name in sorted(state):
190
+ tensor = cast(Any, state[name]).detach().cpu().contiguous()
191
+ digest.update(name.encode())
192
+ digest.update(str(tensor.dtype).encode())
193
+ digest.update(str(tuple(tensor.shape)).encode())
194
+ digest.update(tensor.numpy().tobytes())
195
+ return digest.hexdigest()
196
+
197
+
198
+ def _tensor_digest(value: object) -> str:
199
+ tensor = cast(Any, value).detach().cpu().contiguous()
200
+ digest = hashlib.sha256()
201
+ digest.update(str(tensor.dtype).encode())
202
+ digest.update(str(tuple(tensor.shape)).encode())
203
+ digest.update(tensor.numpy().tobytes())
204
+ return digest.hexdigest()
205
+
206
+
207
+ def _require_sha256(value: object, *, name: str) -> str:
208
+ if not isinstance(value, str) or len(value) != 64 or value != value.lower():
209
+ raise AlgorithmExecutionError(f"graph checkpoint {name} is invalid")
210
+ try:
211
+ int(value, 16)
212
+ except ValueError as exc:
213
+ raise AlgorithmExecutionError(f"graph checkpoint {name} is invalid") from exc
214
+ return value
215
+
216
+
217
+ def _graph_identity_digest(
218
+ *,
219
+ topology_digest: str,
220
+ node_feature_digest: str,
221
+ node_feature_names: tuple[str, ...],
222
+ ) -> str:
223
+ payload = {
224
+ "schema_version": 1,
225
+ "topology_digest": topology_digest,
226
+ "node_feature_digest": node_feature_digest,
227
+ "node_feature_names": list(node_feature_names),
228
+ }
229
+ return hashlib.sha256(
230
+ json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
231
+ ).hexdigest()
232
+
233
+
234
+ def _graph_source_fingerprint(
235
+ *, model_digest: str, graph_identity_digest: str, inference_logits_digest: str
236
+ ) -> str:
237
+ payload = {
238
+ "schema_version": 1,
239
+ "model_digest": model_digest,
240
+ "graph_identity_digest": graph_identity_digest,
241
+ "inference_logits_digest": inference_logits_digest,
242
+ }
243
+ return hashlib.sha256(
244
+ json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
245
+ ).hexdigest()
246
+
247
+
248
+ def _graph_train_loop(
249
+ config: Mapping[str, Any], checkpoint_context: TorchWorkerCheckpointContext
250
+ ) -> None:
251
+ import ray
252
+ import torch
253
+ from ray import train
254
+ from ray.train.torch import get_device, prepare_model
255
+
256
+ columns = config.get("columns")
257
+ names = (
258
+ {str(key): value for key, value in columns.items()}
259
+ if isinstance(columns, Mapping)
260
+ else {}
261
+ )
262
+ nodes_dataset = train.get_dataset_shard("nodes")
263
+ edges_dataset = train.get_dataset_shard("edges")
264
+ train_dataset = train.get_dataset_shard("train")
265
+ if not names:
266
+ node_names = _dataset_column_names(nodes_dataset)
267
+ edge_names = _dataset_column_names(edges_dataset)
268
+ train_names = _dataset_column_names(train_dataset)
269
+ if len(node_names) < 2 or len(edge_names) < 2 or len(train_names) < 2:
270
+ raise AlgorithmConfigurationError(
271
+ "graph adapter columns cannot be inferred"
272
+ )
273
+ names = {
274
+ "node_id": node_names[0],
275
+ "node_features": list(node_names[1:]),
276
+ "edge_source": edge_names[0],
277
+ "edge_destination": edge_names[1],
278
+ "seed_node_id": train_names[0],
279
+ "seed_label": train_names[-1],
280
+ }
281
+ if len(edge_names) >= 3:
282
+ names["edge_relation"] = edge_names[2]
283
+ node_features = tuple(str(value) for value in names["node_features"])
284
+ nodes = _columns(nodes_dataset, (str(names["node_id"]), *node_features))
285
+ edge_columns: list[str] = [
286
+ str(names["edge_source"]),
287
+ str(names["edge_destination"]),
288
+ ]
289
+ if names.get("edge_relation") is not None:
290
+ edge_columns.append(str(names["edge_relation"]))
291
+ edges = _columns(edges_dataset, tuple(edge_columns))
292
+ seeds = _columns(
293
+ train_dataset,
294
+ (str(names["seed_node_id"]), str(names["seed_label"])),
295
+ )
296
+ raw_node_ids = _integer_values(nodes[str(names["node_id"])], "graph node IDs")
297
+ order = sorted(range(len(raw_node_ids)), key=raw_node_ids.__getitem__)
298
+ node_ids = [raw_node_ids[index] for index in order]
299
+ if node_ids != list(range(len(node_ids))):
300
+ raise AlgorithmExecutionError(
301
+ "graph node IDs must be contiguous and zero-based"
302
+ )
303
+ if not seeds[str(names["seed_node_id"])]:
304
+ raise AlgorithmExecutionError("every graph worker requires labeled seeds")
305
+ device = get_device()
306
+ x = torch.tensor(
307
+ [
308
+ [float(cast(Any, nodes[feature][index])) for feature in node_features]
309
+ for index in order
310
+ ],
311
+ dtype=torch.float32,
312
+ device=device,
313
+ )
314
+ source = _integer_values(edges[str(names["edge_source"])], "graph edge sources")
315
+ destination = _integer_values(
316
+ edges[str(names["edge_destination"])], "graph edge destinations"
317
+ )
318
+ relations = (
319
+ _integer_values(edges[str(names["edge_relation"])], "graph edge relation IDs")
320
+ if names.get("edge_relation") is not None
321
+ else []
322
+ )
323
+ if not source or len(source) != len(destination):
324
+ raise AlgorithmExecutionError("graph requires a non-empty edge list")
325
+ if len(relations) not in {0, len(source)}:
326
+ raise AlgorithmExecutionError("graph relation coverage is incomplete")
327
+ if relations:
328
+ edge_records = sorted(zip(source, destination, relations, strict=True))
329
+ source = [left for left, _, _ in edge_records]
330
+ destination = [right for _, right, _ in edge_records]
331
+ relations = [relation for _, _, relation in edge_records]
332
+ else:
333
+ edge_pairs = sorted(zip(source, destination, strict=True))
334
+ source = [left for left, _ in edge_pairs]
335
+ destination = [right for _, right in edge_pairs]
336
+ edge_index_values = (
337
+ [source, destination]
338
+ if relations
339
+ else [source + destination, destination + source]
340
+ )
341
+ edge_index = torch.tensor(edge_index_values, dtype=torch.long, device=device)
342
+ edge_type = (
343
+ torch.tensor(relations, dtype=torch.long, device=device) if relations else None
344
+ )
345
+ seed_index = torch.tensor(
346
+ _integer_values(seeds[str(names["seed_node_id"])], "graph seed node IDs"),
347
+ dtype=torch.long,
348
+ device=device,
349
+ )
350
+ labels = torch.tensor(
351
+ _integer_values(seeds[str(names["seed_label"])], "graph labels"),
352
+ dtype=torch.long,
353
+ device=device,
354
+ )
355
+ model_config = config.get("model", {})
356
+ training = config.get("training", {})
357
+ if not isinstance(model_config, Mapping) or not isinstance(training, Mapping):
358
+ raise AlgorithmConfigurationError("graph model/training config is invalid")
359
+ node_count = len(node_ids)
360
+ if any(
361
+ value < 0 or value >= node_count
362
+ for value in (*source, *destination, *seed_index.tolist())
363
+ ):
364
+ raise AlgorithmExecutionError("graph node IDs are out of range")
365
+ num_classes = int(model_config.get("num_classes", 2))
366
+ if any(value < 0 or value >= num_classes for value in labels.tolist()):
367
+ raise AlgorithmExecutionError("graph labels are out of range")
368
+ if relations:
369
+ num_relations = int(model_config.get("num_relations", 1))
370
+ if any(value < 0 or value >= num_relations for value in relations):
371
+ raise AlgorithmExecutionError("graph relation IDs are out of range")
372
+ model = prepare_model(
373
+ cast(
374
+ torch.nn.Module,
375
+ _build_model(
376
+ len(node_features),
377
+ int(model_config.get("hidden_features", 16)),
378
+ int(model_config.get("num_classes", 2)),
379
+ model_kind=str(config.get("model_kind", "graphsage")),
380
+ num_relations=int(model_config.get("num_relations", 1)),
381
+ ),
382
+ )
383
+ )
384
+ optimizer = torch.optim.Adam(
385
+ model.parameters(), lr=float(training.get("learning_rate", 0.01))
386
+ )
387
+ max_gradient_norm = _gradient_clip_norm(training)
388
+ context = train.get_context()
389
+ rank, world_size = context.get_world_rank(), context.get_world_size()
390
+ if checkpoint_context.source != "none" or checkpoint_context.checkpoint is not None:
391
+ raise AlgorithmExecutionError("graph Stage does not accept an input Checkpoint")
392
+ epochs = int(training.get("epochs", 2))
393
+ loss_value = 0.0
394
+ metric_rows = 0
395
+ metric_correct = 0
396
+ for epoch in range(epochs):
397
+ logits = (
398
+ model(x, edge_index, edge_type)
399
+ if edge_type is not None
400
+ else model(x, edge_index)
401
+ )
402
+ selected = logits[seed_index]
403
+ numerator = torch.nn.functional.cross_entropy(selected, labels, reduction="sum")
404
+ normalizer = int(labels.numel())
405
+
406
+ def finalize(scale: float) -> None:
407
+ for parameter in model.parameters():
408
+ if parameter.grad is not None:
409
+ parameter.grad.mul_(scale)
410
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_gradient_norm)
411
+ optimizer.step()
412
+ optimizer.zero_grad(set_to_none=True)
413
+
414
+ def reduce_normalizer(value: float) -> float:
415
+ tensor = torch.tensor(value, dtype=torch.float64, device=device)
416
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
417
+ torch.distributed.all_reduce(tensor, op=torch.distributed.ReduceOp.SUM)
418
+ return float(tensor.item())
419
+
420
+ apply_torch_loss_backward(
421
+ TorchLossContribution(numerator, normalizer),
422
+ TorchAccumulationWindow(index=epoch, expected_micro_batches=1),
423
+ TorchBackwardContext(
424
+ world_size=world_size,
425
+ backward=lambda value: value.backward(),
426
+ reduce_normalizer=reduce_normalizer,
427
+ finalize_window=finalize,
428
+ ),
429
+ )
430
+ with torch.no_grad():
431
+ loss_value = float(numerator.detach().item() / max(normalizer, 1))
432
+ metric_rows = normalizer
433
+ metric_correct = int((selected.argmax(dim=1) == labels).sum().item())
434
+
435
+ def reduce_metric(
436
+ name: str, contribution: TorchMetricContribution, reducer: str
437
+ ) -> float:
438
+ del name, reducer
439
+ state = torch.tensor(
440
+ [contribution.numerator, contribution.normalizer],
441
+ dtype=torch.float64,
442
+ device=device,
443
+ )
444
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
445
+ torch.distributed.all_reduce(state, op=torch.distributed.ReduceOp.SUM)
446
+ return float(state[0].item() / state[1].item()) if state[1].item() > 0 else 0.0
447
+
448
+ reduced_metrics = reduce_torch_metrics(
449
+ {
450
+ "train_loss": TorchMetricContribution(
451
+ loss_value * metric_rows, metric_rows
452
+ ),
453
+ "accuracy": TorchMetricContribution(metric_correct, metric_rows),
454
+ },
455
+ TorchMetricPolicy({"train_loss": "sum_count", "accuracy": "sum_count"}),
456
+ TorchMetricReductionContext(reduce_metric),
457
+ )
458
+ model = cast(torch.nn.Module, model.module if hasattr(model, "module") else model)
459
+ model.eval()
460
+ with torch.no_grad():
461
+ inference_logits = (
462
+ (
463
+ model(x, edge_index, edge_type)
464
+ if edge_type is not None
465
+ else model(x, edge_index)
466
+ )
467
+ .detach()
468
+ .cpu()
469
+ )
470
+ model_digest = _state_digest(cast(Mapping[str, object], model.state_dict()))
471
+ topology_digest = hashlib.sha256(
472
+ json.dumps(
473
+ {
474
+ "nodes": node_ids,
475
+ "source": source,
476
+ "destination": destination,
477
+ "relations": relations,
478
+ },
479
+ sort_keys=True,
480
+ separators=(",", ":"),
481
+ ).encode()
482
+ ).hexdigest()
483
+ node_feature_digest = _tensor_digest(x)
484
+ graph_identity_digest = _graph_identity_digest(
485
+ topology_digest=topology_digest,
486
+ node_feature_digest=node_feature_digest,
487
+ node_feature_names=node_features,
488
+ )
489
+ inference_logits_digest = _tensor_digest(inference_logits)
490
+ assigned = ray.get_runtime_context().get_assigned_resources()
491
+ worker = {
492
+ "worker_id": str(ray.get_runtime_context().get_worker_id()),
493
+ "node_id": str(ray.get_runtime_context().get_node_id()),
494
+ "rank": rank,
495
+ "world_size": world_size,
496
+ "shard_id": f"train-{rank}",
497
+ "rows_processed": len(labels),
498
+ "input_rows": {
499
+ "train": len(labels),
500
+ "nodes": len(node_ids),
501
+ "edges": len(source),
502
+ },
503
+ "batch_count": epochs,
504
+ "collective_steps": epochs,
505
+ "model_state_digest": model_digest,
506
+ "topology_digest": topology_digest,
507
+ "node_feature_digest": node_feature_digest,
508
+ "graph_identity_digest": graph_identity_digest,
509
+ "inference_logits_digest": inference_logits_digest,
510
+ "topology_kind": "relational" if relations else "homogeneous",
511
+ "resources": {
512
+ "num_cpus": float(assigned.get("CPU", 0.0)),
513
+ "num_gpus": float(assigned.get("GPU", 0.0)),
514
+ },
515
+ }
516
+ workers: list[object] = [worker] * world_size
517
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
518
+ torch.distributed.all_gather_object(workers, worker)
519
+ descriptor_context = checkpoint_context.stage
520
+ with tempfile.TemporaryDirectory(prefix="tributo-graph-checkpoint-") as directory:
521
+ root = Path(directory)
522
+ torch.save(model.state_dict(), root / "model.pt")
523
+ torch.save(inference_logits, root / "inference_logits.pt")
524
+ (root / "model_config.json").write_text(
525
+ json.dumps(
526
+ {
527
+ "input_features": len(node_features),
528
+ "hidden_features": int(model_config.get("hidden_features", 16)),
529
+ "num_classes": int(model_config.get("num_classes", 2)),
530
+ "node_features": list(node_features),
531
+ "model_kind": str(config.get("model_kind", "graphsage")),
532
+ "num_relations": int(model_config.get("num_relations", 1)),
533
+ "graph_identity_version": 1,
534
+ "topology_digest": topology_digest,
535
+ "node_feature_digest": node_feature_digest,
536
+ "graph_identity_digest": graph_identity_digest,
537
+ "inference_logits_digest": inference_logits_digest,
538
+ },
539
+ sort_keys=True,
540
+ ),
541
+ encoding="utf-8",
542
+ )
543
+
544
+ report_torch_checkpoint(
545
+ {
546
+ "train_loss": reduced_metrics.values["train_loss"],
547
+ "accuracy": reduced_metrics.values["accuracy"],
548
+ "execution_workers": workers,
549
+ "model_state_digest": model_digest,
550
+ },
551
+ TorchCheckpointPayloadDraft(root),
552
+ descriptor_context,
553
+ epochs,
554
+ )
555
+
556
+
557
+ @PublicAPI(stability="alpha")
558
+ class DistributedGraphSAGE(RayTorchAdapter):
559
+ """Train homogeneous full-neighborhood GraphSAGE with Core-owned Ray Train."""
560
+
561
+ model_kind = "graphsage"
562
+
563
+ def validate_environment(self, context: TorchRuntimeContext) -> None:
564
+ del context
565
+ try:
566
+ import torch
567
+ import torch_geometric
568
+ except ImportError as exc:
569
+ raise AlgorithmConfigurationError(
570
+ "GraphSAGE requires torch and torch-geometric"
571
+ ) from exc
572
+ if not torch.__version__ or not torch_geometric.__version__:
573
+ raise AlgorithmConfigurationError("GraphSAGE environment is invalid")
574
+
575
+ def bind_datasets(
576
+ self, datasets: Mapping[str, object], context: TorchStageContext
577
+ ) -> Mapping[str, object]:
578
+ del context
579
+ if set(datasets) != {"edges", "nodes", "train"}:
580
+ raise AlgorithmConfigurationError(
581
+ "graph training requires nodes, edges, and train datasets"
582
+ )
583
+ return dict(datasets)
584
+
585
+ def worker_config(self, context: TorchStageContext) -> Mapping[str, object]:
586
+ config = {
587
+ key: value
588
+ for key, value in context.runtime.algorithm_config.items()
589
+ if key not in {"ray", "output"}
590
+ }
591
+ config.setdefault("model_kind", self.model_kind)
592
+ bindings = context.runtime.input_bindings
593
+
594
+ def binding_for(role: str) -> Mapping[str, object]:
595
+ binding = bindings.get(role)
596
+ if not isinstance(binding, Mapping):
597
+ raise AlgorithmConfigurationError(
598
+ f"graph Stage context is missing the {role} binding"
599
+ )
600
+ return binding
601
+
602
+ node_binding = binding_for("nodes")
603
+ edge_binding = binding_for("edges")
604
+ train_binding = binding_for("train")
605
+
606
+ def feature_names(binding: Mapping[str, object]) -> tuple[object, ...]:
607
+ values = binding.get("feature_names", ())
608
+ return tuple(values) if isinstance(values, (list, tuple)) else ()
609
+
610
+ node_features = feature_names(node_binding)
611
+ edge_features = feature_names(edge_binding)
612
+ train_features = feature_names(train_binding)
613
+ label_name = train_binding.get("label_name")
614
+ if (
615
+ len(node_features) < 2
616
+ or len(edge_features) < 2
617
+ or len(train_features) != 1
618
+ or not isinstance(label_name, str)
619
+ or not label_name
620
+ ):
621
+ raise AlgorithmConfigurationError(
622
+ "graph Stage input bindings have an invalid typed layout"
623
+ )
624
+ columns: dict[str, object] = {
625
+ "node_id": str(node_features[0]),
626
+ "node_features": [str(name) for name in node_features[1:]],
627
+ "edge_source": str(edge_features[0]),
628
+ "edge_destination": str(edge_features[1]),
629
+ "seed_node_id": str(train_features[0]),
630
+ "seed_label": label_name,
631
+ }
632
+ if len(edge_features) >= 3:
633
+ columns["edge_relation"] = str(edge_features[2])
634
+ config["columns"] = columns
635
+ return config
636
+
637
+ def train_loop_per_worker(
638
+ self,
639
+ worker_config: Mapping[str, object],
640
+ checkpoint_context: TorchWorkerCheckpointContext,
641
+ ) -> None:
642
+ _graph_train_loop(worker_config, checkpoint_context)
643
+
644
+ def checkpoint_source(
645
+ self, result: object, context: TorchCheckpointContext
646
+ ) -> object:
647
+ del context
648
+ checkpoint = getattr(result, "checkpoint", None)
649
+ if checkpoint is None:
650
+ raise AlgorithmExecutionError("graph training result has no checkpoint")
651
+ return checkpoint
652
+
653
+ def metric_plan(self, context: TorchRuntimeContext) -> Any:
654
+ del context
655
+ from tributo.algorithms.spi import TorchMetricPlan
656
+
657
+ return TorchMetricPlan({"train_loss": "sum_count", "accuracy": "sum_count"})
658
+
659
+ def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
660
+ config = context.stage.runtime.algorithm_config.get("model", {})
661
+ classes = (
662
+ int(config.get("num_classes", 2)) if isinstance(config, Mapping) else 2
663
+ )
664
+ return TorchArtifactPlan(
665
+ source_kind="torch_module",
666
+ input_signature=(
667
+ {"name": "node_id", "dtype": "int64", "shape": ("batch",)},
668
+ ),
669
+ output_signature=(
670
+ {"name": "output", "dtype": "float32", "shape": ("batch", classes + 1)},
671
+ ),
672
+ targets=(
673
+ {
674
+ "name": "graph-model",
675
+ "format": "safetensors",
676
+ "exporter_id": "torch-safetensors-v1",
677
+ },
678
+ {
679
+ "name": "graph-inference",
680
+ "format": "onnx",
681
+ "exporter_id": "torch-onnx-v1",
682
+ "options": {"dynamo": False},
683
+ },
684
+ ),
685
+ roles={"model": "graph-model", "inference": "graph-inference"},
686
+ )
687
+
688
+ @contextmanager
689
+ def open_export_source(
690
+ self, checkpoint_ref: TorchCheckpointRef, artifact_context: TorchArtifactContext
691
+ ) -> Any:
692
+ import torch
693
+ import torch_geometric
694
+ from tributo.exporting.models import (
695
+ CheckpointField,
696
+ ExportCheckpointV1,
697
+ ExportSource,
698
+ )
699
+
700
+ checkpoint = checkpoint_ref.checkpoint
701
+ opener = getattr(checkpoint, "as_directory", None)
702
+ if not callable(opener):
703
+ raise AlgorithmExecutionError("graph checkpoint cannot be opened")
704
+ with opener() as directory:
705
+ root = Path(directory)
706
+ required_payloads = (
707
+ "model_config.json",
708
+ "model.pt",
709
+ "inference_logits.pt",
710
+ )
711
+ missing_payloads = [
712
+ name
713
+ for name in required_payloads
714
+ if not (root / name).is_file() or (root / name).is_symlink()
715
+ ]
716
+ if missing_payloads:
717
+ raise AlgorithmExecutionError(
718
+ f"graph checkpoint is missing payloads: {missing_payloads}"
719
+ )
720
+ model_config = json.loads(
721
+ (root / "model_config.json").read_text(encoding="utf-8")
722
+ )
723
+ model = cast(
724
+ torch.nn.Module,
725
+ _build_model(
726
+ int(model_config["input_features"]),
727
+ int(model_config["hidden_features"]),
728
+ int(model_config["num_classes"]),
729
+ model_kind=str(model_config.get("model_kind", self.model_kind)),
730
+ num_relations=int(model_config.get("num_relations", 1)),
731
+ ),
732
+ )
733
+ try:
734
+ model.load_state_dict(
735
+ torch.load(root / "model.pt", map_location="cpu", weights_only=True)
736
+ )
737
+ except (RuntimeError, TypeError, ValueError) as exc:
738
+ raise AlgorithmExecutionError(
739
+ "graph model payload is incompatible"
740
+ ) from exc
741
+ model.eval()
742
+ inference_logits = torch.load(
743
+ root / "inference_logits.pt", map_location="cpu", weights_only=True
744
+ )
745
+ if (
746
+ not isinstance(inference_logits, torch.Tensor)
747
+ or inference_logits.ndim != 2
748
+ or inference_logits.shape[0] < 1
749
+ or inference_logits.shape[1] != int(model_config["num_classes"])
750
+ or not bool(torch.isfinite(inference_logits).all())
751
+ ):
752
+ raise AlgorithmExecutionError(
753
+ "graph inference logits do not match the finite class contract"
754
+ )
755
+ if model_config.get("graph_identity_version") != 1:
756
+ raise AlgorithmExecutionError("graph identity version is unsupported")
757
+ topology_digest = _require_sha256(
758
+ model_config.get("topology_digest"), name="topology_digest"
759
+ )
760
+ node_feature_digest = _require_sha256(
761
+ model_config.get("node_feature_digest"), name="node_feature_digest"
762
+ )
763
+ graph_identity_digest = _require_sha256(
764
+ model_config.get("graph_identity_digest"), name="graph_identity_digest"
765
+ )
766
+ node_feature_names = model_config.get("node_features")
767
+ if not isinstance(node_feature_names, list) or not all(
768
+ isinstance(value, str) and value for value in node_feature_names
769
+ ):
770
+ raise AlgorithmExecutionError(
771
+ "graph checkpoint node features are invalid"
772
+ )
773
+ if graph_identity_digest != _graph_identity_digest(
774
+ topology_digest=topology_digest,
775
+ node_feature_digest=node_feature_digest,
776
+ node_feature_names=tuple(node_feature_names),
777
+ ):
778
+ raise AlgorithmExecutionError("graph identity digest mismatched")
779
+ expected_logits_digest = _require_sha256(
780
+ model_config.get("inference_logits_digest"),
781
+ name="inference_logits_digest",
782
+ )
783
+ actual_logits_digest = _tensor_digest(inference_logits)
784
+ if expected_logits_digest != actual_logits_digest:
785
+ raise AlgorithmExecutionError(
786
+ "graph inference logits digest mismatched"
787
+ )
788
+ model_digest = _state_digest(cast(Mapping[str, object], model.state_dict()))
789
+ yield ExportSource(
790
+ source_kind="torch_module",
791
+ model_object=_node_lookup_model(model, inference_logits),
792
+ architecture_id=artifact_context.stage.runtime.implementation_id,
793
+ model_config_data=model_config,
794
+ feature_schema={
795
+ "input_names": ["node_id"],
796
+ "node_features": node_feature_names,
797
+ "node_id_min": 0,
798
+ "node_id_max_exclusive": int(inference_logits.shape[0]),
799
+ "graph_identity_version": 1,
800
+ "topology_digest": topology_digest,
801
+ "node_feature_digest": node_feature_digest,
802
+ "graph_identity_digest": graph_identity_digest,
803
+ "inference_logits_digest": actual_logits_digest,
804
+ "output_layout": {
805
+ "logits": [0, int(model_config["num_classes"])],
806
+ "valid": int(model_config["num_classes"]),
807
+ },
808
+ "output_shape": ["batch", int(model_config["num_classes"]) + 1],
809
+ },
810
+ sample_inputs={"node_id": torch.tensor([0, 1], dtype=torch.int64)},
811
+ metadata={
812
+ "framework": "pytorch-geometric",
813
+ "framework_versions": {
814
+ "torch": torch.__version__,
815
+ "torch-geometric": torch_geometric.__version__,
816
+ },
817
+ "task_type": "node_classification",
818
+ "sampling": "full_neighborhood",
819
+ "graph_identity_digest": graph_identity_digest,
820
+ "topology_kind": "relational"
821
+ if self.model_kind == "rgcn"
822
+ else "homogeneous",
823
+ "producer_distribution": "tributo-algorithms",
824
+ },
825
+ source_fingerprint=_graph_source_fingerprint(
826
+ model_digest=model_digest,
827
+ graph_identity_digest=graph_identity_digest,
828
+ inference_logits_digest=actual_logits_digest,
829
+ ),
830
+ checkpoint_contract=ExportCheckpointV1(
831
+ trainer_type=str(model_config.get("model_kind", self.model_kind)),
832
+ architecture_id=artifact_context.stage.runtime.implementation_id,
833
+ input_schema=(
834
+ CheckpointField(
835
+ name="node_id", dtype="int64", shape=("batch",)
836
+ ),
837
+ ),
838
+ output_schema=(
839
+ CheckpointField(
840
+ name="output",
841
+ dtype="float32",
842
+ shape=("batch", int(model_config["num_classes"]) + 1),
843
+ ),
844
+ ),
845
+ preprocessing={
846
+ "type": "transductive_node_lookup",
847
+ "invalid_id_policy": "zero_output_with_valid_false",
848
+ "node_count": int(inference_logits.shape[0]),
849
+ "graph_identity_version": 1,
850
+ "topology_digest": topology_digest,
851
+ "node_feature_digest": node_feature_digest,
852
+ "graph_identity_digest": graph_identity_digest,
853
+ "inference_logits_digest": actual_logits_digest,
854
+ },
855
+ task_type="transductive_node_classification",
856
+ framework="pytorch-geometric",
857
+ framework_version=torch_geometric.__version__,
858
+ ),
859
+ )
860
+
861
+
862
+ @PublicAPI(stability="alpha")
863
+ class DistributedRGCN(DistributedGraphSAGE):
864
+ """Train a relation-aware graph through PyG RGCNConv."""
865
+
866
+ model_kind = "rgcn"
867
+
868
+
869
+ def create_algorithm(
870
+ *,
871
+ plan: object | None = None,
872
+ implementation: object | None = None,
873
+ artifacts: tuple[object, ...] = (),
874
+ ) -> RayTorchAdapter:
875
+ del plan, artifacts
876
+ if implementation is DistributedRGCN:
877
+ return DistributedRGCN()
878
+ if implementation is DistributedGraphSAGE:
879
+ return DistributedGraphSAGE()
880
+ raise AlgorithmConfigurationError("graph implementation drifted")
881
+
882
+
883
+ __all__ = ["DistributedGraphSAGE", "DistributedRGCN", "create_algorithm"]