Skip to content

Training Pipeline

The training pipeline is split into native teacher/student training and teacher-student distillation. Both paths use shared data loading, model factory, checkpointing, tracking, and evaluation utilities.

Distillation From Config

python scripts/recdistill/train_student_from_config.py \
  --config config/experiments/recdistill/de_citeulike_001.yaml

Direct Distillation

python scripts/recdistill/train_student.py \
  --dataset citeulike \
  --teacher-framework recbole \
  --teacher-model BPRMF \
  --student-framework recbole \
  --student-backbone LGCN \
  --lambda-de 0.1

Experiment Runners

RecDistillExperimentRunner

Source code in recdistill/experiment_runner.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
class RecDistillExperimentRunner:
    def __init__(self, args: Any, wandb_logger=None):
        self.config = args if isinstance(args, RecDistillConfig) else None
        self.args = runner_args_from_config(args) if isinstance(args, RecDistillConfig) else args
        self.wandb_logger = wandb_logger
        args = self.args
        self.device = torch.device(args.device) if args.device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.student_backbone = normalize_backbone_name(args.student_backbone)
        self.teacher_source = _teacher_source_from_args(args)
        self.teacher_path = self.teacher_source.path
        self.output_path = _distilled_student_path(
            resolve_student_checkpoint_from_args(args, distiller_name=self.resolve_distiller_name())
        )
        self.output_path.parent.mkdir(parents=True, exist_ok=True)
        self.run_dir = self.output_path.parent.parent if self.output_path.parent.name == "artifacts" else self.output_path.parent
        (self.run_dir / "perf").mkdir(parents=True, exist_ok=True)
        (self.run_dir / "logs").mkdir(parents=True, exist_ok=True)
        (self.run_dir / "config").mkdir(parents=True, exist_ok=True)

        self.teacher_state = None
        self.dataset = None
        self.val_dict: dict[int, set[int]] = {}
        self.test_dict: dict[int, set[int]] = {}
        self.model = None
        self.distiller = None
        self.optimizer = None
        self.trainer = None

    @classmethod
    def from_config(cls, config: RecDistillConfig, wandb_logger=None) -> "RecDistillExperimentRunner":
        return cls(config, wandb_logger=wandb_logger)

    def resolve_distiller_name(self) -> str:
        names = []
        if float(getattr(self.args, "lambda_de", 0.0)) > 0:
            names.append("DE")
        if float(getattr(self.args, "lambda_rrd", 0.0)) > 0:
            names.append("RRD")
        if float(getattr(self.args, "lambda_unkd", 0.0)) > 0:
            names.append("UnKD")
        if float(getattr(self.args, "lambda_td", 0.0)) > 0:
            names.append(str(getattr(self.args, "td_type", "TD")).upper())
        return "-".join(names) if names else "NONE"

    def run_config(self) -> dict[str, Any]:
        return {
            "config_source": "RecDistillConfig" if self.config is not None else "args",
            "dataset": self.args.dataset,
            "teacher_model": self.args.teacher_model,
            "teacher_path": str(self.teacher_path) if self.teacher_path is not None else None,
            "teacher_framework": getattr(self.args, "teacher_framework", "auto"),
            "teacher_format": getattr(self.args, "teacher_format", "auto"),
            "teacher_embedding_dim": self.args.teacher_embedding_dim,
            "student_backbone": self.student_backbone,
            "student_framework": self.args.student_framework,
            "student_embedding_dim": self.args.student_embedding_dim,
            "lightgcn_layers": self.args.lightgcn_layers,
            "neumf_mlp_dims": self.args.neumf_mlp_dims,
            "neumf_dropout": self.args.neumf_dropout,
            "epochs": self.args.epochs,
            "batch_size": self.args.batch_size,
            "learning_rate": self.args.learning_rate,
            "l2_reg": self.args.l2_reg,
            "lambda_de": self.args.lambda_de,
            "num_experts": self.args.num_experts,
            "temperature": self.args.temperature,
            "lambda_rrd": self.args.lambda_rrd,
            "rrd_interesting_size": self.args.rrd_interesting_size,
            "rrd_uninteresting_size": self.args.rrd_uninteresting_size,
            "rrd_temperature": self.args.rrd_temperature,
            "rrd_teacher_topk": self.args.rrd_teacher_topk,
            "lambda_unkd": self.args.lambda_unkd,
            "unkd_sample_num": self.args.unkd_sample_num,
            "unkd_group_count": self.args.unkd_group_count,
            "unkd_popularity_lambda": self.args.unkd_popularity_lambda,
            "unkd_rank_top_k": self.args.unkd_rank_top_k,
            "unkd_rank_temperature": self.args.unkd_rank_temperature,
            "lambda_td": self.args.lambda_td,
            "td_type": self.args.td_type,
            "htd_alpha": self.args.htd_alpha,
            "htd_num_groups": self.args.htd_num_groups,
            "htd_topology_mode": self.args.htd_topology_mode,
            "htd_initial_tau": self.args.htd_initial_tau,
            "htd_min_tau": self.args.htd_min_tau,
            "htd_decay_epochs": self.args.htd_decay_epochs,
            "td_entity_sample_size": self.args.td_entity_sample_size,
            "seed": self.args.seed,
            "eval_enabled": not self.args.skip_eval,
            "eval_k": self.args.eval_k,
            "eval_every": self.args.eval_every,
            "selection_split": self.args.selection_split,
            "selection_metric": self.args.selection_metric,
            "assert_no_train_leak": self.args.assert_no_train_leak,
        }

    def prepare(self) -> None:
        print("\n" + "=" * 80)
        print("Student Distillation Training")
        print("=" * 80)
        print(f"Dataset: {self.args.dataset}")
        print(f"Teacher source: {self.teacher_path or self.teacher_source.format}")
        print(f"Student backbone: {self.student_backbone}")
        print(f"Student framework: {self.args.student_framework}")
        print(f"Device: {self.device}")
        print("=" * 80 + "\n")

        teacher_state = load_teacher(self.teacher_source, device="cpu")
        validate_loaded_teacher_for_distillation(teacher_state, self.resolve_distiller_name())
        print(f"Teacher users/items: {teacher_state.num_users}/{teacher_state.num_items}")
        print(f"Teacher embedding dim: {teacher_state.embedding_dim if teacher_state.has_embeddings else 'none'}")
        print(f"Teacher exact scorer: {teacher_state.scorer is not None}")
        teacher_embedding_source = teacher_state.metadata.get("embedding_source")
        if teacher_embedding_source:
            print(f"Teacher embedding source: {teacher_embedding_source}")
        teacher_representation = teacher_state.metadata.get("representation")
        if teacher_representation:
            print(f"Teacher embedding representation: {teacher_representation}")

        self.teacher_state = teacher_state
        user_mapping, item_mapping, mapping_source = resolve_teacher_dataset_mappings(
            teacher_state.metadata,
            dataset_name=self.args.dataset,
        )
        split_id_space = "dataset_integer" if mapping_source == "dataset_integer" else None
        print(f"Dataset mapping source: {mapping_source}")
        self.dataset, dropped = load_train_dataset(
            dataset_name=self.args.dataset,
            teacher_num_users=teacher_state.num_users,
            teacher_num_items=teacher_state.num_items,
            user_mapping=user_mapping,
            item_mapping=item_mapping,
            id_space=split_id_space,
        )
        print(f"Train interactions: {len(self.dataset.interactions)}")
        print(f"Dropped interactions (out of teacher range): {dropped}")

        if not self.args.skip_eval:
            self.val_dict, dropped_val = load_eval_split(
                dataset_name=self.args.dataset,
                split_name="val",
                teacher_num_users=teacher_state.num_users,
                teacher_num_items=teacher_state.num_items,
                user_mapping=user_mapping,
                item_mapping=item_mapping,
                id_space=split_id_space,
            )
            self.test_dict, dropped_test = load_eval_split(
                dataset_name=self.args.dataset,
                split_name="test",
                teacher_num_users=teacher_state.num_users,
                teacher_num_items=teacher_state.num_items,
                user_mapping=user_mapping,
                item_mapping=item_mapping,
                id_space=split_id_space,
            )
            print(f"Validation interactions: {sum(len(v) for v in self.val_dict.values())} (dropped: {dropped_val})")
            print(f"Test interactions: {sum(len(v) for v in self.test_dict.values())} (dropped: {dropped_test})")

        train_loader = build_train_loader(self.dataset, batch_size=self.args.batch_size, num_workers=self.args.num_workers)
        self.model = build_student_model(
            backbone=self.student_backbone,
            dataset=self.dataset,
            embedding_dim=self.args.student_embedding_dim,
            l2_reg=self.args.l2_reg,
            lightgcn_layers=self.args.lightgcn_layers,
            neumf_mlp_dims=self.args.neumf_mlp_dims,
            neumf_dropout=self.args.neumf_dropout,
            framework=self.args.student_framework,
            graph_builder=build_lightgcn_graph,
        ).to(self.device)
        self.distiller = build_distiller_from_args(
            args=self.args,
            teacher_state=teacher_state,
            student_dim=self.args.student_embedding_dim,
        )
        teacher_state_for_distiller = teacher_state.to(self.device)
        if self.distiller is not None:
            self.distiller = self.distiller.to(self.device)
            self.distiller.on_train_start(teacher_state_for_distiller, self.dataset)
            prepare_distiller_trainable_modules(self.distiller, int(self.args.student_embedding_dim), self.device)
            setattr(self.distiller, "_recdistill_initialized", True)

        trainable_params = list(self.model.parameters())
        if self.distiller is not None:
            trainable_params += list(self.distiller.parameters())
        self.optimizer = torch.optim.Adam(trainable_params, lr=self.args.learning_rate)
        self.trainer = DistillationTrainer(
            model=self.model,
            optimizer=self.optimizer,
            train_loader=train_loader,
            distiller=self.distiller,
            device=self.device,
            teacher_state=teacher_state,
            dataset=self.dataset,
        )

        if not self.args.skip_eval:
            scorer_note = "exact scorer" if teacher_state.scorer is not None else "embedding dot product"
            teacher_eval = evaluate_embeddings(
                user_embeddings=teacher_state.user_embeddings,
                item_embeddings=teacher_state.item_embeddings,
                train_seen=self.dataset.train_dict,
                ground_truth=self.val_dict,
                top_k=self.args.eval_k,
                batch_size=self.args.eval_batch_size,
                device=self.device,
                scorer=teacher_state.scorer,
            )[0]
            print(
                f"Teacher baseline @ {self.args.eval_k} (val, {scorer_note}): "
                f"P={teacher_eval['precision']:.4f} "
                f"R={teacher_eval['recall']:.4f} "
                f"NDCG={teacher_eval['ndcg']:.4f} "
                f"HR={teacher_eval['hr']:.4f}"
            )

    def run(self) -> dict[str, Any]:
        set_seed(int(self.args.seed))
        self.prepare()
        return self.train()

    def train(self) -> dict[str, Any]:
        args = self.args
        assert self.teacher_state is not None
        assert self.dataset is not None
        assert self.model is not None
        assert self.optimizer is not None
        assert self.trainer is not None

        start_payload = {
            "status": "running",
            "started_at_utc": utc_now_iso(),
            **self.run_config(),
            "teacher_embedding_dim": int(self.teacher_state.embedding_dim) if self.teacher_state.has_embeddings else None,
        }
        if self.wandb_logger is not None:
            self.wandb_logger.log_start(start_payload)

        history: list[dict[str, float | int]] = []
        best_score = float("-inf")
        best_epoch = 0
        best_checkpoint = best_checkpoint_path(self.output_path)
        saved_best_checkpoint = False
        early_best_value: float | None = None
        early_best_epoch = 0
        early_bad_steps = 0
        early_stopped = False
        early_stop_reason: str | None = None
        early_monitor_name = "total_loss" if args.early_stop_mode == "loss" else f"val_{args.early_stop_metric}"
        early_best_checkpoint = self.output_path.with_name(f"{self.output_path.stem}.earlystop_best{DISTILLED_STUDENT_EXT}")

        run_status = "completed"
        run_error: str | None = None
        caught_exception: Exception | None = None
        final_test_eval: dict[str, Any] | None = None
        try:
            for epoch in range(1, args.epochs + 1):
                metrics = self.trainer.train_epoch()
                row = {"epoch": epoch, **metrics}
                current_eval: dict[str, dict[str, float] | int] | None = None
                if not args.skip_eval and args.eval_every > 0 and (epoch % args.eval_every == 0):
                    current_eval = evaluate_student(
                        model=self.model,
                        train_seen=self.dataset.train_dict,
                        val_gt=self.val_dict,
                        test_gt=self.test_dict,
                        top_k=args.eval_k,
                        batch_size=args.eval_batch_size,
                        device=self.device,
                        eval_val_only=args.eval_val_only,
                    )
                    self._update_eval_row(row, current_eval)
                    leaked_users_test = int(current_eval.get("leaked_users_test", 0))
                    if args.assert_no_train_leak and (current_eval["leaked_users_val"] > 0 or leaked_users_test > 0):
                        raise RuntimeError(
                            "Train-item leakage detected in recommendations. "
                            f"val_leaks={current_eval['leaked_users_val']} test_leaks={leaked_users_test}"
                        )

                    selected_split_metrics = current_eval[args.selection_split]
                    selected_score = float(selected_split_metrics[args.selection_metric])
                    row["selection_score"] = selected_score
                    if selected_score > best_score:
                        best_score = selected_score
                        best_epoch = epoch
                        self._save_checkpoint(best_checkpoint, epoch, history + [row], best_epoch, best_score)
                        saved_best_checkpoint = True

                history.append(row)
                if self.wandb_logger is not None:
                    self.wandb_logger.log_epoch(row)
                self._print_epoch(epoch, metrics, current_eval)

                if args.save_every > 0 and (epoch % args.save_every == 0):
                    periodic_path = self.output_path.with_name(f"{self.output_path.stem}.ep{epoch}{DISTILLED_STUDENT_EXT}")
                    self._save_checkpoint(periodic_path, epoch, history, best_epoch, best_score if best_epoch > 0 else None)
                    print(f"Saved periodic checkpoint: {periodic_path}")

                early_state = self._maybe_early_stop(
                    epoch=epoch,
                    row=row,
                    current_eval=current_eval,
                    early_best_value=early_best_value,
                    early_best_epoch=early_best_epoch,
                    early_bad_steps=early_bad_steps,
                    early_monitor_name=early_monitor_name,
                    early_best_checkpoint=early_best_checkpoint,
                )
                early_best_value = early_state["best_value"]
                early_best_epoch = early_state["best_epoch"]
                early_bad_steps = early_state["bad_steps"]
                if early_state["stopped"]:
                    early_stopped = True
                    early_stop_reason = early_state["reason"]
                    print(f"Early stopping triggered at epoch {epoch}: {early_stop_reason}")
                    break
        except Exception as exc:
            run_status = "failed"
            run_error = str(exc)
            caught_exception = exc

        if (
            caught_exception is None
            and args.early_stop
            and args.early_stop_restore_best
            and early_best_epoch > 0
            and early_best_checkpoint.exists()
        ):
            payload = load_student_checkpoint(early_best_checkpoint, map_location=self.device)
            self.model.load_state_dict(payload["student_state_dict"])
            print(
                f"Restored early-stop best checkpoint from epoch {payload['epoch']} "
                f"({payload['monitor_name']}={payload['monitor_value']:.6f})"
            )

        if caught_exception is None and not args.skip_eval and args.eval_val_only and len(self.test_dict) > 0:
            final_test_eval = evaluate_student(
                model=self.model,
                train_seen=self.dataset.train_dict,
                val_gt=self.val_dict,
                test_gt=self.test_dict,
                top_k=args.eval_k,
                batch_size=args.eval_batch_size,
                device=self.device,
                eval_val_only=False,
            )
            print(
                f"Final Test@{args.eval_k}: "
                f"P={final_test_eval['test']['precision']:.4f} "
                f"R={final_test_eval['test']['recall']:.4f} "
                f"NDCG={final_test_eval['test']['ndcg']:.4f} "
                f"HR={final_test_eval['test']['hr']:.4f} "
                f"| leaks={final_test_eval['leaked_users_test']}"
            )

        history_path = self.run_dir / "logs" / f"{self.output_path.stem}.history.json"
        should_save_final = caught_exception is None and (
            not saved_best_checkpoint or (args.early_stop and args.early_stop_restore_best and early_best_epoch > 0)
        )
        if should_save_final:
            final_epoch = int(history[-1]["epoch"]) if history else 0
            self._save_checkpoint(
                self.output_path,
                final_epoch,
                history,
                best_epoch,
                best_score if best_epoch > 0 else None,
                extra={
                    "early_stopped": early_stopped,
                    "early_stop_reason": early_stop_reason,
                    "early_best_epoch": early_best_epoch if early_best_epoch > 0 else None,
                    "early_best_value": early_best_value,
                    "early_monitor_name": early_monitor_name if args.early_stop else None,
                    "final_test_eval": final_test_eval,
                },
            )
        if caught_exception is None:
            history_path.write_text(json.dumps(history, indent=2), encoding="utf-8")

        end_payload = {
            "status": run_status,
            "ended_at_utc": utc_now_iso(),
            "best_epoch": int(best_epoch),
            "best_selection_score": float(best_score) if best_epoch > 0 else None,
            "best_checkpoint": str(best_checkpoint) if best_epoch > 0 else None,
            "final_checkpoint": str(self.output_path) if caught_exception is None else None,
            "history_file": str(history_path) if history_path.exists() else None,
            "early_stopped": early_stopped,
            "early_stop_reason": early_stop_reason,
            "early_best_epoch": early_best_epoch if early_best_epoch > 0 else None,
            "early_best_value": early_best_value,
            "early_monitor_name": early_monitor_name if args.early_stop else None,
            "final_test_eval": final_test_eval,
            "error": run_error,
        }
        if self.wandb_logger is not None:
            self.wandb_logger.log_end(end_payload)
        if caught_exception is not None:
            raise caught_exception

        print("\nTraining complete.")
        print(f"Student checkpoint: {self.output_path}")
        if best_epoch > 0:
            print(
                f"Best checkpoint ({args.selection_split}.{args.selection_metric}): "
                f"epoch={best_epoch} score={best_score:.6f} path={best_checkpoint}"
            )
        if final_test_eval is not None:
            print(
                f"Final test metrics: "
                f"NDCG={final_test_eval['test']['ndcg']:.4f} "
                f"HR={final_test_eval['test']['hr']:.4f}"
            )
        print(f"History JSON: {history_path}\n")
        return end_payload

    def _checkpoint_payload(
        self,
        epoch: int,
        history: list[dict[str, Any]],
        best_epoch: int,
        best_score: float | None,
        extra: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        payload = {
            "epoch": epoch,
            "student_state_dict": self.model.state_dict(),
            "optimizer_state_dict": self.optimizer.state_dict(),
            "history": history,
            "config": vars(self.args),
            "teacher_path": str(self.teacher_path) if self.teacher_path is not None else None,
            "teacher_dim": self.teacher_state.embedding_dim if self.teacher_state.has_embeddings else None,
            "num_users": self.dataset.num_users,
            "num_items": self.dataset.num_items,
            "best_epoch": best_epoch,
            "best_selection_score": best_score,
            "best_selection_split": self.args.selection_split,
            "best_selection_metric": self.args.selection_metric,
        }
        if extra:
            payload.update(extra)
        return payload

    def _save_checkpoint(
        self,
        path: Path,
        epoch: int,
        history: list[dict[str, Any]],
        best_epoch: int,
        best_score: float | None,
        extra: dict[str, Any] | None = None,
    ) -> None:
        save_student_checkpoint(path, self._checkpoint_payload(epoch, history, best_epoch, best_score, extra))

    def _update_eval_row(self, row: dict[str, Any], current_eval: dict[str, Any]) -> None:
        row["val_precision"] = float(current_eval["val"]["precision"])
        row["val_recall"] = float(current_eval["val"]["recall"])
        row["val_ndcg"] = float(current_eval["val"]["ndcg"])
        row["val_hr"] = float(current_eval["val"]["hr"])
        row["leaked_users_val"] = int(current_eval["leaked_users_val"])
        if not self.args.eval_val_only:
            row["test_precision"] = float(current_eval["test"]["precision"])
            row["test_recall"] = float(current_eval["test"]["recall"])
            row["test_ndcg"] = float(current_eval["test"]["ndcg"])
            row["test_hr"] = float(current_eval["test"]["hr"])
            row["leaked_users_test"] = int(current_eval["leaked_users_test"])

    def _print_epoch(self, epoch: int, metrics: dict[str, float], current_eval: dict[str, Any] | None) -> None:
        print(
            f"Epoch {epoch:03d}/{self.args.epochs:03d} | "
            f"base={metrics['base_loss']:.6f} "
            f"distill={metrics['distill_loss']:.6f} "
            f"total={metrics['total_loss']:.6f}"
        )
        if current_eval is None:
            return
        print(
            f"  Val@{self.args.eval_k}: "
            f"P={current_eval['val']['precision']:.4f} "
            f"R={current_eval['val']['recall']:.4f} "
            f"NDCG={current_eval['val']['ndcg']:.4f} "
            f"HR={current_eval['val']['hr']:.4f} "
            f"| leaks={current_eval['leaked_users_val']}"
        )
        if not self.args.eval_val_only:
            print(
                f"  Test@{self.args.eval_k}: "
                f"P={current_eval['test']['precision']:.4f} "
                f"R={current_eval['test']['recall']:.4f} "
                f"NDCG={current_eval['test']['ndcg']:.4f} "
                f"HR={current_eval['test']['hr']:.4f} "
                f"| leaks={current_eval['leaked_users_test']}"
            )

    def _maybe_early_stop(
        self,
        *,
        epoch: int,
        row: dict[str, Any],
        current_eval: dict[str, Any] | None,
        early_best_value: float | None,
        early_best_epoch: int,
        early_bad_steps: int,
        early_monitor_name: str,
        early_best_checkpoint: Path,
    ) -> dict[str, Any]:
        if not self.args.early_stop:
            return {
                "best_value": early_best_value,
                "best_epoch": early_best_epoch,
                "bad_steps": early_bad_steps,
                "stopped": False,
                "reason": None,
            }

        current_monitor_value: float | None = None
        if self.args.early_stop_mode == "loss":
            current_monitor_value = float(row["total_loss"])
        elif current_eval is not None:
            current_monitor_value = float(current_eval["val"][self.args.early_stop_metric])

        if current_monitor_value is None:
            return {
                "best_value": early_best_value,
                "best_epoch": early_best_epoch,
                "bad_steps": early_bad_steps,
                "stopped": False,
                "reason": None,
            }

        improved = False
        if early_best_value is None:
            improved = True
        elif self.args.early_stop_mode == "loss":
            improved = current_monitor_value < (early_best_value - self.args.early_stop_min_delta)
        else:
            improved = current_monitor_value > (early_best_value + self.args.early_stop_min_delta)

        if improved:
            early_best_value = current_monitor_value
            early_best_epoch = epoch
            early_bad_steps = 0
            save_student_checkpoint(
                early_best_checkpoint,
                {
                    "epoch": epoch,
                    "monitor_name": early_monitor_name,
                    "monitor_value": current_monitor_value,
                    "student_state_dict": self.model.state_dict(),
                    "optimizer_state_dict": self.optimizer.state_dict(),
                    "config": vars(self.args),
                },
            )
        else:
            early_bad_steps += 1

        stopped = False
        reason = None
        if epoch >= self.args.early_stop_warmup and early_bad_steps >= self.args.early_stop_patience:
            stopped = True
            reason = (
                f"no improvement on {early_monitor_name} for {early_bad_steps} step(s); "
                f"best={early_best_value:.6f} at epoch={early_best_epoch}"
            )
        return {
            "best_value": early_best_value,
            "best_epoch": early_best_epoch,
            "bad_steps": early_bad_steps,
            "stopped": stopped,
            "reason": reason,
        }

config = args if isinstance(args, RecDistillConfig) else None instance-attribute

args = runner_args_from_config(args) if isinstance(args, RecDistillConfig) else args instance-attribute

wandb_logger = wandb_logger instance-attribute

device = torch.device(args.device) if args.device else torch.device('cuda' if torch.cuda.is_available() else 'cpu') instance-attribute

student_backbone = normalize_backbone_name(args.student_backbone) instance-attribute

teacher_source = _teacher_source_from_args(args) instance-attribute

teacher_path = self.teacher_source.path instance-attribute

output_path = _distilled_student_path(resolve_student_checkpoint_from_args(args, distiller_name=(self.resolve_distiller_name()))) instance-attribute

run_dir = self.output_path.parent.parent if self.output_path.parent.name == 'artifacts' else self.output_path.parent instance-attribute

teacher_state = None instance-attribute

dataset = None instance-attribute

val_dict: dict[int, set[int]] = {} instance-attribute

test_dict: dict[int, set[int]] = {} instance-attribute

model = None instance-attribute

distiller = None instance-attribute

optimizer = None instance-attribute

trainer = None instance-attribute

__init__(args: Any, wandb_logger=None)

Source code in recdistill/experiment_runner.py
def __init__(self, args: Any, wandb_logger=None):
    self.config = args if isinstance(args, RecDistillConfig) else None
    self.args = runner_args_from_config(args) if isinstance(args, RecDistillConfig) else args
    self.wandb_logger = wandb_logger
    args = self.args
    self.device = torch.device(args.device) if args.device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
    self.student_backbone = normalize_backbone_name(args.student_backbone)
    self.teacher_source = _teacher_source_from_args(args)
    self.teacher_path = self.teacher_source.path
    self.output_path = _distilled_student_path(
        resolve_student_checkpoint_from_args(args, distiller_name=self.resolve_distiller_name())
    )
    self.output_path.parent.mkdir(parents=True, exist_ok=True)
    self.run_dir = self.output_path.parent.parent if self.output_path.parent.name == "artifacts" else self.output_path.parent
    (self.run_dir / "perf").mkdir(parents=True, exist_ok=True)
    (self.run_dir / "logs").mkdir(parents=True, exist_ok=True)
    (self.run_dir / "config").mkdir(parents=True, exist_ok=True)

    self.teacher_state = None
    self.dataset = None
    self.val_dict: dict[int, set[int]] = {}
    self.test_dict: dict[int, set[int]] = {}
    self.model = None
    self.distiller = None
    self.optimizer = None
    self.trainer = None

from_config(config: RecDistillConfig, wandb_logger=None) -> 'RecDistillExperimentRunner' classmethod

Source code in recdistill/experiment_runner.py
@classmethod
def from_config(cls, config: RecDistillConfig, wandb_logger=None) -> "RecDistillExperimentRunner":
    return cls(config, wandb_logger=wandb_logger)

resolve_distiller_name() -> str

Source code in recdistill/experiment_runner.py
def resolve_distiller_name(self) -> str:
    names = []
    if float(getattr(self.args, "lambda_de", 0.0)) > 0:
        names.append("DE")
    if float(getattr(self.args, "lambda_rrd", 0.0)) > 0:
        names.append("RRD")
    if float(getattr(self.args, "lambda_unkd", 0.0)) > 0:
        names.append("UnKD")
    if float(getattr(self.args, "lambda_td", 0.0)) > 0:
        names.append(str(getattr(self.args, "td_type", "TD")).upper())
    return "-".join(names) if names else "NONE"

run_config() -> dict[str, Any]

Source code in recdistill/experiment_runner.py
def run_config(self) -> dict[str, Any]:
    return {
        "config_source": "RecDistillConfig" if self.config is not None else "args",
        "dataset": self.args.dataset,
        "teacher_model": self.args.teacher_model,
        "teacher_path": str(self.teacher_path) if self.teacher_path is not None else None,
        "teacher_framework": getattr(self.args, "teacher_framework", "auto"),
        "teacher_format": getattr(self.args, "teacher_format", "auto"),
        "teacher_embedding_dim": self.args.teacher_embedding_dim,
        "student_backbone": self.student_backbone,
        "student_framework": self.args.student_framework,
        "student_embedding_dim": self.args.student_embedding_dim,
        "lightgcn_layers": self.args.lightgcn_layers,
        "neumf_mlp_dims": self.args.neumf_mlp_dims,
        "neumf_dropout": self.args.neumf_dropout,
        "epochs": self.args.epochs,
        "batch_size": self.args.batch_size,
        "learning_rate": self.args.learning_rate,
        "l2_reg": self.args.l2_reg,
        "lambda_de": self.args.lambda_de,
        "num_experts": self.args.num_experts,
        "temperature": self.args.temperature,
        "lambda_rrd": self.args.lambda_rrd,
        "rrd_interesting_size": self.args.rrd_interesting_size,
        "rrd_uninteresting_size": self.args.rrd_uninteresting_size,
        "rrd_temperature": self.args.rrd_temperature,
        "rrd_teacher_topk": self.args.rrd_teacher_topk,
        "lambda_unkd": self.args.lambda_unkd,
        "unkd_sample_num": self.args.unkd_sample_num,
        "unkd_group_count": self.args.unkd_group_count,
        "unkd_popularity_lambda": self.args.unkd_popularity_lambda,
        "unkd_rank_top_k": self.args.unkd_rank_top_k,
        "unkd_rank_temperature": self.args.unkd_rank_temperature,
        "lambda_td": self.args.lambda_td,
        "td_type": self.args.td_type,
        "htd_alpha": self.args.htd_alpha,
        "htd_num_groups": self.args.htd_num_groups,
        "htd_topology_mode": self.args.htd_topology_mode,
        "htd_initial_tau": self.args.htd_initial_tau,
        "htd_min_tau": self.args.htd_min_tau,
        "htd_decay_epochs": self.args.htd_decay_epochs,
        "td_entity_sample_size": self.args.td_entity_sample_size,
        "seed": self.args.seed,
        "eval_enabled": not self.args.skip_eval,
        "eval_k": self.args.eval_k,
        "eval_every": self.args.eval_every,
        "selection_split": self.args.selection_split,
        "selection_metric": self.args.selection_metric,
        "assert_no_train_leak": self.args.assert_no_train_leak,
    }

prepare() -> None

Source code in recdistill/experiment_runner.py
def prepare(self) -> None:
    print("\n" + "=" * 80)
    print("Student Distillation Training")
    print("=" * 80)
    print(f"Dataset: {self.args.dataset}")
    print(f"Teacher source: {self.teacher_path or self.teacher_source.format}")
    print(f"Student backbone: {self.student_backbone}")
    print(f"Student framework: {self.args.student_framework}")
    print(f"Device: {self.device}")
    print("=" * 80 + "\n")

    teacher_state = load_teacher(self.teacher_source, device="cpu")
    validate_loaded_teacher_for_distillation(teacher_state, self.resolve_distiller_name())
    print(f"Teacher users/items: {teacher_state.num_users}/{teacher_state.num_items}")
    print(f"Teacher embedding dim: {teacher_state.embedding_dim if teacher_state.has_embeddings else 'none'}")
    print(f"Teacher exact scorer: {teacher_state.scorer is not None}")
    teacher_embedding_source = teacher_state.metadata.get("embedding_source")
    if teacher_embedding_source:
        print(f"Teacher embedding source: {teacher_embedding_source}")
    teacher_representation = teacher_state.metadata.get("representation")
    if teacher_representation:
        print(f"Teacher embedding representation: {teacher_representation}")

    self.teacher_state = teacher_state
    user_mapping, item_mapping, mapping_source = resolve_teacher_dataset_mappings(
        teacher_state.metadata,
        dataset_name=self.args.dataset,
    )
    split_id_space = "dataset_integer" if mapping_source == "dataset_integer" else None
    print(f"Dataset mapping source: {mapping_source}")
    self.dataset, dropped = load_train_dataset(
        dataset_name=self.args.dataset,
        teacher_num_users=teacher_state.num_users,
        teacher_num_items=teacher_state.num_items,
        user_mapping=user_mapping,
        item_mapping=item_mapping,
        id_space=split_id_space,
    )
    print(f"Train interactions: {len(self.dataset.interactions)}")
    print(f"Dropped interactions (out of teacher range): {dropped}")

    if not self.args.skip_eval:
        self.val_dict, dropped_val = load_eval_split(
            dataset_name=self.args.dataset,
            split_name="val",
            teacher_num_users=teacher_state.num_users,
            teacher_num_items=teacher_state.num_items,
            user_mapping=user_mapping,
            item_mapping=item_mapping,
            id_space=split_id_space,
        )
        self.test_dict, dropped_test = load_eval_split(
            dataset_name=self.args.dataset,
            split_name="test",
            teacher_num_users=teacher_state.num_users,
            teacher_num_items=teacher_state.num_items,
            user_mapping=user_mapping,
            item_mapping=item_mapping,
            id_space=split_id_space,
        )
        print(f"Validation interactions: {sum(len(v) for v in self.val_dict.values())} (dropped: {dropped_val})")
        print(f"Test interactions: {sum(len(v) for v in self.test_dict.values())} (dropped: {dropped_test})")

    train_loader = build_train_loader(self.dataset, batch_size=self.args.batch_size, num_workers=self.args.num_workers)
    self.model = build_student_model(
        backbone=self.student_backbone,
        dataset=self.dataset,
        embedding_dim=self.args.student_embedding_dim,
        l2_reg=self.args.l2_reg,
        lightgcn_layers=self.args.lightgcn_layers,
        neumf_mlp_dims=self.args.neumf_mlp_dims,
        neumf_dropout=self.args.neumf_dropout,
        framework=self.args.student_framework,
        graph_builder=build_lightgcn_graph,
    ).to(self.device)
    self.distiller = build_distiller_from_args(
        args=self.args,
        teacher_state=teacher_state,
        student_dim=self.args.student_embedding_dim,
    )
    teacher_state_for_distiller = teacher_state.to(self.device)
    if self.distiller is not None:
        self.distiller = self.distiller.to(self.device)
        self.distiller.on_train_start(teacher_state_for_distiller, self.dataset)
        prepare_distiller_trainable_modules(self.distiller, int(self.args.student_embedding_dim), self.device)
        setattr(self.distiller, "_recdistill_initialized", True)

    trainable_params = list(self.model.parameters())
    if self.distiller is not None:
        trainable_params += list(self.distiller.parameters())
    self.optimizer = torch.optim.Adam(trainable_params, lr=self.args.learning_rate)
    self.trainer = DistillationTrainer(
        model=self.model,
        optimizer=self.optimizer,
        train_loader=train_loader,
        distiller=self.distiller,
        device=self.device,
        teacher_state=teacher_state,
        dataset=self.dataset,
    )

    if not self.args.skip_eval:
        scorer_note = "exact scorer" if teacher_state.scorer is not None else "embedding dot product"
        teacher_eval = evaluate_embeddings(
            user_embeddings=teacher_state.user_embeddings,
            item_embeddings=teacher_state.item_embeddings,
            train_seen=self.dataset.train_dict,
            ground_truth=self.val_dict,
            top_k=self.args.eval_k,
            batch_size=self.args.eval_batch_size,
            device=self.device,
            scorer=teacher_state.scorer,
        )[0]
        print(
            f"Teacher baseline @ {self.args.eval_k} (val, {scorer_note}): "
            f"P={teacher_eval['precision']:.4f} "
            f"R={teacher_eval['recall']:.4f} "
            f"NDCG={teacher_eval['ndcg']:.4f} "
            f"HR={teacher_eval['hr']:.4f}"
        )

run() -> dict[str, Any]

Source code in recdistill/experiment_runner.py
def run(self) -> dict[str, Any]:
    set_seed(int(self.args.seed))
    self.prepare()
    return self.train()

train() -> dict[str, Any]

Source code in recdistill/experiment_runner.py
def train(self) -> dict[str, Any]:
    args = self.args
    assert self.teacher_state is not None
    assert self.dataset is not None
    assert self.model is not None
    assert self.optimizer is not None
    assert self.trainer is not None

    start_payload = {
        "status": "running",
        "started_at_utc": utc_now_iso(),
        **self.run_config(),
        "teacher_embedding_dim": int(self.teacher_state.embedding_dim) if self.teacher_state.has_embeddings else None,
    }
    if self.wandb_logger is not None:
        self.wandb_logger.log_start(start_payload)

    history: list[dict[str, float | int]] = []
    best_score = float("-inf")
    best_epoch = 0
    best_checkpoint = best_checkpoint_path(self.output_path)
    saved_best_checkpoint = False
    early_best_value: float | None = None
    early_best_epoch = 0
    early_bad_steps = 0
    early_stopped = False
    early_stop_reason: str | None = None
    early_monitor_name = "total_loss" if args.early_stop_mode == "loss" else f"val_{args.early_stop_metric}"
    early_best_checkpoint = self.output_path.with_name(f"{self.output_path.stem}.earlystop_best{DISTILLED_STUDENT_EXT}")

    run_status = "completed"
    run_error: str | None = None
    caught_exception: Exception | None = None
    final_test_eval: dict[str, Any] | None = None
    try:
        for epoch in range(1, args.epochs + 1):
            metrics = self.trainer.train_epoch()
            row = {"epoch": epoch, **metrics}
            current_eval: dict[str, dict[str, float] | int] | None = None
            if not args.skip_eval and args.eval_every > 0 and (epoch % args.eval_every == 0):
                current_eval = evaluate_student(
                    model=self.model,
                    train_seen=self.dataset.train_dict,
                    val_gt=self.val_dict,
                    test_gt=self.test_dict,
                    top_k=args.eval_k,
                    batch_size=args.eval_batch_size,
                    device=self.device,
                    eval_val_only=args.eval_val_only,
                )
                self._update_eval_row(row, current_eval)
                leaked_users_test = int(current_eval.get("leaked_users_test", 0))
                if args.assert_no_train_leak and (current_eval["leaked_users_val"] > 0 or leaked_users_test > 0):
                    raise RuntimeError(
                        "Train-item leakage detected in recommendations. "
                        f"val_leaks={current_eval['leaked_users_val']} test_leaks={leaked_users_test}"
                    )

                selected_split_metrics = current_eval[args.selection_split]
                selected_score = float(selected_split_metrics[args.selection_metric])
                row["selection_score"] = selected_score
                if selected_score > best_score:
                    best_score = selected_score
                    best_epoch = epoch
                    self._save_checkpoint(best_checkpoint, epoch, history + [row], best_epoch, best_score)
                    saved_best_checkpoint = True

            history.append(row)
            if self.wandb_logger is not None:
                self.wandb_logger.log_epoch(row)
            self._print_epoch(epoch, metrics, current_eval)

            if args.save_every > 0 and (epoch % args.save_every == 0):
                periodic_path = self.output_path.with_name(f"{self.output_path.stem}.ep{epoch}{DISTILLED_STUDENT_EXT}")
                self._save_checkpoint(periodic_path, epoch, history, best_epoch, best_score if best_epoch > 0 else None)
                print(f"Saved periodic checkpoint: {periodic_path}")

            early_state = self._maybe_early_stop(
                epoch=epoch,
                row=row,
                current_eval=current_eval,
                early_best_value=early_best_value,
                early_best_epoch=early_best_epoch,
                early_bad_steps=early_bad_steps,
                early_monitor_name=early_monitor_name,
                early_best_checkpoint=early_best_checkpoint,
            )
            early_best_value = early_state["best_value"]
            early_best_epoch = early_state["best_epoch"]
            early_bad_steps = early_state["bad_steps"]
            if early_state["stopped"]:
                early_stopped = True
                early_stop_reason = early_state["reason"]
                print(f"Early stopping triggered at epoch {epoch}: {early_stop_reason}")
                break
    except Exception as exc:
        run_status = "failed"
        run_error = str(exc)
        caught_exception = exc

    if (
        caught_exception is None
        and args.early_stop
        and args.early_stop_restore_best
        and early_best_epoch > 0
        and early_best_checkpoint.exists()
    ):
        payload = load_student_checkpoint(early_best_checkpoint, map_location=self.device)
        self.model.load_state_dict(payload["student_state_dict"])
        print(
            f"Restored early-stop best checkpoint from epoch {payload['epoch']} "
            f"({payload['monitor_name']}={payload['monitor_value']:.6f})"
        )

    if caught_exception is None and not args.skip_eval and args.eval_val_only and len(self.test_dict) > 0:
        final_test_eval = evaluate_student(
            model=self.model,
            train_seen=self.dataset.train_dict,
            val_gt=self.val_dict,
            test_gt=self.test_dict,
            top_k=args.eval_k,
            batch_size=args.eval_batch_size,
            device=self.device,
            eval_val_only=False,
        )
        print(
            f"Final Test@{args.eval_k}: "
            f"P={final_test_eval['test']['precision']:.4f} "
            f"R={final_test_eval['test']['recall']:.4f} "
            f"NDCG={final_test_eval['test']['ndcg']:.4f} "
            f"HR={final_test_eval['test']['hr']:.4f} "
            f"| leaks={final_test_eval['leaked_users_test']}"
        )

    history_path = self.run_dir / "logs" / f"{self.output_path.stem}.history.json"
    should_save_final = caught_exception is None and (
        not saved_best_checkpoint or (args.early_stop and args.early_stop_restore_best and early_best_epoch > 0)
    )
    if should_save_final:
        final_epoch = int(history[-1]["epoch"]) if history else 0
        self._save_checkpoint(
            self.output_path,
            final_epoch,
            history,
            best_epoch,
            best_score if best_epoch > 0 else None,
            extra={
                "early_stopped": early_stopped,
                "early_stop_reason": early_stop_reason,
                "early_best_epoch": early_best_epoch if early_best_epoch > 0 else None,
                "early_best_value": early_best_value,
                "early_monitor_name": early_monitor_name if args.early_stop else None,
                "final_test_eval": final_test_eval,
            },
        )
    if caught_exception is None:
        history_path.write_text(json.dumps(history, indent=2), encoding="utf-8")

    end_payload = {
        "status": run_status,
        "ended_at_utc": utc_now_iso(),
        "best_epoch": int(best_epoch),
        "best_selection_score": float(best_score) if best_epoch > 0 else None,
        "best_checkpoint": str(best_checkpoint) if best_epoch > 0 else None,
        "final_checkpoint": str(self.output_path) if caught_exception is None else None,
        "history_file": str(history_path) if history_path.exists() else None,
        "early_stopped": early_stopped,
        "early_stop_reason": early_stop_reason,
        "early_best_epoch": early_best_epoch if early_best_epoch > 0 else None,
        "early_best_value": early_best_value,
        "early_monitor_name": early_monitor_name if args.early_stop else None,
        "final_test_eval": final_test_eval,
        "error": run_error,
    }
    if self.wandb_logger is not None:
        self.wandb_logger.log_end(end_payload)
    if caught_exception is not None:
        raise caught_exception

    print("\nTraining complete.")
    print(f"Student checkpoint: {self.output_path}")
    if best_epoch > 0:
        print(
            f"Best checkpoint ({args.selection_split}.{args.selection_metric}): "
            f"epoch={best_epoch} score={best_score:.6f} path={best_checkpoint}"
        )
    if final_test_eval is not None:
        print(
            f"Final test metrics: "
            f"NDCG={final_test_eval['test']['ndcg']:.4f} "
            f"HR={final_test_eval['test']['hr']:.4f}"
        )
    print(f"History JSON: {history_path}\n")
    return end_payload

runner_args_from_config(config: RecDistillConfig) -> SimpleNamespace

Source code in recdistill/experiment_runner.py
def runner_args_from_config(config: RecDistillConfig) -> SimpleNamespace:
    train = config.distill_student
    teacher = train.teacher
    student = train.student
    distillation = train.distillation
    optimization = train.optimization
    runtime = train.runtime
    evaluation = train.evaluation
    early = optimization.early_stopping

    topology = _dict_section(distillation, "topology")
    rrd = _dict_section(distillation, "rrd")
    unkd = _dict_section(distillation, "unkd")
    wandb = runtime.wandb if isinstance(runtime.wandb, dict) else {}

    return SimpleNamespace(
        dataset=train.dataset,
        teacher_model=teacher.model,
        teacher_embedding_dim=teacher.embedding_dim,
        teacher_path=teacher.path,
        teacher_framework=getattr(teacher, "framework", "auto"),
        teacher_format=getattr(teacher, "format", "auto"),
        student_backbone=student.backbone,
        student_framework=getattr(student, "framework", "recbole"),
        student_embedding_dim=student.embedding_dim,
        lightgcn_layers=getattr(student, "num_layers", getattr(student, "lightgcn_layers", 2)),
        neumf_mlp_dims=getattr(student, "mlp_hidden_size", getattr(student, "mlp_dims", "64,32,16,8")),
        neumf_dropout=getattr(student, "dropout", 0.0),
        epochs=optimization.epochs,
        batch_size=optimization.batch_size,
        learning_rate=optimization.learning_rate,
        l2_reg=optimization.l2_reg,
        lambda_de=getattr(distillation, "lambda_de", 0.0),
        num_experts=getattr(distillation, "num_experts", getattr(student, "num_experts", 10)),
        temperature=getattr(distillation, "temperature", getattr(student, "temperature", 1.0)),
        lambda_rrd=getattr(distillation, "lambda_rrd", 0.0),
        rrd_interesting_size=rrd.get("interesting_size", getattr(student, "rrd_interesting_size", 10)),
        rrd_uninteresting_size=rrd.get("uninteresting_size", getattr(student, "rrd_uninteresting_size", 50)),
        rrd_temperature=rrd.get("temperature", getattr(student, "rrd_temperature", 1.0)),
        rrd_teacher_topk=rrd.get("teacher_topk", getattr(student, "rrd_teacher_topk", 500)),
        lambda_unkd=getattr(distillation, "lambda_unkd", 0.0),
        unkd_sample_num=unkd.get("sample_num", getattr(student, "unkd_sample_num", 30)),
        unkd_group_count=unkd.get("group_count", getattr(student, "unkd_group_count", 2)),
        unkd_popularity_lambda=unkd.get("popularity_lambda", getattr(student, "unkd_popularity_lambda", 1.0)),
        unkd_rank_top_k=unkd.get("rank_top_k", getattr(student, "unkd_rank_top_k", 1000)),
        unkd_rank_temperature=unkd.get("rank_temperature", getattr(student, "unkd_rank_temperature", 20.0)),
        lambda_td=topology.get("lambda_td", getattr(distillation, "lambda_td", 0.0)),
        td_type=str(topology.get("type", getattr(distillation, "strategy", "HTD"))).upper(),
        td_entity_sample_size=topology.get("entity_sample_size", getattr(student, "td_entity_sample_size", 0)),
        htd_alpha=topology.get("alpha", getattr(student, "htd_alpha", 0.5)),
        htd_num_groups=topology.get("num_groups", getattr(student, "htd_num_groups", 40)),
        htd_topology_mode=topology.get("topology_mode", getattr(student, "htd_topology_mode", "group_pe")),
        htd_initial_tau=topology.get("initial_tau", getattr(student, "htd_initial_tau", 1.0)),
        htd_min_tau=topology.get("min_tau", getattr(student, "htd_min_tau", 1e-10)),
        htd_decay_epochs=topology.get("decay_epochs", getattr(student, "htd_decay_epochs", 100)),
        seed=runtime.seed,
        device=runtime.device,
        num_workers=runtime.num_workers,
        output_path=runtime.output_path,
        output_strategy=getattr(runtime, "output_strategy", "fixed"),
        save_every=runtime.save_every,
        skip_eval=not evaluation.enabled,
        eval_k=evaluation.k,
        eval_every=evaluation.every,
        eval_batch_size=evaluation.batch_size,
        eval_val_only=evaluation.val_only,
        selection_split=evaluation.selection_split,
        selection_metric=evaluation.selection_metric,
        assert_no_train_leak=evaluation.assert_no_train_leak,
        early_stop=bool(early.enabled) if early is not None else False,
        early_stop_mode=early.mode if early is not None else "loss",
        early_stop_metric=early.metric if early is not None else "ndcg",
        early_stop_patience=early.patience if early is not None else 5,
        early_stop_min_delta=early.min_delta if early is not None else 0.0,
        early_stop_warmup=getattr(early, "warmup", 0) if early is not None else 0,
        early_stop_restore_best=getattr(early, "restore_best", False) if early is not None else False,
        wandb_log=bool(wandb.get("enabled", False)),
        wandb_project=wandb.get("project"),
        wandb_entity=wandb.get("entity"),
        wandb_run_name=wandb.get("run_name"),
        wandb_tags=",".join(str(tag) for tag in wandb.get("tags", [])) if isinstance(wandb.get("tags"), list) else wandb.get("tags"),
        wandb_group=wandb.get("group"),
        wandb_notes=wandb.get("notes"),
    )

NativeTrainingArgs dataclass

Source code in recdistill/native_runner.py
@dataclass
class NativeTrainingArgs:
    role: str
    dataset: str
    backbone: str
    embedding_dim: int
    framework: str = "recbole"
    epochs: int = 100
    batch_size: int = 512
    learning_rate: float = 0.001
    l2_reg: float = 0.0001
    dropout: float = 0.0
    lightgcn_layers: int = 2
    neumf_mlp_dims: str = "64,32,16,8"
    seed: int = 42
    device: str | None = None
    num_workers: int = 0
    output_path: str | None = None
    save_every: int = 0
    skip_eval: bool = False
    eval_k: int = 20
    eval_every: int = 5
    eval_batch_size: int = 1024
    eval_val_only: bool = True
    selection_split: str = "val"
    selection_metric: str = "ndcg"
    assert_no_train_leak: bool = True
    early_stop: bool = False
    early_stop_mode: str = "val_metric"
    early_stop_metric: str = "ndcg"
    early_stop_patience: int = 10
    early_stop_min_delta: float = 0.0
    early_stop_warmup: int = 0
    early_stop_restore_best: bool = False
    config_path: str | None = None

role: str instance-attribute

dataset: str instance-attribute

backbone: str instance-attribute

embedding_dim: int instance-attribute

framework: str = 'recbole' class-attribute instance-attribute

epochs: int = 100 class-attribute instance-attribute

batch_size: int = 512 class-attribute instance-attribute

learning_rate: float = 0.001 class-attribute instance-attribute

l2_reg: float = 0.0001 class-attribute instance-attribute

dropout: float = 0.0 class-attribute instance-attribute

lightgcn_layers: int = 2 class-attribute instance-attribute

neumf_mlp_dims: str = '64,32,16,8' class-attribute instance-attribute

seed: int = 42 class-attribute instance-attribute

device: str | None = None class-attribute instance-attribute

num_workers: int = 0 class-attribute instance-attribute

output_path: str | None = None class-attribute instance-attribute

save_every: int = 0 class-attribute instance-attribute

skip_eval: bool = False class-attribute instance-attribute

eval_k: int = 20 class-attribute instance-attribute

eval_every: int = 5 class-attribute instance-attribute

eval_batch_size: int = 1024 class-attribute instance-attribute

eval_val_only: bool = True class-attribute instance-attribute

selection_split: str = 'val' class-attribute instance-attribute

selection_metric: str = 'ndcg' class-attribute instance-attribute

assert_no_train_leak: bool = True class-attribute instance-attribute

early_stop: bool = False class-attribute instance-attribute

early_stop_mode: str = 'val_metric' class-attribute instance-attribute

early_stop_metric: str = 'ndcg' class-attribute instance-attribute

early_stop_patience: int = 10 class-attribute instance-attribute

early_stop_min_delta: float = 0.0 class-attribute instance-attribute

early_stop_warmup: int = 0 class-attribute instance-attribute

early_stop_restore_best: bool = False class-attribute instance-attribute

config_path: str | None = None class-attribute instance-attribute

__init__(role: str, dataset: str, backbone: str, embedding_dim: int, framework: str = 'recbole', epochs: int = 100, batch_size: int = 512, learning_rate: float = 0.001, l2_reg: float = 0.0001, dropout: float = 0.0, lightgcn_layers: int = 2, neumf_mlp_dims: str = '64,32,16,8', seed: int = 42, device: str | None = None, num_workers: int = 0, output_path: str | None = None, save_every: int = 0, skip_eval: bool = False, eval_k: int = 20, eval_every: int = 5, eval_batch_size: int = 1024, eval_val_only: bool = True, selection_split: str = 'val', selection_metric: str = 'ndcg', assert_no_train_leak: bool = True, early_stop: bool = False, early_stop_mode: str = 'val_metric', early_stop_metric: str = 'ndcg', early_stop_patience: int = 10, early_stop_min_delta: float = 0.0, early_stop_warmup: int = 0, early_stop_restore_best: bool = False, config_path: str | None = None) -> None

NativeModelTrainingRunner

Source code in recdistill/native_runner.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
class NativeModelTrainingRunner:
    def __init__(self, args: NativeTrainingArgs):
        self.args = args
        self.role = _normalize_role(args.role)
        self.device = torch.device(args.device) if args.device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.backbone = normalize_backbone_name(args.backbone)
        self.output_path = Path(args.output_path) if args.output_path else self._default_output_path()
        self.output_path.parent.mkdir(parents=True, exist_ok=True)
        self.run_dir = self.output_path.parent.parent if self.output_path.parent.name == "artifacts" else self.output_path.parent
        (self.run_dir / "logs").mkdir(parents=True, exist_ok=True)
        (self.run_dir / "config").mkdir(parents=True, exist_ok=True)
        if args.config_path:
            source = Path(args.config_path)
            if source.exists():
                (self.run_dir / "config" / source.name).write_text(source.read_text(encoding="utf-8"), encoding="utf-8")

        self.dataset = None
        self.val_dict: dict[int, set[int]] = {}
        self.test_dict: dict[int, set[int]] = {}
        self.model = None
        self.optimizer = None
        self.trainer = None

    def run_config(self) -> dict[str, Any]:
        payload = asdict(self.args)
        payload["role"] = self.role
        payload["backbone"] = self.backbone
        payload["framework"] = self.args.framework
        payload["output_path"] = str(self.output_path)
        return payload

    def prepare(self) -> None:
        print("\n" + "=" * 80)
        print(f"{self.role.capitalize()} Training")
        print("=" * 80)
        print(f"Dataset: {self.args.dataset}")
        print(f"Backbone: {self.backbone}")
        print(f"Framework: {self.args.framework}")
        print(f"Embedding dim: {self.args.embedding_dim}")
        print(f"Device: {self.device}")
        print("=" * 80 + "\n")

        self.dataset = load_interaction_dataset(self.args.dataset)
        print(f"Train interactions: {len(self.dataset.interactions)}")
        print(f"Users/items: {self.dataset.num_users}/{self.dataset.num_items}")

        if not self.args.skip_eval:
            self.val_dict, dropped_val = load_eval_split(
                dataset_name=self.args.dataset,
                split_name="val",
                teacher_num_users=self.dataset.num_users,
                teacher_num_items=self.dataset.num_items,
            )
            self.test_dict, dropped_test = load_eval_split(
                dataset_name=self.args.dataset,
                split_name="test",
                teacher_num_users=self.dataset.num_users,
                teacher_num_items=self.dataset.num_items,
            )
            print(f"Validation interactions: {sum(len(v) for v in self.val_dict.values())} (dropped: {dropped_val})")
            print(f"Test interactions: {sum(len(v) for v in self.test_dict.values())} (dropped: {dropped_test})")

        train_loader = build_train_loader(
            self.dataset,
            batch_size=int(self.args.batch_size),
            num_workers=int(self.args.num_workers),
        )
        self.model = build_student_model(
            backbone=self.backbone,
            dataset=self.dataset,
            embedding_dim=int(self.args.embedding_dim),
            l2_reg=float(self.args.l2_reg),
            lightgcn_layers=int(self.args.lightgcn_layers),
            neumf_mlp_dims=parse_mlp_dims(self.args.neumf_mlp_dims),
            neumf_dropout=float(self.args.dropout),
            framework=self.args.framework,
            graph_builder=build_lightgcn_graph,
        ).to(self.device)
        self.optimizer = torch.optim.Adam(self.model.parameters(), lr=float(self.args.learning_rate))
        self.trainer = DistillationTrainer(
            model=self.model,
            optimizer=self.optimizer,
            train_loader=train_loader,
            distiller=None,
            device=self.device,
            dataset=self.dataset,
        )

    def run(self) -> dict[str, Any]:
        set_seed(int(self.args.seed))
        self.prepare()
        return self.train()

    def train(self) -> dict[str, Any]:
        assert self.dataset is not None
        assert self.model is not None
        assert self.optimizer is not None
        assert self.trainer is not None

        history: list[dict[str, Any]] = []
        best_score = float("-inf")
        best_epoch = 0
        best_artifact = best_checkpoint_path(self.output_path)
        early_best_value = float("inf") if self.args.early_stop_mode == "loss" else float("-inf")
        early_best_epoch = 0
        early_bad_steps = 0
        early_stopped = False
        early_stop_reason: str | None = None
        early_monitor_name = "total_loss" if self.args.early_stop_mode == "loss" else f"val_{self.args.early_stop_metric}"
        early_best_artifact = _with_role_suffix(
            self.output_path,
            f".earlystop_best{TEACHER_EXT if self.role == 'teacher' else STUDENT_EXT}",
        )

        for epoch in range(1, int(self.args.epochs) + 1):
            metrics = self.trainer.train_epoch()
            row: dict[str, Any] = {"epoch": epoch, **metrics}
            current_eval = None
            if not self.args.skip_eval and self.args.eval_every > 0 and epoch % int(self.args.eval_every) == 0:
                current_eval = evaluate_student(
                    model=self.model,
                    train_seen=self.dataset.train_dict,
                    val_gt=self.val_dict,
                    test_gt=self.test_dict,
                    top_k=int(self.args.eval_k),
                    batch_size=int(self.args.eval_batch_size),
                    device=self.device,
                    eval_val_only=bool(self.args.eval_val_only),
                )
                self._update_eval_row(row, current_eval)
                leaked_users_test = int(current_eval.get("leaked_users_test", 0))
                if self.args.assert_no_train_leak and (current_eval["leaked_users_val"] > 0 or leaked_users_test > 0):
                    raise RuntimeError(
                        "Train-item leakage detected in recommendations. "
                        f"val_leaks={current_eval['leaked_users_val']} test_leaks={leaked_users_test}"
                    )

                selected_metrics = current_eval[self.args.selection_split]
                selected_score = float(selected_metrics[self.args.selection_metric])
                row["selection_score"] = selected_score
                if selected_score > best_score:
                    best_score = selected_score
                    best_epoch = epoch
                    self._save_artifact(best_artifact, epoch, history + [row], best_epoch, best_score)

            history.append(row)
            self._print_epoch(epoch, metrics, current_eval)

            early_state = self._maybe_early_stop(
                epoch=epoch,
                row=row,
                current_eval=current_eval,
                early_best_value=early_best_value,
                early_best_epoch=early_best_epoch,
                early_bad_steps=early_bad_steps,
                early_monitor_name=early_monitor_name,
            )
            early_best_value = early_state["best_value"]
            early_best_epoch = early_state["best_epoch"]
            early_bad_steps = early_state["bad_steps"]
            row["early_monitor_name"] = early_monitor_name if self.args.early_stop else None
            row["early_monitor_value"] = early_state["current_value"]
            row["early_bad_steps"] = early_bad_steps if self.args.early_stop else None
            if self.args.early_stop and early_state["improved"] and self.args.early_stop_restore_best:
                self._save_artifact(
                    early_best_artifact,
                    epoch,
                    history,
                    best_epoch,
                    best_score if best_epoch > 0 else None,
                    extra={
                        "early_monitor_name": early_monitor_name,
                        "early_best_epoch": early_best_epoch,
                        "early_best_value": early_best_value,
                    },
                )
            if early_state["stopped"]:
                early_stopped = True
                early_stop_reason = early_state["reason"]
                print(f"Early stopping triggered at epoch {epoch}: {early_stop_reason}")
                break

            if self.args.save_every > 0 and epoch % int(self.args.save_every) == 0:
                periodic = _with_role_suffix(
                    self.output_path,
                    f".ep{epoch}{TEACHER_EXT if self.role == 'teacher' else STUDENT_EXT}",
                )
                self._save_artifact(periodic, epoch, history, best_epoch, best_score if best_epoch > 0 else None)

        final_epoch = int(history[-1]["epoch"]) if history else 0
        self._save_artifact(
            self.output_path,
            final_epoch,
            history,
            best_epoch,
            best_score if best_epoch > 0 else None,
            extra={
                "early_stopped": early_stopped,
                "early_stop_reason": early_stop_reason,
                "early_best_epoch": early_best_epoch if self.args.early_stop else 0,
                "early_best_value": early_best_value if self.args.early_stop and early_best_epoch > 0 else None,
                "early_monitor_name": early_monitor_name if self.args.early_stop else None,
            },
        )
        history_path = self.run_dir / "logs" / f"{self.output_path.stem}.history.json"
        history_path.write_text(json.dumps(history, indent=2), encoding="utf-8")

        result = {
            "status": "completed",
            "ended_at_utc": utc_now_iso(),
            "role": self.role,
            "dataset": self.args.dataset,
            "backbone": self.backbone,
            "output_path": str(self.output_path),
            "history_path": str(history_path),
            "best_epoch": best_epoch,
            "best_selection_score": best_score if best_epoch > 0 else None,
            "best_path": str(best_artifact) if best_epoch > 0 else None,
            "early_stopped": early_stopped,
            "early_stop_reason": early_stop_reason,
            "early_best_epoch": early_best_epoch if self.args.early_stop else 0,
            "early_best_value": early_best_value if self.args.early_stop and early_best_epoch > 0 else None,
            "early_monitor_name": early_monitor_name if self.args.early_stop else None,
        }
        print("\nTraining complete.")
        print(f"{self.role.capitalize()} artifact: {self.output_path}")
        if best_epoch > 0:
            print(f"Best artifact: {best_artifact} (epoch={best_epoch}, score={best_score:.6f})")
        print(f"History JSON: {history_path}\n")
        return result

    def _save_artifact(
        self,
        path: Path,
        epoch: int,
        history: list[dict[str, Any]],
        best_epoch: int,
        best_score: float | None,
        extra: dict[str, Any] | None = None,
    ) -> None:
        assert self.dataset is not None
        assert self.model is not None
        assert self.optimizer is not None

        if self.role == "teacher":
            scorer = self._build_teacher_scorer()
            state = TeacherState(
                user_embeddings=self.model.get_all_user_embeddings().detach().cpu(),
                item_embeddings=self.model.get_all_item_embeddings().detach().cpu(),
                scorer=scorer,
                metadata={
                    "source": "recdistill_native_training",
                    "dataset": self.args.dataset,
                    "model_name": self.backbone,
                    "score_representation": "exact_scorer" if scorer is not None else "embedding_dot_product",
                    "embedding_dim": int(self.args.embedding_dim),
                    "epoch": int(epoch),
                    "best_epoch": int(best_epoch),
                    "best_selection_score": best_score,
                    "config": self.run_config(),
                    "history": history,
                    **(extra or {}),
                },
            )
            save_teacher_state(path, state, framework="recdistill", model_name=self.backbone)
            return

        payload = {
            "epoch": int(epoch),
            "student_state_dict": self.model.state_dict(),
            "optimizer_state_dict": self.optimizer.state_dict(),
            "history": history,
            "config": self.run_config(),
            "num_users": int(self.dataset.num_users),
            "num_items": int(self.dataset.num_items),
            "best_epoch": int(best_epoch),
            "best_selection_score": best_score,
        }
        payload.update(extra or {})
        save_student_checkpoint(path, payload)

    def _build_teacher_scorer(self) -> PrecomputedScoresScorer | None:
        assert self.dataset is not None
        assert self.model is not None
        if self.backbone != "NMF" or not hasattr(self.model, "score_items_for_user"):
            return None

        self.model.eval()
        rows: list[torch.Tensor] = []
        with torch.no_grad():
            for start in range(0, int(self.dataset.num_users), int(self.args.eval_batch_size)):
                stop = min(start + int(self.args.eval_batch_size), int(self.dataset.num_users))
                batch_rows = [
                    self.model.score_items_for_user(user=user, num_items=int(self.dataset.num_items)).detach().cpu()
                    for user in range(start, stop)
                ]
                rows.append(torch.stack(batch_rows, dim=0))
        return PrecomputedScoresScorer(scores=torch.cat(rows, dim=0))

    def _default_output_path(self) -> Path:
        experiment_id = new_experiment_id()
        filename = experiment_artifact_filename(
            kind=self.role,
            experiment_id=experiment_id,
            framework=self.args.framework,
            model=self.backbone,
            dataset=self.args.dataset,
        )
        return experiment_artifact_path(
            kind=self.role,
            experiment_id=experiment_id,
            framework=self.args.framework,
            model=self.backbone,
            dataset=self.args.dataset,
            filename=filename,
        )

    def _update_eval_row(self, row: dict[str, Any], current_eval: dict[str, Any]) -> None:
        row["val_precision"] = float(current_eval["val"]["precision"])
        row["val_recall"] = float(current_eval["val"]["recall"])
        row["val_ndcg"] = float(current_eval["val"]["ndcg"])
        row["val_hr"] = float(current_eval["val"]["hr"])
        row["leaked_users_val"] = int(current_eval["leaked_users_val"])
        if not self.args.eval_val_only:
            row["test_precision"] = float(current_eval["test"]["precision"])
            row["test_recall"] = float(current_eval["test"]["recall"])
            row["test_ndcg"] = float(current_eval["test"]["ndcg"])
            row["test_hr"] = float(current_eval["test"]["hr"])
            row["leaked_users_test"] = int(current_eval["leaked_users_test"])

    def _maybe_early_stop(
        self,
        *,
        epoch: int,
        row: dict[str, Any],
        current_eval: dict[str, Any] | None,
        early_best_value: float,
        early_best_epoch: int,
        early_bad_steps: int,
        early_monitor_name: str,
    ) -> dict[str, Any]:
        if not self.args.early_stop:
            return {
                "best_value": early_best_value,
                "best_epoch": early_best_epoch,
                "bad_steps": early_bad_steps,
                "current_value": None,
                "improved": False,
                "stopped": False,
                "reason": None,
            }

        mode = str(self.args.early_stop_mode).lower()
        if mode == "loss":
            current_monitor_value = float(row.get("total_loss", row.get("base_loss")))
        elif mode == "val_metric":
            if current_eval is None:
                return {
                    "best_value": early_best_value,
                    "best_epoch": early_best_epoch,
                    "bad_steps": early_bad_steps,
                    "current_value": None,
                    "improved": False,
                    "stopped": False,
                    "reason": None,
                }
            current_monitor_value = float(current_eval["val"][self.args.early_stop_metric])
        else:
            raise ValueError("early_stopping.mode must be either 'loss' or 'val_metric'.")

        if early_best_epoch == 0:
            improved = True
        elif mode == "loss":
            improved = current_monitor_value < (early_best_value - float(self.args.early_stop_min_delta))
        else:
            improved = current_monitor_value > (early_best_value + float(self.args.early_stop_min_delta))

        if improved:
            early_best_value = current_monitor_value
            early_best_epoch = epoch
            early_bad_steps = 0
        else:
            early_bad_steps += 1

        stopped = False
        reason = None
        if epoch >= int(self.args.early_stop_warmup) and early_bad_steps >= int(self.args.early_stop_patience):
            stopped = True
            reason = (
                f"no improvement on {early_monitor_name} for {early_bad_steps} step(s); "
                f"best={early_best_value:.6f} at epoch={early_best_epoch}"
            )

        return {
            "best_value": early_best_value,
            "best_epoch": early_best_epoch,
            "bad_steps": early_bad_steps,
            "current_value": current_monitor_value,
            "improved": improved,
            "stopped": stopped,
            "reason": reason,
        }

    def _print_epoch(self, epoch: int, metrics: dict[str, float], current_eval: dict[str, Any] | None) -> None:
        print(
            f"Epoch {epoch:03d}/{int(self.args.epochs):03d} | "
            f"base={metrics['base_loss']:.6f} total={metrics['total_loss']:.6f}"
        )
        if current_eval is None:
            return
        print(
            f"  Val@{self.args.eval_k}: "
            f"P={current_eval['val']['precision']:.4f} "
            f"R={current_eval['val']['recall']:.4f} "
            f"NDCG={current_eval['val']['ndcg']:.4f} "
            f"HR={current_eval['val']['hr']:.4f} "
            f"| leaks={current_eval['leaked_users_val']}"
        )

args = args instance-attribute

role = _normalize_role(args.role) instance-attribute

device = torch.device(args.device) if args.device else torch.device('cuda' if torch.cuda.is_available() else 'cpu') instance-attribute

backbone = normalize_backbone_name(args.backbone) instance-attribute

output_path = Path(args.output_path) if args.output_path else self._default_output_path() instance-attribute

run_dir = self.output_path.parent.parent if self.output_path.parent.name == 'artifacts' else self.output_path.parent instance-attribute

dataset = None instance-attribute

val_dict: dict[int, set[int]] = {} instance-attribute

test_dict: dict[int, set[int]] = {} instance-attribute

model = None instance-attribute

optimizer = None instance-attribute

trainer = None instance-attribute

__init__(args: NativeTrainingArgs)

Source code in recdistill/native_runner.py
def __init__(self, args: NativeTrainingArgs):
    self.args = args
    self.role = _normalize_role(args.role)
    self.device = torch.device(args.device) if args.device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
    self.backbone = normalize_backbone_name(args.backbone)
    self.output_path = Path(args.output_path) if args.output_path else self._default_output_path()
    self.output_path.parent.mkdir(parents=True, exist_ok=True)
    self.run_dir = self.output_path.parent.parent if self.output_path.parent.name == "artifacts" else self.output_path.parent
    (self.run_dir / "logs").mkdir(parents=True, exist_ok=True)
    (self.run_dir / "config").mkdir(parents=True, exist_ok=True)
    if args.config_path:
        source = Path(args.config_path)
        if source.exists():
            (self.run_dir / "config" / source.name).write_text(source.read_text(encoding="utf-8"), encoding="utf-8")

    self.dataset = None
    self.val_dict: dict[int, set[int]] = {}
    self.test_dict: dict[int, set[int]] = {}
    self.model = None
    self.optimizer = None
    self.trainer = None

run_config() -> dict[str, Any]

Source code in recdistill/native_runner.py
def run_config(self) -> dict[str, Any]:
    payload = asdict(self.args)
    payload["role"] = self.role
    payload["backbone"] = self.backbone
    payload["framework"] = self.args.framework
    payload["output_path"] = str(self.output_path)
    return payload

prepare() -> None

Source code in recdistill/native_runner.py
def prepare(self) -> None:
    print("\n" + "=" * 80)
    print(f"{self.role.capitalize()} Training")
    print("=" * 80)
    print(f"Dataset: {self.args.dataset}")
    print(f"Backbone: {self.backbone}")
    print(f"Framework: {self.args.framework}")
    print(f"Embedding dim: {self.args.embedding_dim}")
    print(f"Device: {self.device}")
    print("=" * 80 + "\n")

    self.dataset = load_interaction_dataset(self.args.dataset)
    print(f"Train interactions: {len(self.dataset.interactions)}")
    print(f"Users/items: {self.dataset.num_users}/{self.dataset.num_items}")

    if not self.args.skip_eval:
        self.val_dict, dropped_val = load_eval_split(
            dataset_name=self.args.dataset,
            split_name="val",
            teacher_num_users=self.dataset.num_users,
            teacher_num_items=self.dataset.num_items,
        )
        self.test_dict, dropped_test = load_eval_split(
            dataset_name=self.args.dataset,
            split_name="test",
            teacher_num_users=self.dataset.num_users,
            teacher_num_items=self.dataset.num_items,
        )
        print(f"Validation interactions: {sum(len(v) for v in self.val_dict.values())} (dropped: {dropped_val})")
        print(f"Test interactions: {sum(len(v) for v in self.test_dict.values())} (dropped: {dropped_test})")

    train_loader = build_train_loader(
        self.dataset,
        batch_size=int(self.args.batch_size),
        num_workers=int(self.args.num_workers),
    )
    self.model = build_student_model(
        backbone=self.backbone,
        dataset=self.dataset,
        embedding_dim=int(self.args.embedding_dim),
        l2_reg=float(self.args.l2_reg),
        lightgcn_layers=int(self.args.lightgcn_layers),
        neumf_mlp_dims=parse_mlp_dims(self.args.neumf_mlp_dims),
        neumf_dropout=float(self.args.dropout),
        framework=self.args.framework,
        graph_builder=build_lightgcn_graph,
    ).to(self.device)
    self.optimizer = torch.optim.Adam(self.model.parameters(), lr=float(self.args.learning_rate))
    self.trainer = DistillationTrainer(
        model=self.model,
        optimizer=self.optimizer,
        train_loader=train_loader,
        distiller=None,
        device=self.device,
        dataset=self.dataset,
    )

run() -> dict[str, Any]

Source code in recdistill/native_runner.py
def run(self) -> dict[str, Any]:
    set_seed(int(self.args.seed))
    self.prepare()
    return self.train()

train() -> dict[str, Any]

Source code in recdistill/native_runner.py
def train(self) -> dict[str, Any]:
    assert self.dataset is not None
    assert self.model is not None
    assert self.optimizer is not None
    assert self.trainer is not None

    history: list[dict[str, Any]] = []
    best_score = float("-inf")
    best_epoch = 0
    best_artifact = best_checkpoint_path(self.output_path)
    early_best_value = float("inf") if self.args.early_stop_mode == "loss" else float("-inf")
    early_best_epoch = 0
    early_bad_steps = 0
    early_stopped = False
    early_stop_reason: str | None = None
    early_monitor_name = "total_loss" if self.args.early_stop_mode == "loss" else f"val_{self.args.early_stop_metric}"
    early_best_artifact = _with_role_suffix(
        self.output_path,
        f".earlystop_best{TEACHER_EXT if self.role == 'teacher' else STUDENT_EXT}",
    )

    for epoch in range(1, int(self.args.epochs) + 1):
        metrics = self.trainer.train_epoch()
        row: dict[str, Any] = {"epoch": epoch, **metrics}
        current_eval = None
        if not self.args.skip_eval and self.args.eval_every > 0 and epoch % int(self.args.eval_every) == 0:
            current_eval = evaluate_student(
                model=self.model,
                train_seen=self.dataset.train_dict,
                val_gt=self.val_dict,
                test_gt=self.test_dict,
                top_k=int(self.args.eval_k),
                batch_size=int(self.args.eval_batch_size),
                device=self.device,
                eval_val_only=bool(self.args.eval_val_only),
            )
            self._update_eval_row(row, current_eval)
            leaked_users_test = int(current_eval.get("leaked_users_test", 0))
            if self.args.assert_no_train_leak and (current_eval["leaked_users_val"] > 0 or leaked_users_test > 0):
                raise RuntimeError(
                    "Train-item leakage detected in recommendations. "
                    f"val_leaks={current_eval['leaked_users_val']} test_leaks={leaked_users_test}"
                )

            selected_metrics = current_eval[self.args.selection_split]
            selected_score = float(selected_metrics[self.args.selection_metric])
            row["selection_score"] = selected_score
            if selected_score > best_score:
                best_score = selected_score
                best_epoch = epoch
                self._save_artifact(best_artifact, epoch, history + [row], best_epoch, best_score)

        history.append(row)
        self._print_epoch(epoch, metrics, current_eval)

        early_state = self._maybe_early_stop(
            epoch=epoch,
            row=row,
            current_eval=current_eval,
            early_best_value=early_best_value,
            early_best_epoch=early_best_epoch,
            early_bad_steps=early_bad_steps,
            early_monitor_name=early_monitor_name,
        )
        early_best_value = early_state["best_value"]
        early_best_epoch = early_state["best_epoch"]
        early_bad_steps = early_state["bad_steps"]
        row["early_monitor_name"] = early_monitor_name if self.args.early_stop else None
        row["early_monitor_value"] = early_state["current_value"]
        row["early_bad_steps"] = early_bad_steps if self.args.early_stop else None
        if self.args.early_stop and early_state["improved"] and self.args.early_stop_restore_best:
            self._save_artifact(
                early_best_artifact,
                epoch,
                history,
                best_epoch,
                best_score if best_epoch > 0 else None,
                extra={
                    "early_monitor_name": early_monitor_name,
                    "early_best_epoch": early_best_epoch,
                    "early_best_value": early_best_value,
                },
            )
        if early_state["stopped"]:
            early_stopped = True
            early_stop_reason = early_state["reason"]
            print(f"Early stopping triggered at epoch {epoch}: {early_stop_reason}")
            break

        if self.args.save_every > 0 and epoch % int(self.args.save_every) == 0:
            periodic = _with_role_suffix(
                self.output_path,
                f".ep{epoch}{TEACHER_EXT if self.role == 'teacher' else STUDENT_EXT}",
            )
            self._save_artifact(periodic, epoch, history, best_epoch, best_score if best_epoch > 0 else None)

    final_epoch = int(history[-1]["epoch"]) if history else 0
    self._save_artifact(
        self.output_path,
        final_epoch,
        history,
        best_epoch,
        best_score if best_epoch > 0 else None,
        extra={
            "early_stopped": early_stopped,
            "early_stop_reason": early_stop_reason,
            "early_best_epoch": early_best_epoch if self.args.early_stop else 0,
            "early_best_value": early_best_value if self.args.early_stop and early_best_epoch > 0 else None,
            "early_monitor_name": early_monitor_name if self.args.early_stop else None,
        },
    )
    history_path = self.run_dir / "logs" / f"{self.output_path.stem}.history.json"
    history_path.write_text(json.dumps(history, indent=2), encoding="utf-8")

    result = {
        "status": "completed",
        "ended_at_utc": utc_now_iso(),
        "role": self.role,
        "dataset": self.args.dataset,
        "backbone": self.backbone,
        "output_path": str(self.output_path),
        "history_path": str(history_path),
        "best_epoch": best_epoch,
        "best_selection_score": best_score if best_epoch > 0 else None,
        "best_path": str(best_artifact) if best_epoch > 0 else None,
        "early_stopped": early_stopped,
        "early_stop_reason": early_stop_reason,
        "early_best_epoch": early_best_epoch if self.args.early_stop else 0,
        "early_best_value": early_best_value if self.args.early_stop and early_best_epoch > 0 else None,
        "early_monitor_name": early_monitor_name if self.args.early_stop else None,
    }
    print("\nTraining complete.")
    print(f"{self.role.capitalize()} artifact: {self.output_path}")
    if best_epoch > 0:
        print(f"Best artifact: {best_artifact} (epoch={best_epoch}, score={best_score:.6f})")
    print(f"History JSON: {history_path}\n")
    return result

native_args_from_model_config(*, role: str, dataset: str, backbone: str, overrides: dict[str, Any] | None = None) -> NativeTrainingArgs

Source code in recdistill/native_runner.py
def native_args_from_model_config(
    *,
    role: str,
    dataset: str,
    backbone: str,
    overrides: dict[str, Any] | None = None,
) -> NativeTrainingArgs:
    loader = get_config_loader()
    framework = None
    if overrides:
        framework = overrides.get("framework")
    model_cfg = loader.load_model_config(role, backbone, framework=framework)
    args = NativeTrainingArgs(
        role=role,
        dataset=dataset,
        backbone=model_cfg.backbone,
        framework=getattr(model_cfg, "framework", "recbole"),
        embedding_dim=int(model_cfg.embedding_dim),
        learning_rate=float(model_cfg.learning_rate),
        l2_reg=float(model_cfg.l2_reg),
        dropout=float(model_cfg.dropout),
        lightgcn_layers=int(getattr(model_cfg, "num_layers", getattr(model_cfg, "lightgcn_layers", 2))),
        neumf_mlp_dims=_stringify_mlp_dims(getattr(model_cfg, "mlp_hidden_size", getattr(model_cfg, "mlp_dims", "64,32,16,8"))),
    )
    if overrides:
        for key, value in overrides.items():
            if value is not None and hasattr(args, key):
                setattr(args, key, value)
    if args.early_stop and str(args.early_stop_mode).lower() == "val_metric" and args.skip_eval:
        raise ValueError("optimization.early_stopping.mode='val_metric' requires evaluation.enabled=true.")
    if args.early_stop and int(args.early_stop_patience) < 0:
        raise ValueError("optimization.early_stopping.patience must be non-negative.")
    return args

native_args_to_config(args: NativeTrainingArgs) -> dict[str, Any]

Source code in recdistill/native_runner.py
def native_args_to_config(args: NativeTrainingArgs) -> dict[str, Any]:
    role = _normalize_role(args.role)
    model_section_name = "teacher" if role == "teacher" else "student"
    model_key = "model" if role == "teacher" else "backbone"
    model_conf = {
        "framework": args.framework,
        model_key: args.backbone,
        "embedding_dim": int(args.embedding_dim),
        "learning_rate": float(args.learning_rate),
        "l2_reg": float(args.l2_reg),
        "dropout": float(args.dropout),
    }
    if args.backbone in {"LGCN", "NGCF", "DGCF", "SGL", "SPECTRALCF"}:
        model_conf["num_layers"] = int(args.lightgcn_layers)
    if args.backbone == "NMF":
        model_conf["mlp_hidden_size"] = _parse_mlp_dims_for_config(args.neumf_mlp_dims)

    return {
        "dataset": args.dataset,
        model_section_name: model_conf,
        "optimization": {
            "epochs": int(args.epochs),
            "batch_size": int(args.batch_size),
            "learning_rate": float(args.learning_rate),
            "l2_reg": float(args.l2_reg),
            "early_stopping": {
                "enabled": bool(args.early_stop),
                "mode": args.early_stop_mode,
                "metric": args.early_stop_metric,
                "patience": int(args.early_stop_patience),
                "min_delta": float(args.early_stop_min_delta),
                "warmup": int(args.early_stop_warmup),
                "restore_best": bool(args.early_stop_restore_best),
            },
        },
        "runtime": {
            "seed": int(args.seed),
            "device": args.device,
            "num_workers": int(args.num_workers),
            "output_path": args.output_path,
            "save_every": int(args.save_every),
        },
        "evaluation": {
            "enabled": not bool(args.skip_eval),
            "k": int(args.eval_k),
            "every": int(args.eval_every),
            "batch_size": int(args.eval_batch_size),
            "val_only": bool(args.eval_val_only),
            "selection_split": args.selection_split,
            "selection_metric": args.selection_metric,
            "assert_no_train_leak": bool(args.assert_no_train_leak),
        },
    }

native_args_from_config_file(path: str | Path, *, role: str, fallback_dataset: str | None = None, fallback_backbone: str | None = None, overrides: dict[str, Any] | None = None) -> NativeTrainingArgs

Source code in recdistill/native_runner.py
def native_args_from_config_file(
    path: str | Path,
    *,
    role: str,
    fallback_dataset: str | None = None,
    fallback_backbone: str | None = None,
    overrides: dict[str, Any] | None = None,
) -> NativeTrainingArgs:
    config_path = Path(path)
    raw_text = config_path.read_text(encoding="utf-8")
    if config_path.suffix.lower() == ".json":
        raw = json.loads(raw_text)
    else:
        try:
            import yaml
        except ModuleNotFoundError as exc:  # pragma: no cover - environment-specific
            raise ModuleNotFoundError("PyYAML is required to read YAML training configs.") from exc
        raw = yaml.safe_load(raw_text) or {}

    config = raw.get("config", raw) if isinstance(raw, dict) else {}
    return native_args_from_config(
        config,
        role=role,
        config_path=config_path,
        fallback_dataset=fallback_dataset,
        fallback_backbone=fallback_backbone,
        overrides=overrides,
    )

native_args_from_config(config: dict[str, Any], *, role: str, config_path: str | Path | None = None, fallback_dataset: str | None = None, fallback_backbone: str | None = None, overrides: dict[str, Any] | None = None) -> NativeTrainingArgs

Source code in recdistill/native_runner.py
def native_args_from_config(
    config: dict[str, Any],
    *,
    role: str,
    config_path: str | Path | None = None,
    fallback_dataset: str | None = None,
    fallback_backbone: str | None = None,
    overrides: dict[str, Any] | None = None,
) -> NativeTrainingArgs:
    config_path_obj = Path(config_path) if config_path is not None else None
    config = get_config_loader().resolve_config_modules(config)
    experiment_meta = config.get("experiment", {}) if isinstance(config.get("experiment", {}), dict) else {}
    experiment_id = normalize_experiment_id(experiment_meta.get("id"), config_path=config_path_obj)
    if not isinstance(config, dict):
        train = {}
    elif _normalize_role(role) == "teacher":
        train = config.get("train_teacher", {})
    else:
        train = config.get("train_student", {})
    model_section_name = "teacher" if _normalize_role(role) == "teacher" else "student"
    model_conf = train.get(model_section_name, train) if isinstance(train, dict) else {}
    optim_conf = train.get("optimization", {}) if isinstance(train, dict) else {}
    runtime_conf = train.get("runtime", {}) if isinstance(train, dict) else {}
    eval_conf = train.get("evaluation", {}) if isinstance(train, dict) else {}
    early_conf = optim_conf.get("early_stopping", {}) if isinstance(optim_conf, dict) else {}

    dataset = train.get("dataset") or config.get("dataset") or fallback_dataset
    backbone = model_conf.get("backbone") or model_conf.get("model") or fallback_backbone
    if dataset is None:
        raise ValueError(f"Missing dataset in {config_path_obj or '<config>'}.")
    if backbone is None:
        raise ValueError(f"Missing {model_section_name} backbone/model in {config_path_obj or '<config>'}.")

    def _override_or_config(key: str, source: dict[str, Any], default: Any = None) -> Any:
        if overrides and key in overrides and overrides[key] is not None:
            return overrides[key]
        value = source.get(key, default)
        return default if value is None else value

    embedding_dim = _override_or_config("embedding_dim", model_conf)
    if embedding_dim is None:
        raise ValueError(f"Missing {model_section_name}.embedding_dim in {config_path_obj or '<config>'}.")
    lightgcn_layers = _first_not_none(
        overrides.get("lightgcn_layers") if overrides else None,
        model_conf.get("lightgcn_layers"),
        model_conf.get("num_layers"),
        model_conf.get("layers"),
        2,
    )
    mlp_dims = _first_not_none(
        overrides.get("neumf_mlp_dims") if overrides else None,
        model_conf.get("neumf_mlp_dims"),
        model_conf.get("mlp_hidden_size"),
        model_conf.get("mlp_dims"),
        "64,32,16,8",
    )

    configured_output_path = runtime_conf.get("output_path")
    if configured_output_path is None:
        framework = str(_override_or_config("framework", model_conf, "recbole"))
        configured_output_path = experiment_artifact_path(
            kind=role,
            experiment_id=experiment_id,
            framework=framework,
            model=str(backbone),
            dataset=str(dataset),
            filename=experiment_artifact_filename(
                kind=role,
                experiment_id=experiment_id,
                framework=framework,
                model=str(backbone),
                dataset=str(dataset),
            ),
        )

    args = NativeTrainingArgs(
        role=role,
        dataset=str(dataset),
        backbone=str(backbone),
        framework=str(_override_or_config("framework", model_conf, "recbole")),
        embedding_dim=int(embedding_dim),
        epochs=int(_override_or_config("epochs", optim_conf, 100)),
        batch_size=int(_override_or_config("batch_size", optim_conf, 512)),
        learning_rate=float(_override_or_config("learning_rate", optim_conf, model_conf.get("learning_rate", 0.001))),
        l2_reg=float(_override_or_config("l2_reg", optim_conf, model_conf.get("l2_reg", 0.0001))),
        dropout=float(_override_or_config("dropout", model_conf, 0.0)),
        lightgcn_layers=int(lightgcn_layers),
        neumf_mlp_dims=_stringify_mlp_dims(mlp_dims),
        seed=int(runtime_conf.get("seed", 42)),
        device=runtime_conf.get("device"),
        num_workers=int(runtime_conf.get("num_workers", 0)),
        output_path=str(configured_output_path),
        save_every=int(runtime_conf.get("save_every", 0)),
        skip_eval=not bool(eval_conf.get("enabled", True)),
        eval_k=int(eval_conf.get("k", 20)),
        eval_every=int(eval_conf.get("every", 5)),
        eval_batch_size=int(eval_conf.get("batch_size", 1024)),
        eval_val_only=bool(eval_conf.get("val_only", True)),
        selection_split=str(eval_conf.get("selection_split", "val")),
        selection_metric=str(eval_conf.get("selection_metric", "ndcg")),
        assert_no_train_leak=bool(eval_conf.get("assert_no_train_leak", True)),
        early_stop=bool(early_conf.get("enabled", False)),
        early_stop_mode=str(early_conf.get("mode", "val_metric")),
        early_stop_metric=str(early_conf.get("metric", "ndcg")),
        early_stop_patience=int(early_conf.get("patience", 10)),
        early_stop_min_delta=float(early_conf.get("min_delta", 0.0)),
        early_stop_warmup=int(early_conf.get("warmup", 0)),
        early_stop_restore_best=bool(early_conf.get("restore_best", False)),
        config_path=str(config_path_obj) if config_path_obj is not None else None,
    )
    if overrides:
        for key, value in overrides.items():
            if value is not None and hasattr(args, key):
                setattr(args, key, value)
    return args

Trainers

Trainer

Bases: ABC

Source code in recdistill/trainers/base.py
6
7
8
9
class Trainer(ABC):
    @abstractmethod
    def train_epoch(self) -> dict[str, float]:
        raise NotImplementedError

train_epoch() -> dict[str, float] abstractmethod

Source code in recdistill/trainers/base.py
7
8
9
@abstractmethod
def train_epoch(self) -> dict[str, float]:
    raise NotImplementedError

TrainerMetrics dataclass

Source code in recdistill/trainers/distillation.py
@dataclass
class TrainerMetrics:
    base_loss: float
    distill_loss: float
    total_loss: float

base_loss: float instance-attribute

distill_loss: float instance-attribute

total_loss: float instance-attribute

__init__(base_loss: float, distill_loss: float, total_loss: float) -> None

DistillationTrainer

Bases: Trainer

Source code in recdistill/trainers/distillation.py
class DistillationTrainer(Trainer):
    def __init__(
        self,
        model: torch.nn.Module,
        optimizer: torch.optim.Optimizer,
        train_loader,
        distiller: Distiller | None = None,
        device: torch.device | None = None,
        teacher_state: TeacherState | None = None,
        dataset: InteractionDataset | None = None,
        config: RecDistillConfig | None = None,
    ):
        self.config = config
        self.train_config = config.distill_student if config is not None else None
        self.device = device or torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.model = model.to(self.device)
        self.optimizer = optimizer
        self.train_loader = train_loader
        self.distiller = distiller.to(self.device) if distiller is not None else None
        self.teacher_state = teacher_state.to(self.device) if teacher_state is not None else None
        self.dataset = dataset

        if (
            self.distiller is not None
            and self.teacher_state is not None
            and self.dataset is not None
            and not getattr(self.distiller, "_recdistill_initialized", False)
        ):
            self.distiller.on_train_start(self.teacher_state, self.dataset)
            setattr(self.distiller, "_recdistill_initialized", True)

    @classmethod
    def load_config(
        cls,
        dataset_name: str,
        teacher_model: str,
        distiller_strategy: str,
        student_backbone: str | None = None,
        overrides: dict | None = None,
    ) -> RecDistillConfig:
        """Load the validated RecDistill config used by trainer callers."""
        return load_recdistill_experiment(
            dataset_name=dataset_name,
            teacher_model=teacher_model,
            distiller_strategy=distiller_strategy,
            student_backbone=student_backbone,
            overrides=overrides,
        )

    def train_epoch(self) -> dict[str, float]:
        self.model.train()
        if self.distiller is not None:
            self.distiller.on_epoch_start()

        total_base_loss = 0.0
        total_distill_loss = 0.0
        total_loss = 0.0
        num_batches = 0

        for users, pos_items, neg_items in self.train_loader:
            batch = InteractionBatch(
                users=users.to(self.device),
                pos_items=pos_items.to(self.device),
                neg_items=neg_items.to(self.device),
            )

            batch_output = self.model(batch.users, batch.pos_items, batch.neg_items)
            base_loss = self.model.compute_base_loss(batch_output)

            distill_loss = torch.zeros((), device=self.device)
            if self.distiller is not None:
                aux_batch = self.distiller.build_aux_batch(batch, device=self.device)
                distill_loss = self.distiller.compute_loss(self.model, batch, aux_batch)

            loss = base_loss + distill_loss
            self.optimizer.zero_grad()
            loss.backward()
            self.optimizer.step()

            total_base_loss += float(base_loss.detach().cpu())
            total_distill_loss += float(distill_loss.detach().cpu())
            total_loss += float(loss.detach().cpu())
            num_batches += 1

        if num_batches == 0:
            return TrainerMetrics(0.0, 0.0, 0.0).__dict__

        return TrainerMetrics(
            base_loss=total_base_loss / num_batches,
            distill_loss=total_distill_loss / num_batches,
            total_loss=total_loss / num_batches,
        ).__dict__

config = config instance-attribute

train_config = config.distill_student if config is not None else None instance-attribute

device = device or torch.device('cuda' if torch.cuda.is_available() else 'cpu') instance-attribute

model = model.to(self.device) instance-attribute

optimizer = optimizer instance-attribute

train_loader = train_loader instance-attribute

distiller = distiller.to(self.device) if distiller is not None else None instance-attribute

teacher_state = teacher_state.to(self.device) if teacher_state is not None else None instance-attribute

dataset = dataset instance-attribute

__init__(model: torch.nn.Module, optimizer: torch.optim.Optimizer, train_loader, distiller: Distiller | None = None, device: torch.device | None = None, teacher_state: TeacherState | None = None, dataset: InteractionDataset | None = None, config: RecDistillConfig | None = None)

Source code in recdistill/trainers/distillation.py
def __init__(
    self,
    model: torch.nn.Module,
    optimizer: torch.optim.Optimizer,
    train_loader,
    distiller: Distiller | None = None,
    device: torch.device | None = None,
    teacher_state: TeacherState | None = None,
    dataset: InteractionDataset | None = None,
    config: RecDistillConfig | None = None,
):
    self.config = config
    self.train_config = config.distill_student if config is not None else None
    self.device = device or torch.device("cuda" if torch.cuda.is_available() else "cpu")
    self.model = model.to(self.device)
    self.optimizer = optimizer
    self.train_loader = train_loader
    self.distiller = distiller.to(self.device) if distiller is not None else None
    self.teacher_state = teacher_state.to(self.device) if teacher_state is not None else None
    self.dataset = dataset

    if (
        self.distiller is not None
        and self.teacher_state is not None
        and self.dataset is not None
        and not getattr(self.distiller, "_recdistill_initialized", False)
    ):
        self.distiller.on_train_start(self.teacher_state, self.dataset)
        setattr(self.distiller, "_recdistill_initialized", True)

load_config(dataset_name: str, teacher_model: str, distiller_strategy: str, student_backbone: str | None = None, overrides: dict | None = None) -> RecDistillConfig classmethod

Load the validated RecDistill config used by trainer callers.

Source code in recdistill/trainers/distillation.py
@classmethod
def load_config(
    cls,
    dataset_name: str,
    teacher_model: str,
    distiller_strategy: str,
    student_backbone: str | None = None,
    overrides: dict | None = None,
) -> RecDistillConfig:
    """Load the validated RecDistill config used by trainer callers."""
    return load_recdistill_experiment(
        dataset_name=dataset_name,
        teacher_model=teacher_model,
        distiller_strategy=distiller_strategy,
        student_backbone=student_backbone,
        overrides=overrides,
    )

train_epoch() -> dict[str, float]

Source code in recdistill/trainers/distillation.py
def train_epoch(self) -> dict[str, float]:
    self.model.train()
    if self.distiller is not None:
        self.distiller.on_epoch_start()

    total_base_loss = 0.0
    total_distill_loss = 0.0
    total_loss = 0.0
    num_batches = 0

    for users, pos_items, neg_items in self.train_loader:
        batch = InteractionBatch(
            users=users.to(self.device),
            pos_items=pos_items.to(self.device),
            neg_items=neg_items.to(self.device),
        )

        batch_output = self.model(batch.users, batch.pos_items, batch.neg_items)
        base_loss = self.model.compute_base_loss(batch_output)

        distill_loss = torch.zeros((), device=self.device)
        if self.distiller is not None:
            aux_batch = self.distiller.build_aux_batch(batch, device=self.device)
            distill_loss = self.distiller.compute_loss(self.model, batch, aux_batch)

        loss = base_loss + distill_loss
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        total_base_loss += float(base_loss.detach().cpu())
        total_distill_loss += float(distill_loss.detach().cpu())
        total_loss += float(loss.detach().cpu())
        num_batches += 1

    if num_batches == 0:
        return TrainerMetrics(0.0, 0.0, 0.0).__dict__

    return TrainerMetrics(
        base_loss=total_base_loss / num_batches,
        distill_loss=total_distill_loss / num_batches,
        total_loss=total_loss / num_batches,
    ).__dict__

Factories

normalize_backbone_name(backbone: str) -> str

Source code in recdistill/factories.py
def normalize_backbone_name(backbone: str) -> str:
    return canonical_model_name(backbone)

parse_mlp_dims(value: str | list[int] | tuple[int, ...]) -> tuple[int, ...]

Source code in recdistill/factories.py
def parse_mlp_dims(value: str | list[int] | tuple[int, ...]) -> tuple[int, ...]:
    if isinstance(value, str):
        return tuple(int(part.strip()) for part in value.split(",") if part.strip())
    return tuple(int(part) for part in value)

build_student_model(*, backbone: str, dataset: InteractionDataset, embedding_dim: int, l2_reg: float = 0.0, lightgcn_layers: int = 2, neumf_mlp_dims: str | list[int] | tuple[int, ...] = '64,32,16,8', neumf_dropout: float = 0.0, framework: str = 'recbole', graph_builder=None)

Source code in recdistill/factories.py
def build_student_model(
    *,
    backbone: str,
    dataset: InteractionDataset,
    embedding_dim: int,
    l2_reg: float = 0.0,
    lightgcn_layers: int = 2,
    neumf_mlp_dims: str | list[int] | tuple[int, ...] = "64,32,16,8",
    neumf_dropout: float = 0.0,
    framework: str = "recbole",
    graph_builder=None,
):
    backbone = normalize_backbone_name(backbone)
    del graph_builder
    return build_framework_backbone_adapter(
        framework=framework,
        backbone=backbone,
        dataset=dataset,
        embedding_dim=int(embedding_dim),
        l2_reg=float(l2_reg),
        lightgcn_layers=int(lightgcn_layers),
        neumf_mlp_dims=parse_mlp_dims(neumf_mlp_dims),
        neumf_dropout=float(neumf_dropout),
    )

build_distiller_from_args(args: Any, teacher_state: TeacherState, student_dim: int) -> Distiller | None

Source code in recdistill/factories.py
def build_distiller_from_args(args: Any, teacher_state: TeacherState, student_dim: int) -> Distiller | None:
    active_distillers: list[Distiller] = []
    if float(getattr(args, "lambda_de", 0.0)) > 0:
        if not teacher_state.has_embeddings:
            raise ValueError("DE distillation requires an embedding-based teacher.")
        active_distillers.append(
            DEDistiller(
                teacher_dim=teacher_state.embedding_dim,
                student_dim=int(student_dim),
                num_experts=int(args.num_experts),
                lambda_de=float(args.lambda_de),
                temperature=float(args.temperature),
            )
        )

    if float(getattr(args, "lambda_rrd", 0.0)) > 0:
        sampler = RRDSampler(
            interesting_size=int(args.rrd_interesting_size),
            uninteresting_size=int(args.rrd_uninteresting_size),
            temperature=float(args.rrd_temperature),
            topk_provider=TeacherTopKProvider(top_k=int(args.rrd_teacher_topk)),
        )
        active_distillers.append(RRDDistiller(sampler=sampler, lambda_rrd=float(args.lambda_rrd)))

    if float(getattr(args, "lambda_unkd", 0.0)) > 0:
        active_distillers.append(
            UnKDDistiller(
                lambda_unkd=float(args.lambda_unkd),
                sample_num=int(args.unkd_sample_num),
                group_count=int(args.unkd_group_count),
                popularity_lambda=float(args.unkd_popularity_lambda),
                rank_top_k=int(args.unkd_rank_top_k),
                rank_temperature=float(args.unkd_rank_temperature),
            )
        )

    if float(getattr(args, "lambda_td", 0.0)) > 0:
        if not teacher_state.has_embeddings:
            raise ValueError("HTD/FTD topology distillation requires an embedding-based teacher.")
        topology_type = str(args.td_type).upper()
        if topology_type == "FTD":
            active_distillers.append(
                FTDistiller(
                    lambda_td=float(args.lambda_td),
                    entity_sample_size=int(args.td_entity_sample_size),
                )
            )
        else:
            active_distillers.append(
                HTDistiller(
                    lambda_td=float(args.lambda_td),
                    alpha=float(args.htd_alpha),
                    num_groups=int(args.htd_num_groups),
                    topology_mode=str(args.htd_topology_mode),
                    initial_tau=float(args.htd_initial_tau),
                    min_tau=float(args.htd_min_tau),
                    decay_epochs=int(args.htd_decay_epochs),
                    entity_sample_size=int(args.td_entity_sample_size),
                )
            )

    if not active_distillers:
        return None
    if len(active_distillers) == 1:
        return active_distillers[0]
    return CompositeDistiller(active_distillers)

build_student_from_config(student_config: Any, dataset: InteractionDataset, *, optimization_config: Any | None = None, graph_builder=None)

Source code in recdistill/factories.py
def build_student_from_config(
    student_config: Any,
    dataset: InteractionDataset,
    *,
    optimization_config: Any | None = None,
    graph_builder=None,
):
    return build_student_model(
        backbone=student_config.backbone,
        dataset=dataset,
        embedding_dim=student_config.embedding_dim,
        l2_reg=getattr(optimization_config, "l2_reg", 0.0) if optimization_config is not None else 0.0,
        lightgcn_layers=getattr(student_config, "num_layers", getattr(student_config, "lightgcn_layers", 2)),
        neumf_mlp_dims=getattr(student_config, "mlp_hidden_size", getattr(student_config, "mlp_dims", "64,32,16,8")),
        neumf_dropout=getattr(student_config, "dropout", 0.0),
        framework=getattr(student_config, "framework", "recbole"),
        graph_builder=graph_builder,
    )

build_distiller_from_config(distillation_config: Any, *, teacher_state: TeacherState, student_dim: int) -> Distiller | None

Source code in recdistill/factories.py
def build_distiller_from_config(
    distillation_config: Any,
    *,
    teacher_state: TeacherState,
    student_dim: int,
) -> Distiller | None:
    class _Args:
        pass

    args = _Args()
    args.lambda_de = getattr(distillation_config, "lambda_de", 0.0)
    args.num_experts = getattr(distillation_config, "num_experts", 10)
    args.temperature = getattr(distillation_config, "temperature", 1.0)
    args.lambda_rrd = getattr(distillation_config, "lambda_rrd", 0.0)
    args.rrd_interesting_size = _nested_get(distillation_config, "rrd", "interesting_size", 10)
    args.rrd_uninteresting_size = _nested_get(distillation_config, "rrd", "uninteresting_size", 50)
    args.rrd_temperature = _nested_get(distillation_config, "rrd", "temperature", 1.0)
    args.rrd_teacher_topk = _nested_get(distillation_config, "rrd", "teacher_topk", 500)
    args.lambda_unkd = getattr(distillation_config, "lambda_unkd", 0.0)
    args.unkd_sample_num = _nested_get(distillation_config, "unkd", "sample_num", 30)
    args.unkd_group_count = _nested_get(distillation_config, "unkd", "group_count", 2)
    args.unkd_popularity_lambda = _nested_get(distillation_config, "unkd", "popularity_lambda", 1.0)
    args.unkd_rank_top_k = _nested_get(distillation_config, "unkd", "rank_top_k", 1000)
    args.unkd_rank_temperature = _nested_get(distillation_config, "unkd", "rank_temperature", 20.0)
    topology = getattr(distillation_config, "topology", None) or {}
    args.lambda_td = _mapping_get(topology, "lambda_td", getattr(distillation_config, "lambda_td", 0.0))
    args.td_type = _mapping_get(topology, "type", getattr(distillation_config, "strategy", "HTD"))
    args.td_entity_sample_size = _mapping_get(topology, "entity_sample_size", 0)
    args.htd_alpha = _mapping_get(topology, "alpha", 0.5)
    args.htd_num_groups = _mapping_get(topology, "num_groups", 40)
    args.htd_topology_mode = _mapping_get(topology, "topology_mode", "group_pe")
    args.htd_initial_tau = _mapping_get(topology, "initial_tau", 1.0)
    args.htd_min_tau = _mapping_get(topology, "min_tau", 1e-10)
    args.htd_decay_epochs = _mapping_get(topology, "decay_epochs", 100)
    return build_distiller_from_args(args, teacher_state=teacher_state, student_dim=student_dim)

Shared Training Utilities

PositiveInteractionDataset

Bases: Dataset

Source code in recdistill/training.py
class PositiveInteractionDataset(torch.utils.data.Dataset):
    def __init__(self, interactions: list[tuple[int, int]]):
        self._interactions = interactions

    def __len__(self) -> int:
        return len(self._interactions)

    def __getitem__(self, idx: int) -> tuple[int, int]:
        return self._interactions[idx]

__init__(interactions: list[tuple[int, int]])

Source code in recdistill/training.py
def __init__(self, interactions: list[tuple[int, int]]):
    self._interactions = interactions

__len__() -> int

Source code in recdistill/training.py
def __len__(self) -> int:
    return len(self._interactions)

__getitem__(idx: int) -> tuple[int, int]

Source code in recdistill/training.py
def __getitem__(self, idx: int) -> tuple[int, int]:
    return self._interactions[idx]

BPRBatchCollator

Source code in recdistill/training.py
class BPRBatchCollator:
    def __init__(self, negative_sampler: BPRNegativeSampler):
        self.negative_sampler = negative_sampler

    def __call__(self, batch_rows: list[tuple[int, int]]):
        users = torch.tensor([user for user, _ in batch_rows], dtype=torch.long)
        pos_items = torch.tensor([item for _, item in batch_rows], dtype=torch.long)
        neg_items = torch.tensor(
            [self.negative_sampler.sample(user) for user, _ in batch_rows],
            dtype=torch.long,
        )
        return users, pos_items, neg_items

negative_sampler = negative_sampler instance-attribute

__init__(negative_sampler: BPRNegativeSampler)

Source code in recdistill/training.py
def __init__(self, negative_sampler: BPRNegativeSampler):
    self.negative_sampler = negative_sampler

__call__(batch_rows: list[tuple[int, int]])

Source code in recdistill/training.py
def __call__(self, batch_rows: list[tuple[int, int]]):
    users = torch.tensor([user for user, _ in batch_rows], dtype=torch.long)
    pos_items = torch.tensor([item for _, item in batch_rows], dtype=torch.long)
    neg_items = torch.tensor(
        [self.negative_sampler.sample(user) for user, _ in batch_rows],
        dtype=torch.long,
    )
    return users, pos_items, neg_items

set_seed(seed: int) -> None

Source code in recdistill/training.py
def set_seed(seed: int) -> None:
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed(seed)
        torch.cuda.manual_seed_all(seed)

build_train_loader(dataset: InteractionDataset, batch_size: int, num_workers: int = 0) -> torch.utils.data.DataLoader

Source code in recdistill/training.py
def build_train_loader(
    dataset: InteractionDataset,
    batch_size: int,
    num_workers: int = 0,
) -> torch.utils.data.DataLoader:
    pair_dataset = PositiveInteractionDataset(dataset.interactions)
    negative_sampler = BPRNegativeSampler(dataset)

    loader_kwargs = dict(
        dataset=pair_dataset,
        batch_size=batch_size,
        shuffle=True,
        num_workers=num_workers,
        drop_last=False,
        pin_memory=True,
        collate_fn=BPRBatchCollator(negative_sampler),
    )
    if num_workers > 0:
        loader_kwargs["prefetch_factor"] = 2
        loader_kwargs["persistent_workers"] = True
    return torch.utils.data.DataLoader(**loader_kwargs)

build_lightgcn_graph(dataset: InteractionDataset) -> torch.Tensor

Source code in recdistill/training.py
def build_lightgcn_graph(dataset: InteractionDataset) -> torch.Tensor:
    rows: list[int] = []
    cols: list[int] = []
    item_offset = dataset.num_users
    for user, item in dataset.interactions:
        item_node = item_offset + item
        rows.extend([user, item_node])
        cols.extend([item_node, user])
    return torch.tensor([rows, cols], dtype=torch.long)

prepare_distiller_trainable_modules(distiller, student_dim: int, device: torch.device) -> None

Source code in recdistill/training.py
def prepare_distiller_trainable_modules(distiller, student_dim: int, device: torch.device) -> None:
    if distiller is None:
        return
    children = getattr(distiller, "distillers", None)
    if children is not None:
        for child in children:
            prepare_distiller_trainable_modules(child, student_dim, device)
        return
    prepare = getattr(distiller, "_ensure_student_adapters", None)
    if callable(prepare):
        prepare(student_dim=int(student_dim), device=device)