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,707 @@
1
+ """RayTorchAdapter for jagged-history recommendation with All-to-All routing."""
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 _integer_tensor(
43
+ value: object,
44
+ field_name: str,
45
+ *,
46
+ device: Any = None,
47
+ ) -> Any:
48
+ import torch
49
+
50
+ tensor = torch.as_tensor(value, device=device)
51
+ if tensor.dtype == torch.bool or tensor.is_floating_point() or tensor.is_complex():
52
+ raise AlgorithmExecutionError(f"{field_name} must contain integer values")
53
+ return tensor.to(dtype=torch.long)
54
+
55
+
56
+ def _gradient_clip_norm(training: Mapping[str, Any]) -> float:
57
+ value = training.get("max_gradient_norm", 1.0)
58
+ if (
59
+ not isinstance(value, (int, float))
60
+ or isinstance(value, bool)
61
+ or not math.isfinite(float(value))
62
+ or float(value) <= 0
63
+ ):
64
+ raise AlgorithmConfigurationError(
65
+ "training.max_gradient_norm must be positive and finite"
66
+ )
67
+ return float(value)
68
+
69
+
70
+ def _model(*, user_count: int, item_count: int, embedding_dim: int) -> object:
71
+ import torch
72
+
73
+ if min(user_count, item_count, embedding_dim) < 1:
74
+ raise ValueError("jagged model dimensions must be positive")
75
+
76
+ class JaggedRankingModel(torch.nn.Module):
77
+ def __init__(self) -> None:
78
+ super().__init__()
79
+ self.user_embedding = torch.nn.Embedding(user_count, embedding_dim)
80
+ self.history_embedding = torch.nn.EmbeddingBag(
81
+ item_count, embedding_dim, mode="mean", include_last_offset=False
82
+ )
83
+ self.candidate_embedding = torch.nn.Embedding(item_count, embedding_dim)
84
+ self.bias = torch.nn.Parameter(torch.zeros(()))
85
+
86
+ def forward(
87
+ self,
88
+ user_ids: object,
89
+ history_values: object,
90
+ history_offsets: object,
91
+ candidate_ids: object,
92
+ ) -> object:
93
+ users = _integer_tensor(user_ids, "jagged user IDs")
94
+ values = _integer_tensor(history_values, "jagged history item IDs")
95
+ offsets = _integer_tensor(history_offsets, "jagged history offsets")
96
+ candidates = _integer_tensor(candidate_ids, "jagged candidate item IDs")
97
+ return (
98
+ self.user_embedding(users) + self.history_embedding(values, offsets)
99
+ ).mul(self.candidate_embedding(candidates)).sum(
100
+ dim=1, keepdim=True
101
+ ) + self.bias
102
+
103
+ return JaggedRankingModel()
104
+
105
+
106
+ def _padded_inference_model(model: object) -> object:
107
+ import torch
108
+
109
+ base = cast(torch.nn.Module, model)
110
+
111
+ class PaddedJaggedRankingModel(torch.nn.Module):
112
+ def __init__(self) -> None:
113
+ super().__init__()
114
+ self.user_embedding = cast(Any, base).user_embedding
115
+ self.history_embedding = cast(Any, base).history_embedding
116
+ self.candidate_embedding = cast(Any, base).candidate_embedding
117
+ self.bias = cast(Any, base).bias
118
+
119
+ def forward(
120
+ self, user_ids: object, item_history: object, candidate_ids: object
121
+ ) -> object:
122
+ users = _integer_tensor(user_ids, "jagged user IDs")
123
+ history = _integer_tensor(item_history, "jagged history item IDs")
124
+ candidates = _integer_tensor(candidate_ids, "jagged candidate item IDs")
125
+ user_count = self.user_embedding.num_embeddings
126
+ item_count = self.candidate_embedding.num_embeddings
127
+ user_valid = users.ge(0).logical_and(users.lt(user_count))
128
+ candidate_valid = candidates.ge(0).logical_and(candidates.lt(item_count))
129
+ history_valid = history.eq(-1).logical_or(
130
+ history.ge(0).logical_and(history.lt(item_count))
131
+ )
132
+ valid = user_valid.logical_and(candidate_valid).logical_and(
133
+ history_valid.all(dim=1)
134
+ )
135
+ safe_users = users.clamp(min=0, max=user_count - 1)
136
+ safe_candidates = candidates.clamp(min=0, max=item_count - 1)
137
+ mask = history.ge(0).logical_and(history_valid)
138
+ safe_history = history.clamp(min=0, max=item_count - 1)
139
+ embeddings = torch.nn.functional.embedding(
140
+ safe_history, self.history_embedding.weight
141
+ )
142
+ weights = mask.unsqueeze(-1).to(dtype=embeddings.dtype)
143
+ history_mean = (embeddings * weights).sum(dim=1) / weights.sum(
144
+ dim=1
145
+ ).clamp_min(1.0)
146
+ score = (self.user_embedding(safe_users) + history_mean).mul(
147
+ self.candidate_embedding(safe_candidates)
148
+ ).sum(dim=1, keepdim=True) + self.bias
149
+ output = torch.where(valid.unsqueeze(-1), score, torch.zeros_like(score))
150
+ return torch.cat(
151
+ (output, valid.unsqueeze(-1).to(dtype=output.dtype)), dim=1
152
+ )
153
+
154
+ return PaddedJaggedRankingModel()
155
+
156
+
157
+ def _state_digest(state: Mapping[str, object]) -> str:
158
+ digest = hashlib.sha256()
159
+ for name in sorted(state):
160
+ tensor = cast(Any, state[name]).detach().cpu().contiguous()
161
+ digest.update(name.encode())
162
+ digest.update(str(tensor.dtype).encode())
163
+ digest.update(str(tuple(tensor.shape)).encode())
164
+ digest.update(tensor.numpy().tobytes())
165
+ return digest.hexdigest()
166
+
167
+
168
+ def _jagged_tensors(
169
+ frame: object,
170
+ *,
171
+ user_col: str,
172
+ history_col: str,
173
+ candidate_col: str,
174
+ label_col: str,
175
+ item_count: int,
176
+ device: Any,
177
+ user_count: int | None = None,
178
+ ) -> tuple[Any, Any, Any, Any, Any, int]:
179
+ import numpy as np
180
+ import torch
181
+
182
+ data = cast(Any, frame)
183
+ histories: list[list[int]] = []
184
+ for raw in data[history_col].tolist():
185
+ values = (
186
+ raw.tolist()
187
+ if isinstance(raw, np.ndarray)
188
+ else list(raw)
189
+ if isinstance(raw, (list, tuple))
190
+ else None
191
+ )
192
+ if not values:
193
+ raise AlgorithmExecutionError(
194
+ "jagged histories must be non-empty sequences"
195
+ )
196
+ history_tensor = _integer_tensor(values, "jagged history item IDs")
197
+ if history_tensor.ndim != 1:
198
+ raise AlgorithmExecutionError(
199
+ "jagged histories must be one-dimensional sequences"
200
+ )
201
+ history = [int(value) for value in history_tensor.tolist()]
202
+ if any(value < 0 or value >= item_count for value in history):
203
+ raise AlgorithmExecutionError("jagged history item ID is out of range")
204
+ histories.append(history)
205
+ if not histories:
206
+ raise AlgorithmExecutionError("jagged recommendation shard is empty")
207
+ offsets: list[int] = []
208
+ flattened: list[int] = []
209
+ for history in histories:
210
+ offsets.append(len(flattened))
211
+ flattened.extend(history)
212
+ user_ids = _integer_tensor(
213
+ data[user_col].to_numpy(copy=True), "jagged user IDs", device=device
214
+ )
215
+ history_values = torch.as_tensor(flattened, dtype=torch.long, device=device)
216
+ history_offsets = torch.as_tensor(offsets, dtype=torch.long, device=device)
217
+ candidate_ids = _integer_tensor(
218
+ data[candidate_col].to_numpy(copy=True),
219
+ "jagged candidate item IDs",
220
+ device=device,
221
+ )
222
+ labels = torch.as_tensor(
223
+ data[label_col].to_numpy(copy=True), dtype=torch.float32, device=device
224
+ ).reshape(-1, 1)
225
+ if user_count is not None and (
226
+ bool((user_ids < 0).any()) or bool((user_ids >= user_count).any())
227
+ ):
228
+ raise AlgorithmExecutionError("jagged user ID is out of range")
229
+ if bool((candidate_ids < 0).any()) or bool((candidate_ids >= item_count).any()):
230
+ raise AlgorithmExecutionError("jagged candidate item ID is out of range")
231
+ if user_ids.shape != candidate_ids.shape or user_ids.shape[0] != labels.shape[0]:
232
+ raise AlgorithmExecutionError("jagged interaction columns have mismatched rows")
233
+ if not torch.isfinite(labels).all() or not bool(
234
+ ((labels == 0) | (labels == 1)).all()
235
+ ):
236
+ raise AlgorithmExecutionError("jagged labels must be finite 0 or 1")
237
+ return (
238
+ user_ids,
239
+ history_values,
240
+ history_offsets,
241
+ candidate_ids,
242
+ labels,
243
+ len(flattened),
244
+ )
245
+
246
+
247
+ def _route_sparse_keys(values: object, *, rank: int, world_size: int) -> int:
248
+ import torch
249
+ import torch.distributed as dist
250
+
251
+ tokens = cast(torch.Tensor, values)
252
+ if not dist.is_initialized() or world_size == 1:
253
+ return int(tokens.numel())
254
+ owners = torch.remainder(tokens, world_size)
255
+ send_counts_tensor = torch.bincount(owners, minlength=world_size).to(
256
+ dtype=torch.int64
257
+ )
258
+ gathered_counts = [torch.zeros_like(send_counts_tensor) for _ in range(world_size)]
259
+ dist.all_gather(gathered_counts, send_counts_tensor)
260
+ send_counts = [int(value) for value in send_counts_tensor.cpu().tolist()]
261
+ receive_counts = [
262
+ int(gathered_counts[source][rank].cpu()) for source in range(world_size)
263
+ ]
264
+ ordered = tokens[torch.argsort(owners)].contiguous()
265
+ received = torch.empty(
266
+ sum(receive_counts), dtype=tokens.dtype, device=tokens.device
267
+ )
268
+ dist.all_to_all_single(
269
+ received,
270
+ ordered,
271
+ output_split_sizes=receive_counts,
272
+ input_split_sizes=send_counts,
273
+ )
274
+ if received.numel() and not bool(
275
+ torch.remainder(received, world_size).eq(rank).all()
276
+ ):
277
+ raise AlgorithmExecutionError("All-to-All sparse-key ownership drifted")
278
+ return int(received.numel())
279
+
280
+
281
+ def _train_loop(
282
+ config: Mapping[str, Any], checkpoint_context: TorchWorkerCheckpointContext
283
+ ) -> None:
284
+ import pandas as pd
285
+ import ray
286
+ import torch
287
+ import torch.distributed as dist
288
+ from ray import train
289
+ from ray.train.torch import get_device, prepare_model
290
+
291
+ shard = train.get_dataset_shard("train")
292
+ frames = [
293
+ cast(pd.DataFrame, batch)
294
+ for batch in shard.iter_batches(batch_format="pandas", batch_size=256)
295
+ ]
296
+ if not frames:
297
+ raise AlgorithmExecutionError("jagged recommendation shard is empty")
298
+ frame = pd.concat(frames, ignore_index=True)
299
+ model_config = config.get("model")
300
+ data_config = config.get("data")
301
+ training = config.get("training")
302
+ if (
303
+ not isinstance(model_config, Mapping)
304
+ or not isinstance(data_config, Mapping)
305
+ or not isinstance(training, Mapping)
306
+ ):
307
+ raise AlgorithmConfigurationError(
308
+ "jagged model/data/training config is invalid"
309
+ )
310
+ device = get_device()
311
+ model = prepare_model(
312
+ cast(
313
+ torch.nn.Module,
314
+ _model(
315
+ user_count=int(model_config["user_count"]),
316
+ item_count=int(model_config["item_count"]),
317
+ embedding_dim=int(model_config["embedding_dim"]),
318
+ ),
319
+ )
320
+ )
321
+ context = train.get_context()
322
+ rank, world_size = context.get_world_rank(), context.get_world_size()
323
+ (
324
+ user_ids,
325
+ history_values,
326
+ history_offsets,
327
+ candidate_ids,
328
+ labels,
329
+ history_token_count,
330
+ ) = _jagged_tensors(
331
+ frame,
332
+ user_col=str(data_config["user_col"]),
333
+ history_col=str(data_config["history_col"]),
334
+ candidate_col=str(data_config["candidate_col"]),
335
+ label_col=str(data_config["label_col"]),
336
+ user_count=int(model_config["user_count"]),
337
+ item_count=int(model_config["item_count"]),
338
+ device=device,
339
+ )
340
+ routed_token_count = _route_sparse_keys(
341
+ history_values, rank=rank, world_size=world_size
342
+ )
343
+ optimizer = torch.optim.Adam(
344
+ model.parameters(), lr=float(training.get("learning_rate", 0.01))
345
+ )
346
+ max_gradient_norm = _gradient_clip_norm(training)
347
+ if checkpoint_context.source != "none" or checkpoint_context.checkpoint is not None:
348
+ raise AlgorithmExecutionError(
349
+ "jagged Stage does not accept an input Checkpoint"
350
+ )
351
+ logits = model(user_ids, history_values, history_offsets, candidate_ids)
352
+ numerator = torch.nn.functional.binary_cross_entropy_with_logits(
353
+ logits, labels, reduction="sum"
354
+ )
355
+ rows = int(labels.shape[0])
356
+
357
+ def reduce_normalizer(value: float) -> float:
358
+ tensor = torch.tensor(value, dtype=torch.float64, device=device)
359
+ if dist.is_initialized():
360
+ dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
361
+ return float(tensor.item())
362
+
363
+ def finalize(scale: float) -> None:
364
+ for parameter in model.parameters():
365
+ if parameter.grad is not None:
366
+ parameter.grad.mul_(scale)
367
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_gradient_norm)
368
+ optimizer.step()
369
+ optimizer.zero_grad(set_to_none=True)
370
+
371
+ apply_torch_loss_backward(
372
+ TorchLossContribution(numerator, rows),
373
+ TorchAccumulationWindow(0, 1),
374
+ TorchBackwardContext(
375
+ world_size=world_size,
376
+ backward=lambda value: value.backward(),
377
+ reduce_normalizer=reduce_normalizer,
378
+ finalize_window=finalize,
379
+ ),
380
+ )
381
+
382
+ def reduce_metric(
383
+ name: str, contribution: TorchMetricContribution, reducer: str
384
+ ) -> float:
385
+ del name, reducer
386
+ state = torch.tensor(
387
+ [contribution.numerator, contribution.normalizer],
388
+ dtype=torch.float64,
389
+ device=device,
390
+ )
391
+ if dist.is_initialized():
392
+ dist.all_reduce(state, op=dist.ReduceOp.SUM)
393
+ return float(state[0].item() / state[1].item()) if state[1].item() > 0 else 0.0
394
+
395
+ train_loss = reduce_torch_metrics(
396
+ {"train_loss": TorchMetricContribution(float(numerator.detach().item()), rows)},
397
+ TorchMetricPolicy({"train_loss": "sum_count"}),
398
+ TorchMetricReductionContext(reduce_metric),
399
+ ).values["train_loss"]
400
+ unwrapped = cast(
401
+ torch.nn.Module, model.module if hasattr(model, "module") else model
402
+ )
403
+ state = cast(Mapping[str, object], unwrapped.state_dict())
404
+ model_digest = _state_digest(state)
405
+ worker = {
406
+ "worker_id": str(ray.get_runtime_context().get_worker_id()),
407
+ "node_id": str(ray.get_runtime_context().get_node_id()),
408
+ "rank": rank,
409
+ "world_size": world_size,
410
+ "shard_id": f"jagged-{rank}",
411
+ "rows_processed": rows,
412
+ "input_rows": {
413
+ "train": rows,
414
+ "coverage.history_tokens": history_token_count,
415
+ "coverage.routed_owned_tokens": routed_token_count,
416
+ "coverage.positive_pairs": int((labels == 1).sum().item()),
417
+ "coverage.negative_pairs": int((labels == 0).sum().item()),
418
+ },
419
+ "batch_count": 1,
420
+ "collective_steps": 2,
421
+ "model_state_digest": model_digest,
422
+ }
423
+ workers: list[object] = [None] * world_size
424
+ if dist.is_initialized():
425
+ dist.all_gather_object(workers, worker)
426
+ else:
427
+ workers[0] = worker
428
+ with tempfile.TemporaryDirectory(prefix="tributo-jagged-") as directory:
429
+ root = Path(directory)
430
+ torch.save(dict(state), root / "model.pt")
431
+ (root / "model_config.json").write_text(
432
+ json.dumps(
433
+ {"model": dict(model_config), "data": dict(data_config)}, sort_keys=True
434
+ ),
435
+ encoding="utf-8",
436
+ )
437
+
438
+ report_torch_checkpoint(
439
+ {
440
+ "train_loss": train_loss,
441
+ "execution_workers": workers,
442
+ "model_state_digest": model_digest,
443
+ },
444
+ TorchCheckpointPayloadDraft(root),
445
+ checkpoint_context.stage,
446
+ 1,
447
+ )
448
+
449
+
450
+ @PublicAPI(stability="alpha")
451
+ class DistributedJaggedEmbedding(RayTorchAdapter):
452
+ """Train a DDP recommender while routing sparse history keys across workers."""
453
+
454
+ def validate_environment(self, context: TorchRuntimeContext) -> None:
455
+ del context
456
+ try:
457
+ import torch
458
+ except ImportError as exc:
459
+ raise AlgorithmConfigurationError(
460
+ "jagged recommendation requires PyTorch"
461
+ ) from exc
462
+ if not torch.__version__:
463
+ raise AlgorithmConfigurationError(
464
+ "jagged recommendation environment is invalid"
465
+ )
466
+
467
+ def bind_datasets(
468
+ self, datasets: Mapping[str, object], context: TorchStageContext
469
+ ) -> Mapping[str, object]:
470
+ del context
471
+ if set(datasets) != {"train"}:
472
+ raise AlgorithmConfigurationError(
473
+ "jagged recommendation requires train Dataset"
474
+ )
475
+ return dict(datasets)
476
+
477
+ def worker_config(self, context: TorchStageContext) -> Mapping[str, object]:
478
+ config = {
479
+ key: value
480
+ for key, value in context.runtime.algorithm_config.items()
481
+ if key not in {"ray", "output"}
482
+ }
483
+ binding = context.runtime.input_bindings.get("train")
484
+ if not isinstance(binding, Mapping):
485
+ raise AlgorithmConfigurationError(
486
+ "jagged Stage context is missing the train binding"
487
+ )
488
+ feature_names = binding.get("feature_names")
489
+ label_name = binding.get("label_name")
490
+ if (
491
+ not isinstance(feature_names, (list, tuple))
492
+ or len(feature_names) != 3
493
+ or not all(isinstance(name, str) and name for name in feature_names)
494
+ or not isinstance(label_name, str)
495
+ or not label_name
496
+ or binding.get("sample_weight_name") is not None
497
+ ):
498
+ raise AlgorithmConfigurationError(
499
+ "jagged train binding has an invalid typed layout"
500
+ )
501
+ data = config.get("data")
502
+ if not isinstance(data, Mapping):
503
+ raise AlgorithmConfigurationError("jagged data config is required")
504
+ normalized_data = dict(data)
505
+ normalized_data.update(
506
+ {
507
+ "user_col": feature_names[0],
508
+ "history_col": feature_names[1],
509
+ "candidate_col": feature_names[2],
510
+ "label_col": label_name,
511
+ }
512
+ )
513
+ config["data"] = normalized_data
514
+ return config
515
+
516
+ def train_loop_per_worker(
517
+ self,
518
+ worker_config: Mapping[str, object],
519
+ checkpoint_context: TorchWorkerCheckpointContext,
520
+ ) -> None:
521
+ _train_loop(worker_config, checkpoint_context)
522
+
523
+ def checkpoint_source(
524
+ self, result: object, context: TorchCheckpointContext
525
+ ) -> object:
526
+ del context
527
+ checkpoint = getattr(result, "checkpoint", None)
528
+ if checkpoint is None:
529
+ raise AlgorithmExecutionError("jagged training result has no checkpoint")
530
+ return checkpoint
531
+
532
+ def metric_plan(self, context: TorchRuntimeContext) -> TorchMetricPlan:
533
+ del context
534
+ return TorchMetricPlan({"train_loss": "sum_count"})
535
+
536
+ def artifact_plan(self, context: TorchArtifactContext) -> TorchArtifactPlan:
537
+ config = context.stage.runtime.algorithm_config.get("data", {})
538
+ width = (
539
+ int(config.get("inference_history_width", 1))
540
+ if isinstance(config, Mapping)
541
+ else 1
542
+ )
543
+ return TorchArtifactPlan(
544
+ source_kind="torch_module",
545
+ input_signature=(
546
+ {"name": "user_id", "dtype": "int64", "shape": ("batch",)},
547
+ {"name": "item_history", "dtype": "int64", "shape": ("batch", width)},
548
+ {"name": "item_id", "dtype": "int64", "shape": ("batch",)},
549
+ ),
550
+ output_signature=(
551
+ {"name": "output", "dtype": "float32", "shape": ("batch", 2)},
552
+ ),
553
+ targets=(
554
+ {
555
+ "name": "jagged-ranking-model",
556
+ "format": "safetensors",
557
+ "exporter_id": "torch-safetensors-v1",
558
+ },
559
+ {
560
+ "name": "jagged-ranking-inference",
561
+ "format": "onnx",
562
+ "exporter_id": "torch-onnx-v1",
563
+ "options": {"dynamo": False},
564
+ },
565
+ ),
566
+ roles={
567
+ "model": "jagged-ranking-model",
568
+ "inference": "jagged-ranking-inference",
569
+ },
570
+ )
571
+
572
+ @contextmanager
573
+ def open_export_source(
574
+ self, checkpoint_ref: TorchCheckpointRef, artifact_context: TorchArtifactContext
575
+ ) -> Any:
576
+ import torch
577
+ from tributo.exporting.models import (
578
+ CheckpointField,
579
+ ExportCheckpointV1,
580
+ ExportSource,
581
+ )
582
+
583
+ opener = getattr(checkpoint_ref.checkpoint, "as_directory", None)
584
+ if not callable(opener):
585
+ raise AlgorithmExecutionError("jagged checkpoint cannot be opened")
586
+ with opener() as directory:
587
+ root = Path(directory)
588
+ required_payloads = ("model_config.json", "model.pt")
589
+ missing_payloads = [
590
+ name
591
+ for name in required_payloads
592
+ if not (root / name).is_file() or (root / name).is_symlink()
593
+ ]
594
+ if missing_payloads:
595
+ raise AlgorithmExecutionError(
596
+ f"jagged checkpoint is missing payloads: {missing_payloads}"
597
+ )
598
+ metadata = json.loads(
599
+ (root / "model_config.json").read_text(encoding="utf-8")
600
+ )
601
+ model_config = cast(Mapping[str, Any], metadata["model"])
602
+ data_config = cast(Mapping[str, Any], metadata["data"])
603
+ model = cast(
604
+ torch.nn.Module,
605
+ _model(
606
+ user_count=int(model_config["user_count"]),
607
+ item_count=int(model_config["item_count"]),
608
+ embedding_dim=int(model_config["embedding_dim"]),
609
+ ),
610
+ )
611
+ try:
612
+ model.load_state_dict(
613
+ torch.load(root / "model.pt", map_location="cpu", weights_only=True)
614
+ )
615
+ except (RuntimeError, TypeError, ValueError) as exc:
616
+ raise AlgorithmExecutionError(
617
+ "jagged model payload is incompatible"
618
+ ) from exc
619
+ model.eval()
620
+ yield ExportSource(
621
+ source_kind="torch_module",
622
+ model_object=_padded_inference_model(model),
623
+ architecture_id=artifact_context.stage.runtime.implementation_id,
624
+ model_config_data=metadata,
625
+ feature_schema={
626
+ "input_names": ["user_id", "item_history", "item_id"],
627
+ "raw_feature_names": [
628
+ str(data_config["user_col"]),
629
+ str(data_config["history_col"]),
630
+ str(data_config["candidate_col"]),
631
+ ],
632
+ "jagged_feature": str(data_config["history_col"]),
633
+ "user_id_min": 0,
634
+ "user_id_max_exclusive": int(model_config["user_count"]),
635
+ "item_id_min": 0,
636
+ "item_id_max_exclusive": int(model_config["item_count"]),
637
+ "output_layout": {"score": 0, "valid": 1},
638
+ "history_width": int(data_config["inference_history_width"]),
639
+ },
640
+ sample_inputs={
641
+ "user_id": torch.tensor([0, 0], dtype=torch.int64),
642
+ "item_history": torch.tensor(
643
+ [[0] + [-1] * (int(data_config["inference_history_width"]) - 1)]
644
+ * 2,
645
+ dtype=torch.int64,
646
+ ),
647
+ "item_id": torch.tensor([0, 0], dtype=torch.int64),
648
+ },
649
+ metadata={
650
+ "framework": "pytorch",
651
+ "task_type": "ranking",
652
+ "sparse_routing": "all_to_all_single_owner_mod",
653
+ "producer_distribution": "tributo-algorithms",
654
+ },
655
+ source_fingerprint=_state_digest(
656
+ cast(Mapping[str, object], model.state_dict())
657
+ ),
658
+ checkpoint_contract=ExportCheckpointV1(
659
+ trainer_type="jagged_embedding_recommender",
660
+ architecture_id=artifact_context.stage.runtime.implementation_id,
661
+ input_schema=(
662
+ CheckpointField(
663
+ name="user_id", dtype="int64", shape=("batch",)
664
+ ),
665
+ CheckpointField(
666
+ name="item_history",
667
+ dtype="int64",
668
+ shape=(
669
+ "batch",
670
+ int(data_config["inference_history_width"]),
671
+ ),
672
+ ),
673
+ CheckpointField(
674
+ name="item_id", dtype="int64", shape=("batch",)
675
+ ),
676
+ ),
677
+ output_schema=(
678
+ CheckpointField(
679
+ name="output", dtype="float32", shape=("batch", 2)
680
+ ),
681
+ ),
682
+ preprocessing={
683
+ "type": "padded_jagged_history",
684
+ "padding_value": -1,
685
+ "history_width": int(data_config["inference_history_width"]),
686
+ "invalid_id_policy": "zero_output_with_valid_false",
687
+ },
688
+ task_type="ranking",
689
+ framework="pytorch",
690
+ framework_version=torch.__version__,
691
+ ),
692
+ )
693
+
694
+
695
+ def create_jagged_algorithm(
696
+ *,
697
+ plan: object | None = None,
698
+ implementation: object | None = None,
699
+ artifacts: tuple[object, ...] = (),
700
+ ) -> DistributedJaggedEmbedding:
701
+ del plan, artifacts
702
+ if implementation is not DistributedJaggedEmbedding:
703
+ raise AlgorithmConfigurationError("jagged implementation drifted")
704
+ return DistributedJaggedEmbedding()
705
+
706
+
707
+ __all__ = ["DistributedJaggedEmbedding", "create_jagged_algorithm"]