Skip to content

Students And Backbones

Students are adapter-backed PyTorch models trained either as plain recommendation baselines or as distilled models. The framework adapters hide RecBole, Elliot, and Lenskit implementation details behind a shared training surface.

Student Training

Train a baseline student without distillation:

python scripts/student_training/student_training.py \
  --framework recbole \
  --backbone LGCN \
  --dataset citeulike \
  --distillation none

Complete student experiment configs live in:

config/experiments/student/

Backbone Contract

Adapter-backed models expose the methods consumed by trainers and distillers:

forward(users, pos_items, neg_items)
score_items(users, items)
user_embeddings()
item_embeddings()

Framework Backbones

FrameworkBatchOutput dataclass

Source code in recdistill/framework_backbone.py
@dataclass
class FrameworkBatchOutput:
    pos_scores: torch.Tensor
    neg_scores: torch.Tensor
    base_loss: torch.Tensor

pos_scores: torch.Tensor instance-attribute

neg_scores: torch.Tensor instance-attribute

base_loss: torch.Tensor instance-attribute

__init__(pos_scores: torch.Tensor, neg_scores: torch.Tensor, base_loss: torch.Tensor) -> None

RecBoleDatasetAdapter

Source code in recdistill/framework_backbone.py
class RecBoleDatasetAdapter:
    def __init__(self, dataset: InteractionDataset):
        self.dataset = dataset
        self.uid_field = "user_id"
        self.iid_field = "item_id"
        self.inter_num = len(dataset.interactions)
        users = torch.tensor([user for user, _ in dataset.interactions], dtype=torch.long)
        items = torch.tensor([item for _, item in dataset.interactions], dtype=torch.long)
        self.inter_feat = {
            self.uid_field: users,
            self.iid_field: items,
        }

    def num(self, field: str) -> int:
        if field == "user_id":
            return self.dataset.num_users
        if field == "item_id":
            return self.dataset.num_items
        raise KeyError(f"Unsupported RecBole field: {field}")

    def inter_matrix(self, form: str = "coo"):
        rows = [user for user, _ in self.dataset.interactions]
        cols = [item for _, item in self.dataset.interactions]
        data = [1.0] * len(rows)
        matrix = sp.coo_matrix(
            (data, (rows, cols)),
            shape=(self.dataset.num_users, self.dataset.num_items),
            dtype="float32",
        )
        if form == "coo":
            return matrix
        if form == "csr":
            return matrix.tocsr()
        raise ValueError(f"Unsupported sparse matrix form: {form}")

dataset = dataset instance-attribute

uid_field = 'user_id' instance-attribute

iid_field = 'item_id' instance-attribute

inter_num = len(dataset.interactions) instance-attribute

inter_feat = {self.uid_field: users, self.iid_field: items} instance-attribute

__init__(dataset: InteractionDataset)

Source code in recdistill/framework_backbone.py
def __init__(self, dataset: InteractionDataset):
    self.dataset = dataset
    self.uid_field = "user_id"
    self.iid_field = "item_id"
    self.inter_num = len(dataset.interactions)
    users = torch.tensor([user for user, _ in dataset.interactions], dtype=torch.long)
    items = torch.tensor([item for _, item in dataset.interactions], dtype=torch.long)
    self.inter_feat = {
        self.uid_field: users,
        self.iid_field: items,
    }

num(field: str) -> int

Source code in recdistill/framework_backbone.py
def num(self, field: str) -> int:
    if field == "user_id":
        return self.dataset.num_users
    if field == "item_id":
        return self.dataset.num_items
    raise KeyError(f"Unsupported RecBole field: {field}")

inter_matrix(form: str = 'coo')

Source code in recdistill/framework_backbone.py
def inter_matrix(self, form: str = "coo"):
    rows = [user for user, _ in self.dataset.interactions]
    cols = [item for _, item in self.dataset.interactions]
    data = [1.0] * len(rows)
    matrix = sp.coo_matrix(
        (data, (rows, cols)),
        shape=(self.dataset.num_users, self.dataset.num_items),
        dtype="float32",
    )
    if form == "coo":
        return matrix
    if form == "csr":
        return matrix.tocsr()
    raise ValueError(f"Unsupported sparse matrix form: {form}")

RecBoleBackboneAdapter

Bases: Module

Source code in recdistill/framework_backbone.py
class RecBoleBackboneAdapter(nn.Module):
    _GRAPH_BACKBONES = {"LGCN", "NGCF", "DGCF", "SGL", "SPECTRALCF"}

    def __init__(
        self,
        *,
        backbone: str,
        dataset: InteractionDataset,
        embedding_dim: int,
        l2_reg: float = 0.0,
        lightgcn_layers: int = 2,
        neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8),
        neumf_dropout: float = 0.0,
        device: torch.device | str | None = None,
    ):
        super().__init__()
        self.backbone = canonical_model_name(backbone)
        self.dataset = dataset
        self.embedding_dim = int(embedding_dim)
        self.l2_reg = float(l2_reg)
        self.device_name = torch.device(device) if device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.config = self._build_config(
            embedding_dim=int(embedding_dim),
            l2_reg=float(l2_reg),
            lightgcn_layers=int(lightgcn_layers),
            neumf_mlp_dims=tuple(int(v) for v in neumf_mlp_dims),
            neumf_dropout=float(neumf_dropout),
        )
        self.recbole_dataset = RecBoleDatasetAdapter(dataset)
        self.model = self._build_model()
        self.model.to(self.device_name)

    @property
    def can_score_items_together(self) -> bool:
        return True

    def forward(
        self,
        users: torch.Tensor,
        pos_items: torch.Tensor,
        neg_items: torch.Tensor,
    ) -> FrameworkBatchOutput:
        users = users.to(self.device_name)
        pos_items = pos_items.to(self.device_name)
        neg_items = neg_items.to(self.device_name)
        interaction = {
            "user_id": users,
            "item_id": pos_items,
            "neg_item_id": neg_items,
        }
        if self.backbone == "NMF":
            pos_scores = self.model.forward(users, pos_items)
            neg_scores = self.model.forward(users, neg_items)
            base_loss = -F.logsigmoid(pos_scores - neg_scores).mean()
            if self.l2_reg > 0:
                user_emb = self.model.user_mf_embedding(users)
                pos_emb = self.model.item_mf_embedding(pos_items)
                neg_emb = self.model.item_mf_embedding(neg_items)
                reg = 0.5 * (
                    user_emb.norm(2).pow(2) + pos_emb.norm(2).pow(2) + neg_emb.norm(2).pow(2)
                ) / max(1, users.size(0))
                base_loss = base_loss + self.l2_reg * reg
        elif self.backbone in self._GRAPH_BACKBONES:
            user_table, item_table = self._graph_embeddings()
            pos_scores = (user_table[users] * item_table[pos_items]).sum(dim=-1)
            neg_scores = (user_table[users] * item_table[neg_items]).sum(dim=-1)
            base_loss = self._model_loss(interaction)
        else:
            if self.backbone == "LINE":
                user_e = self.model.user_embedding(users)
                pos_e = self.model.item_embedding(pos_items)
                neg_e = self.model.item_embedding(neg_items)
            else:
                user_e, pos_e = self.model.forward(users, pos_items)
                neg_e = self.model.get_item_embedding(neg_items)
            pos_scores = (user_e * pos_e).sum(dim=-1)
            neg_scores = (user_e * neg_e).sum(dim=-1)
            base_loss = self._model_loss(interaction)
            if self.l2_reg > 0:
                reg = 0.5 * (
                    user_e.norm(2).pow(2) + pos_e.norm(2).pow(2) + neg_e.norm(2).pow(2)
                ) / max(1, users.size(0))
                base_loss = base_loss + self.l2_reg * reg

        return FrameworkBatchOutput(
            pos_scores=pos_scores,
            neg_scores=neg_scores,
            base_loss=base_loss,
        )

    def compute_base_loss(self, batch_output: FrameworkBatchOutput) -> torch.Tensor:
        return batch_output.base_loss

    def score_items(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
        users = users.to(self.device_name)
        items = items.to(self.device_name)
        if items.ndim == 1:
            return self._score_pairs(users, items)
        expanded_users = users.unsqueeze(-1).expand(-1, items.size(1))
        return self._score_pairs(expanded_users, items)

    def score_items_for_user(self, user: int, num_items: int) -> torch.Tensor:
        items = torch.arange(num_items, dtype=torch.long, device=self.device_name)
        users = torch.full_like(items, int(user))
        return self.score_items(users, items)

    def get_all_user_embeddings(self) -> torch.Tensor:
        if self.backbone in self._GRAPH_BACKBONES:
            user_table, _ = self._graph_embeddings()
            return user_table
        if self.backbone == "NMF":
            return self.model.user_mf_embedding.weight
        return self.model.user_embedding.weight

    def get_all_item_embeddings(self) -> torch.Tensor:
        if self.backbone in self._GRAPH_BACKBONES:
            _, item_table = self._graph_embeddings()
            return item_table
        if self.backbone == "NMF":
            return self.model.item_mf_embedding.weight
        return self.model.item_embedding.weight

    def _score_pairs(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
        if self.backbone == "NMF":
            return torch.sigmoid(self.model.forward(users, items))
        if self.backbone in self._GRAPH_BACKBONES:
            user_table, item_table = self._graph_embeddings()
            return (user_table[users] * item_table[items]).sum(dim=-1)
        if self.backbone == "LINE":
            user_e = self.model.user_embedding(users)
            item_e = self.model.item_embedding(items)
            return (user_e * item_e).sum(dim=-1)
        user_e = self.model.get_user_embedding(users)
        item_e = self.model.get_item_embedding(items)
        return (user_e * item_e).sum(dim=-1)

    def _graph_embeddings(self) -> tuple[torch.Tensor, torch.Tensor]:
        if self.backbone == "SGL":
            return self.model.forward(self.model.train_graph)
        return self.model.forward()

    def _model_loss(self, interaction: dict[str, torch.Tensor]) -> torch.Tensor:
        loss = self.model.calculate_loss(interaction)
        if isinstance(loss, (tuple, list)):
            tensor_losses = [value for value in loss if torch.is_tensor(value)]
            if tensor_losses:
                return sum(tensor_losses)
        return loss

    def _build_config(
        self,
        *,
        embedding_dim: int,
        l2_reg: float,
        lightgcn_layers: int,
        neumf_mlp_dims: tuple[int, ...],
        neumf_dropout: float,
    ) -> dict:
        config = {
            "USER_ID_FIELD": "user_id",
            "ITEM_ID_FIELD": "item_id",
            "NEG_PREFIX": "neg_",
            "LABEL_FIELD": "label",
            "device": self.device_name,
            "embedding_size": embedding_dim,
        }
        if self.backbone == "LGCN":
            config.update(
                {
                    "n_layers": lightgcn_layers,
                    "reg_weight": l2_reg,
                    "require_pow": False,
                }
            )
        if self.backbone == "LINE":
            config.update(
                {
                    "order": 1,
                    "second_order_loss_weight": 1.0,
                }
            )
        if self.backbone == "NGCF":
            config.update(
                {
                    "hidden_size_list": [embedding_dim] * max(1, lightgcn_layers),
                    "node_dropout": 0.0,
                    "message_dropout": neumf_dropout,
                    "reg_weight": l2_reg,
                }
            )
        if self.backbone == "DGCF":
            n_factors = 4 if embedding_dim % 4 == 0 else 1
            config.update(
                {
                    "n_factors": n_factors,
                    "n_iterations": 2,
                    "n_layers": lightgcn_layers,
                    "reg_weight": l2_reg,
                    "cor_weight": 0.0,
                    "train_batch_size": 512,
                }
            )
        if self.backbone == "SGL":
            config.update(
                {
                    "n_layers": lightgcn_layers,
                    "type": "ED",
                    "drop_ratio": 0.1,
                    "ssl_tau": 0.2,
                    "reg_weight": l2_reg,
                    "ssl_weight": 0.1,
                }
            )
        if self.backbone == "SPECTRALCF":
            config.update(
                {
                    "n_layers": lightgcn_layers,
                    "reg_weight": l2_reg,
                }
            )
        if self.backbone == "NMF":
            config.update(
                {
                    "mf_embedding_size": embedding_dim,
                    "mlp_embedding_size": embedding_dim,
                    "mlp_hidden_size": list(neumf_mlp_dims),
                    "dropout_prob": neumf_dropout,
                    "mf_train": True,
                    "mlp_train": True,
                    "use_pretrain": False,
                    "mf_pretrain_path": None,
                    "mlp_pretrain_path": None,
                }
            )
        return config

    def _build_model(self) -> nn.Module:
        if self.backbone == "LINE":
            from recommenders.recbole.model.general_recommender.line import LINE

            return LINE(self.config, self.recbole_dataset)
        if self.backbone == "LGCN":
            from recommenders.recbole.model.general_recommender.lightgcn import LightGCN

            return LightGCN(self.config, self.recbole_dataset)
        if self.backbone == "NGCF":
            from recommenders.recbole.model.general_recommender.ngcf import NGCF

            return NGCF(self.config, self.recbole_dataset)
        if self.backbone == "DGCF":
            from recommenders.recbole.model.general_recommender.dgcf import DGCF

            return DGCF(self.config, self.recbole_dataset)
        if self.backbone == "SGL":
            from recommenders.recbole.model.general_recommender.sgl import SGL

            model = SGL(self.config, self.recbole_dataset)
            model.graph_construction()
            return model
        if self.backbone == "SPECTRALCF":
            from recommenders.recbole.model.general_recommender.spectralcf import SpectralCF

            return SpectralCF(self.config, self.recbole_dataset)
        if self.backbone == "NMF":
            from recommenders.recbole.model.general_recommender.neumf import NeuMF

            return NeuMF(self.config, self.recbole_dataset)
        from recommenders.recbole.model.general_recommender.bpr import BPR

        return BPR(self.config, self.recbole_dataset)

backbone = canonical_model_name(backbone) instance-attribute

dataset = dataset instance-attribute

embedding_dim = int(embedding_dim) instance-attribute

l2_reg = float(l2_reg) instance-attribute

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

config = self._build_config(embedding_dim=(int(embedding_dim)), l2_reg=(float(l2_reg)), lightgcn_layers=(int(lightgcn_layers)), neumf_mlp_dims=(tuple((int(v)) for v in neumf_mlp_dims)), neumf_dropout=(float(neumf_dropout))) instance-attribute

recbole_dataset = RecBoleDatasetAdapter(dataset) instance-attribute

model = self._build_model() instance-attribute

can_score_items_together: bool property

__init__(*, backbone: str, dataset: InteractionDataset, embedding_dim: int, l2_reg: float = 0.0, lightgcn_layers: int = 2, neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8), neumf_dropout: float = 0.0, device: torch.device | str | None = None)

Source code in recdistill/framework_backbone.py
def __init__(
    self,
    *,
    backbone: str,
    dataset: InteractionDataset,
    embedding_dim: int,
    l2_reg: float = 0.0,
    lightgcn_layers: int = 2,
    neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8),
    neumf_dropout: float = 0.0,
    device: torch.device | str | None = None,
):
    super().__init__()
    self.backbone = canonical_model_name(backbone)
    self.dataset = dataset
    self.embedding_dim = int(embedding_dim)
    self.l2_reg = float(l2_reg)
    self.device_name = torch.device(device) if device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
    self.config = self._build_config(
        embedding_dim=int(embedding_dim),
        l2_reg=float(l2_reg),
        lightgcn_layers=int(lightgcn_layers),
        neumf_mlp_dims=tuple(int(v) for v in neumf_mlp_dims),
        neumf_dropout=float(neumf_dropout),
    )
    self.recbole_dataset = RecBoleDatasetAdapter(dataset)
    self.model = self._build_model()
    self.model.to(self.device_name)

forward(users: torch.Tensor, pos_items: torch.Tensor, neg_items: torch.Tensor) -> FrameworkBatchOutput

Source code in recdistill/framework_backbone.py
def forward(
    self,
    users: torch.Tensor,
    pos_items: torch.Tensor,
    neg_items: torch.Tensor,
) -> FrameworkBatchOutput:
    users = users.to(self.device_name)
    pos_items = pos_items.to(self.device_name)
    neg_items = neg_items.to(self.device_name)
    interaction = {
        "user_id": users,
        "item_id": pos_items,
        "neg_item_id": neg_items,
    }
    if self.backbone == "NMF":
        pos_scores = self.model.forward(users, pos_items)
        neg_scores = self.model.forward(users, neg_items)
        base_loss = -F.logsigmoid(pos_scores - neg_scores).mean()
        if self.l2_reg > 0:
            user_emb = self.model.user_mf_embedding(users)
            pos_emb = self.model.item_mf_embedding(pos_items)
            neg_emb = self.model.item_mf_embedding(neg_items)
            reg = 0.5 * (
                user_emb.norm(2).pow(2) + pos_emb.norm(2).pow(2) + neg_emb.norm(2).pow(2)
            ) / max(1, users.size(0))
            base_loss = base_loss + self.l2_reg * reg
    elif self.backbone in self._GRAPH_BACKBONES:
        user_table, item_table = self._graph_embeddings()
        pos_scores = (user_table[users] * item_table[pos_items]).sum(dim=-1)
        neg_scores = (user_table[users] * item_table[neg_items]).sum(dim=-1)
        base_loss = self._model_loss(interaction)
    else:
        if self.backbone == "LINE":
            user_e = self.model.user_embedding(users)
            pos_e = self.model.item_embedding(pos_items)
            neg_e = self.model.item_embedding(neg_items)
        else:
            user_e, pos_e = self.model.forward(users, pos_items)
            neg_e = self.model.get_item_embedding(neg_items)
        pos_scores = (user_e * pos_e).sum(dim=-1)
        neg_scores = (user_e * neg_e).sum(dim=-1)
        base_loss = self._model_loss(interaction)
        if self.l2_reg > 0:
            reg = 0.5 * (
                user_e.norm(2).pow(2) + pos_e.norm(2).pow(2) + neg_e.norm(2).pow(2)
            ) / max(1, users.size(0))
            base_loss = base_loss + self.l2_reg * reg

    return FrameworkBatchOutput(
        pos_scores=pos_scores,
        neg_scores=neg_scores,
        base_loss=base_loss,
    )

compute_base_loss(batch_output: FrameworkBatchOutput) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def compute_base_loss(self, batch_output: FrameworkBatchOutput) -> torch.Tensor:
    return batch_output.base_loss

score_items(users: torch.Tensor, items: torch.Tensor) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def score_items(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
    users = users.to(self.device_name)
    items = items.to(self.device_name)
    if items.ndim == 1:
        return self._score_pairs(users, items)
    expanded_users = users.unsqueeze(-1).expand(-1, items.size(1))
    return self._score_pairs(expanded_users, items)

score_items_for_user(user: int, num_items: int) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def score_items_for_user(self, user: int, num_items: int) -> torch.Tensor:
    items = torch.arange(num_items, dtype=torch.long, device=self.device_name)
    users = torch.full_like(items, int(user))
    return self.score_items(users, items)

get_all_user_embeddings() -> torch.Tensor

Source code in recdistill/framework_backbone.py
def get_all_user_embeddings(self) -> torch.Tensor:
    if self.backbone in self._GRAPH_BACKBONES:
        user_table, _ = self._graph_embeddings()
        return user_table
    if self.backbone == "NMF":
        return self.model.user_mf_embedding.weight
    return self.model.user_embedding.weight

get_all_item_embeddings() -> torch.Tensor

Source code in recdistill/framework_backbone.py
def get_all_item_embeddings(self) -> torch.Tensor:
    if self.backbone in self._GRAPH_BACKBONES:
        _, item_table = self._graph_embeddings()
        return item_table
    if self.backbone == "NMF":
        return self.model.item_mf_embedding.weight
    return self.model.item_embedding.weight

ElliotBackboneAdapter

Bases: Module

Source code in recdistill/framework_backbone.py
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
class ElliotBackboneAdapter(nn.Module):
    _GRAPH_BACKBONES = {"LGCN", "NGCF", "DGCF", "SGL"}

    def __init__(
        self,
        *,
        backbone: str,
        dataset: InteractionDataset,
        embedding_dim: int,
        l2_reg: float = 0.0,
        lightgcn_layers: int = 2,
        neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8),
        neumf_dropout: float = 0.0,
        device: torch.device | str | None = None,
    ):
        super().__init__()
        self.backbone = canonical_model_name(backbone)
        self.dataset = dataset
        self.embedding_dim = int(embedding_dim)
        self.l2_reg = float(l2_reg)
        self.device_name = torch.device(device) if device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.seed = 42
        self.edge_index = self._edge_index()
        self.sparse_graph = None
        self.ultragcn_constraints = None
        self.model = self._build_model(
            lightgcn_layers=int(lightgcn_layers),
            neumf_mlp_dims=neumf_mlp_dims,
            neumf_dropout=neumf_dropout,
        )
        self.model.to(self.device_name)
        if hasattr(self.model, "device"):
            self.model.device = self.device_name

    @property
    def can_score_items_together(self) -> bool:
        return True

    def forward(self, users: torch.Tensor, pos_items: torch.Tensor, neg_items: torch.Tensor) -> FrameworkBatchOutput:
        users = users.to(self.device_name)
        pos_items = pos_items.to(self.device_name)
        neg_items = neg_items.to(self.device_name)

        if self.backbone == "ULTRAGCN":
            neg_matrix = neg_items.unsqueeze(1)
            base_loss = self.model.forward(users, pos_items, neg_matrix)
            pos_scores = self._score_pairs(users, pos_items)
            neg_scores = self._score_pairs(users, neg_items)
        elif self.backbone == "SGL":
            user_table, item_table = self._embedding_tables()
            pos_scores = (user_table[users] * item_table[pos_items]).sum(dim=-1)
            neg_scores = (user_table[users] * item_table[neg_items]).sum(dim=-1)
            base_loss = self._sgl_loss(users, pos_items, neg_items, pos_scores, neg_scores)
        else:
            pos_scores = self._score_pairs(users, pos_items)
            neg_scores = self._score_pairs(users, neg_items)
            base_loss = _bpr_loss(
                pos_scores,
                neg_scores,
                l2_reg=self.l2_reg,
                embeddings=self._regularized_embeddings(users, pos_items, neg_items),
            )
        return FrameworkBatchOutput(pos_scores=pos_scores, neg_scores=neg_scores, base_loss=base_loss)

    def compute_base_loss(self, batch_output: FrameworkBatchOutput) -> torch.Tensor:
        return batch_output.base_loss

    def score_items(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
        users = users.to(self.device_name)
        items = items.to(self.device_name)
        if items.ndim == 1:
            return self._score_pairs(users, items)
        expanded_users = users.unsqueeze(-1).expand(-1, items.size(1))
        return self._score_pairs(expanded_users, items)

    def score_items_for_user(self, user: int, num_items: int) -> torch.Tensor:
        items = torch.arange(num_items, dtype=torch.long, device=self.device_name)
        users = torch.full_like(items, int(user))
        return self.score_items(users, items)

    def get_all_user_embeddings(self) -> torch.Tensor:
        if self.backbone == "NMF":
            return self.model.user_mf_embedding.weight
        if self.backbone == "BPRMF":
            return self.model.Gu.weight
        if self.backbone == "ULTRAGCN":
            return self.model.Gu.weight
        user_table, _ = self._embedding_tables(evaluate=True)
        return user_table

    def get_all_item_embeddings(self) -> torch.Tensor:
        if self.backbone == "NMF":
            return self.model.item_mf_embedding.weight
        if self.backbone == "BPRMF":
            return self.model.Gi.weight
        if self.backbone == "ULTRAGCN":
            return self.model.Gi.weight
        _, item_table = self._embedding_tables(evaluate=True)
        return item_table

    def _score_pairs(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
        users = users.to(self.device_name)
        items = items.to(self.device_name)
        if self.backbone == "NMF":
            return self.model.forward((users, items), training=True).squeeze(-1)
        if self.backbone == "BPRMF":
            return (self.model.Gu(users) * self.model.Gi(items)).sum(dim=-1)
        if self.backbone == "ULTRAGCN":
            user_table = self.model.Gu.weight
            item_table = self.model.Gi.weight
        else:
            user_table, item_table = self._embedding_tables()
        return (user_table[users] * item_table[items]).sum(dim=-1)

    def _regularized_embeddings(
        self,
        users: torch.Tensor,
        pos_items: torch.Tensor,
        neg_items: torch.Tensor,
    ) -> tuple[torch.Tensor, ...]:
        if self.backbone == "NMF":
            return (
                self.model.user_mf_embedding(users.to(self.device_name)),
                self.model.item_mf_embedding(pos_items.to(self.device_name)),
                self.model.item_mf_embedding(neg_items.to(self.device_name)),
            )
        if self.backbone == "BPRMF":
            return (
                self.model.Gu(users.to(self.device_name)),
                self.model.Gi(pos_items.to(self.device_name)),
                self.model.Gi(neg_items.to(self.device_name)),
            )
        if self.backbone == "ULTRAGCN":
            return (
                self.model.Gu(users.to(self.device_name)),
                self.model.Gi(pos_items.to(self.device_name)),
                self.model.Gi(neg_items.to(self.device_name)),
            )
        if self.backbone == "LGCN":
            return (
                self.model.Gu(users.to(self.device_name)),
                self.model.Gi(pos_items.to(self.device_name)),
                self.model.Gi(neg_items.to(self.device_name)),
            )
        if self.backbone in {"NGCF", "DGCF", "SGL"}:
            user_table, item_table = self._embedding_tables()
            return (
                user_table[users.to(self.device_name)],
                item_table[pos_items.to(self.device_name)],
                item_table[neg_items.to(self.device_name)],
            )
        self._raise_unsupported()

    def _embedding_tables(self, *, evaluate: bool = False) -> tuple[torch.Tensor, torch.Tensor]:
        if self.backbone == "LGCN":
            return self.model.propagate_embeddings(evaluate=evaluate)
        if self.backbone == "NGCF":
            return self.model.propagate_embeddings(self.sparse_graph)
        if self.backbone == "DGCF":
            return self.model.propagate_embeddings()
        if self.backbone == "SGL":
            return self.model.propagate_embeddings(self.sparse_graph)
        self._raise_unsupported()

    def _sgl_loss(
        self,
        users: torch.Tensor,
        pos_items: torch.Tensor,
        neg_items: torch.Tensor,
        pos_scores: torch.Tensor,
        neg_scores: torch.Tensor,
    ) -> torch.Tensor:
        bpr_loss = -F.logsigmoid(pos_scores - neg_scores).sum()
        reg_loss = self.model.l2_loss(
            self.model.Gu.weight[users],
            self.model.Gi.weight[pos_items],
            self.model.Gi.weight[neg_items],
        )
        adj_1 = self._dropout_sparse_graph(drop_rate=0.1)
        adj_2 = self._dropout_sparse_graph(drop_rate=0.1)
        gu1, gi1 = self.model.propagate_embeddings(adj_1, view=True)
        gu2, gi2 = self.model.propagate_embeddings(adj_2, view=True)
        gu1 = F.normalize(gu1, dim=1)
        gi1 = F.normalize(gi1, dim=1)
        gu2 = F.normalize(gu2, dim=1)
        gi2 = F.normalize(gi2, dim=1)
        pos_ratings_user = (gu1[users] * gu2[users]).sum(dim=-1)
        pos_ratings_item = (gi1[pos_items] * gi2[pos_items]).sum(dim=-1)
        ssl_logits_user = torch.matmul(gu1[users], gu2.t()) - pos_ratings_user[:, None]
        ssl_logits_item = torch.matmul(gi1[pos_items], gi2.t()) - pos_ratings_item[:, None]
        infonce_loss = torch.logsumexp(ssl_logits_user / self.model.ssl_temp, dim=1).sum()
        infonce_loss = infonce_loss + torch.logsumexp(ssl_logits_item / self.model.ssl_temp, dim=1).sum()
        return bpr_loss + self.model.ssl_reg * infonce_loss + self.l2_reg * reg_loss

    def _build_model(
        self,
        *,
        lightgcn_layers: int,
        neumf_mlp_dims: tuple[int, ...],
        neumf_dropout: float,
    ) -> nn.Module:
        if self.backbone == "NMF":
            from recommenders.elliot.neural.NeuMF.neural_matrix_factorization_torch_model import (
                NeuralMatrixFactorizationTorchModel,
            )

            return NeuralMatrixFactorizationTorchModel(
                num_users=self.dataset.num_users,
                num_items=self.dataset.num_items,
                embed_mf_size=self.embedding_dim,
                embed_mlp_size=self.embedding_dim,
                mlp_hidden_size=tuple(neumf_mlp_dims),
                dropout=float(neumf_dropout),
                is_mf_train=True,
                is_mlp_train=True,
                learning_rate=0.001,
            )
        if self.backbone == "BPRMF":
            from recommenders.elliot.torch.bprmf import BPRMFModel

            return BPRMFModel(
                num_users=self.dataset.num_users,
                num_items=self.dataset.num_items,
                learning_rate=0.001,
                embed_k=self.embedding_dim,
                l_w=self.l2_reg,
                random_seed=self.seed,
                device=self.device_name,
            )
        if self.backbone == "LGCN":
            from recommenders.elliot.torch.lightgcn import LightGCNModel

            self.sparse_graph = self._sparse_graph()
            return LightGCNModel(
                num_users=self.dataset.num_users,
                num_items=self.dataset.num_items,
                learning_rate=0.001,
                embed_k=self.embedding_dim,
                l_w=self.l2_reg,
                n_layers=lightgcn_layers,
                adj=self.sparse_graph,
                normalize=True,
                random_seed=self.seed,
                device=self.device_name,
            )
        if self.backbone == "NGCF":
            from recommenders.elliot.torch.ngcf import NGCFModel

            self.sparse_graph = self._sparse_graph()
            return NGCFModel(
                num_users=self.dataset.num_users,
                num_items=self.dataset.num_items,
                learning_rate=0.001,
                embed_k=self.embedding_dim,
                l_w=self.l2_reg,
                weight_size=self.embedding_dim,
                n_layers=lightgcn_layers,
                message_dropout=0.1,
                random_seed=self.seed,
                device=self.device_name,
            )
        if self.backbone == "DGCF":
            from recommenders.elliot.torch.dgcf import DGCFModel

            edge_index = self.edge_index.cpu().numpy()
            return DGCFModel(
                num_users=self.dataset.num_users,
                num_items=self.dataset.num_items,
                learning_rate=0.001,
                embed_k=self.embedding_dim,
                l_w_bpr=self.l2_reg,
                l_w_ind=1e-4,
                n_layers=lightgcn_layers,
                intents=4,
                routing_iterations=2,
                edge_index=edge_index,
                random_seed=self.seed,
                device=self.device_name,
            )
        if self.backbone == "SGL":
            from recommenders.elliot.torch.sgl import SGLModel

            self.sparse_graph = self._sparse_graph()
            return SGLModel(
                num_users=self.dataset.num_users,
                num_items=self.dataset.num_items,
                learning_rate=0.001,
                embed_k=self.embedding_dim,
                l_w=self.l2_reg,
                n_layers=lightgcn_layers,
                ssl_temp=0.1,
                ssl_reg=0.1,
                adj=self.sparse_graph,
                sampling="ed",
                random_seed=self.seed,
                device=self.device_name,
            )
        if self.backbone == "ULTRAGCN":
            from recommenders.elliot.torch.ultragcn import UltraGCNModel

            ii_neighbor_mat, ii_constraint_mat, constraint_mat = self._ultragcn_constraints()
            return UltraGCNModel(
                num_users=self.dataset.num_users,
                num_items=self.dataset.num_items,
                learning_rate=0.001,
                embed_k=self.embedding_dim,
                w1=1e-7,
                w2=1.0,
                w3=1.0,
                w4=1.0,
                initial_weight=1e-3,
                negative_num=1,
                negative_weight=200.0,
                ii_neighbor_mat=ii_neighbor_mat,
                ii_constraint_mat=ii_constraint_mat,
                constraint_mat=constraint_mat,
                gamma=self.l2_reg,
                lm=2.75,
                random_seed=self.seed,
                device=self.device_name,
            )
        self._raise_unsupported()

    def _ensure_supported_for_training(self) -> None:
        if self.backbone not in {"BPRMF", "NMF", "LGCN", "NGCF", "DGCF", "SGL", "ULTRAGCN"}:
            self._raise_unsupported()

    def _edge_index(self) -> torch.Tensor:
        rows: list[int] = []
        cols: list[int] = []
        for user, item in self.dataset.interactions:
            item_node = self.dataset.num_users + item
            rows.extend([user, item_node])
            cols.extend([item_node, user])
        return torch.tensor([rows, cols], dtype=torch.long)

    def _sparse_graph(self):
        try:
            from torch_sparse import SparseTensor
        except ModuleNotFoundError as exc:
            raise ModuleNotFoundError(
                "Elliot LGCN/NGCF/SGL adapters require torch_sparse. "
                "Install the PyG dependencies from setup/requirements_cpu.txt or setup/requirements_cuda.txt."
            ) from exc

        edge_index = self.edge_index.to(self.device_name)
        return SparseTensor(
            row=edge_index[0],
            col=edge_index[1],
            sparse_sizes=(
                self.dataset.num_users + self.dataset.num_items,
                self.dataset.num_users + self.dataset.num_items,
            ),
        ).to(self.device_name)

    def _dropout_sparse_graph(self, *, drop_rate: float):
        try:
            from torch_sparse import SparseTensor
        except ModuleNotFoundError as exc:
            raise ModuleNotFoundError(
                "Elliot SGL adapter requires torch_sparse. "
                "Install the PyG dependencies from setup/requirements_cpu.txt or setup/requirements_cuda.txt."
            ) from exc

        edge_index = self.edge_index.to(self.device_name)
        if edge_index.numel() == 0:
            return self.sparse_graph
        keep_mask = torch.rand(edge_index.size(1), device=self.device_name) >= float(drop_rate)
        if not bool(keep_mask.any()):
            keep_mask[torch.randint(edge_index.size(1), (1,), device=self.device_name)] = True
        kept = edge_index[:, keep_mask]
        return SparseTensor(
            row=kept[0],
            col=kept[1],
            sparse_sizes=(
                self.dataset.num_users + self.dataset.num_items,
                self.dataset.num_users + self.dataset.num_items,
            ),
        ).to(self.device_name)

    def _train_interaction_matrix(self) -> sp.csr_matrix:
        rows = [user for user, _ in self.dataset.interactions]
        cols = [item for _, item in self.dataset.interactions]
        data = np.ones(len(rows), dtype=np.float32)
        return sp.csr_matrix(
            (data, (rows, cols)),
            shape=(self.dataset.num_users, self.dataset.num_items),
            dtype=np.float32,
        )

    def _ultragcn_constraints(self) -> tuple[torch.Tensor, torch.Tensor, dict[str, torch.Tensor]]:
        train_mat = self._train_interaction_matrix()
        num_neighbors = min(10, max(1, self.dataset.num_items))
        ii_neighbor_mat, ii_constraint_mat = self._ultragcn_item_constraints(train_mat, num_neighbors)
        items_degree = np.asarray(train_mat.sum(axis=0)).reshape(-1).astype(np.float32)
        users_degree = np.asarray(train_mat.sum(axis=1)).reshape(-1).astype(np.float32)
        users_degree = np.maximum(users_degree, 1.0)
        beta_uD = np.sqrt(users_degree + 1.0) / users_degree
        beta_iD = 1.0 / np.sqrt(items_degree + 1.0)
        constraint_mat = {
            "beta_uD": torch.from_numpy(beta_uD).float().to(self.device_name),
            "beta_iD": torch.from_numpy(beta_iD).float().to(self.device_name),
        }
        return (
            ii_neighbor_mat.to(self.device_name),
            ii_constraint_mat.to(self.device_name),
            constraint_mat,
        )

    def _ultragcn_item_constraints(self, train_mat: sp.csr_matrix, num_neighbors: int) -> tuple[torch.Tensor, torch.Tensor]:
        item_graph = train_mat.T.dot(train_mat).tocsr()
        n_items = item_graph.shape[0]
        neighbor_mat = torch.zeros((n_items, num_neighbors), dtype=torch.long)
        sim_mat = torch.zeros((n_items, num_neighbors), dtype=torch.float32)
        if n_items == 0:
            return neighbor_mat, sim_mat
        item_degree_col = np.asarray(item_graph.sum(axis=0)).reshape(-1).astype(np.float32)
        item_degree_row = np.asarray(item_graph.sum(axis=1)).reshape(-1).astype(np.float32)
        beta_uD = np.sqrt(item_degree_row + 1.0) / np.maximum(item_degree_row, 1.0)
        beta_iD = 1.0 / np.sqrt(item_degree_col + 1.0)
        constraint = beta_uD.reshape(-1, 1) * beta_iD.reshape(1, -1)
        k = min(num_neighbors, n_items)
        for item in range(n_items):
            row = item_graph.getrow(item).toarray().reshape(-1).astype(np.float32)
            scores = torch.from_numpy(row * constraint[item]).float()
            values, indices = torch.topk(scores, k=k)
            neighbor_mat[item, :k] = indices.long()
            sim_mat[item, :k] = values.float()
            if k < num_neighbors:
                neighbor_mat[item, k:] = indices[0].long()
        return neighbor_mat, sim_mat

    def _raise_unsupported(self):
        raise NotImplementedError(
            f"Unsupported Elliot backbone for RecDistill adapter: {self.backbone}. "
            "Supported Elliot PyTorch adapters: BPRMF, NeuMF, LGCN, NGCF, DGCF, SGL, UltraGCN."
        )

backbone = canonical_model_name(backbone) instance-attribute

dataset = dataset instance-attribute

embedding_dim = int(embedding_dim) instance-attribute

l2_reg = float(l2_reg) instance-attribute

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

seed = 42 instance-attribute

edge_index = self._edge_index() instance-attribute

sparse_graph = None instance-attribute

ultragcn_constraints = None instance-attribute

model = self._build_model(lightgcn_layers=(int(lightgcn_layers)), neumf_mlp_dims=neumf_mlp_dims, neumf_dropout=neumf_dropout) instance-attribute

can_score_items_together: bool property

__init__(*, backbone: str, dataset: InteractionDataset, embedding_dim: int, l2_reg: float = 0.0, lightgcn_layers: int = 2, neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8), neumf_dropout: float = 0.0, device: torch.device | str | None = None)

Source code in recdistill/framework_backbone.py
def __init__(
    self,
    *,
    backbone: str,
    dataset: InteractionDataset,
    embedding_dim: int,
    l2_reg: float = 0.0,
    lightgcn_layers: int = 2,
    neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8),
    neumf_dropout: float = 0.0,
    device: torch.device | str | None = None,
):
    super().__init__()
    self.backbone = canonical_model_name(backbone)
    self.dataset = dataset
    self.embedding_dim = int(embedding_dim)
    self.l2_reg = float(l2_reg)
    self.device_name = torch.device(device) if device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
    self.seed = 42
    self.edge_index = self._edge_index()
    self.sparse_graph = None
    self.ultragcn_constraints = None
    self.model = self._build_model(
        lightgcn_layers=int(lightgcn_layers),
        neumf_mlp_dims=neumf_mlp_dims,
        neumf_dropout=neumf_dropout,
    )
    self.model.to(self.device_name)
    if hasattr(self.model, "device"):
        self.model.device = self.device_name

forward(users: torch.Tensor, pos_items: torch.Tensor, neg_items: torch.Tensor) -> FrameworkBatchOutput

Source code in recdistill/framework_backbone.py
def forward(self, users: torch.Tensor, pos_items: torch.Tensor, neg_items: torch.Tensor) -> FrameworkBatchOutput:
    users = users.to(self.device_name)
    pos_items = pos_items.to(self.device_name)
    neg_items = neg_items.to(self.device_name)

    if self.backbone == "ULTRAGCN":
        neg_matrix = neg_items.unsqueeze(1)
        base_loss = self.model.forward(users, pos_items, neg_matrix)
        pos_scores = self._score_pairs(users, pos_items)
        neg_scores = self._score_pairs(users, neg_items)
    elif self.backbone == "SGL":
        user_table, item_table = self._embedding_tables()
        pos_scores = (user_table[users] * item_table[pos_items]).sum(dim=-1)
        neg_scores = (user_table[users] * item_table[neg_items]).sum(dim=-1)
        base_loss = self._sgl_loss(users, pos_items, neg_items, pos_scores, neg_scores)
    else:
        pos_scores = self._score_pairs(users, pos_items)
        neg_scores = self._score_pairs(users, neg_items)
        base_loss = _bpr_loss(
            pos_scores,
            neg_scores,
            l2_reg=self.l2_reg,
            embeddings=self._regularized_embeddings(users, pos_items, neg_items),
        )
    return FrameworkBatchOutput(pos_scores=pos_scores, neg_scores=neg_scores, base_loss=base_loss)

compute_base_loss(batch_output: FrameworkBatchOutput) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def compute_base_loss(self, batch_output: FrameworkBatchOutput) -> torch.Tensor:
    return batch_output.base_loss

score_items(users: torch.Tensor, items: torch.Tensor) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def score_items(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
    users = users.to(self.device_name)
    items = items.to(self.device_name)
    if items.ndim == 1:
        return self._score_pairs(users, items)
    expanded_users = users.unsqueeze(-1).expand(-1, items.size(1))
    return self._score_pairs(expanded_users, items)

score_items_for_user(user: int, num_items: int) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def score_items_for_user(self, user: int, num_items: int) -> torch.Tensor:
    items = torch.arange(num_items, dtype=torch.long, device=self.device_name)
    users = torch.full_like(items, int(user))
    return self.score_items(users, items)

get_all_user_embeddings() -> torch.Tensor

Source code in recdistill/framework_backbone.py
def get_all_user_embeddings(self) -> torch.Tensor:
    if self.backbone == "NMF":
        return self.model.user_mf_embedding.weight
    if self.backbone == "BPRMF":
        return self.model.Gu.weight
    if self.backbone == "ULTRAGCN":
        return self.model.Gu.weight
    user_table, _ = self._embedding_tables(evaluate=True)
    return user_table

get_all_item_embeddings() -> torch.Tensor

Source code in recdistill/framework_backbone.py
def get_all_item_embeddings(self) -> torch.Tensor:
    if self.backbone == "NMF":
        return self.model.item_mf_embedding.weight
    if self.backbone == "BPRMF":
        return self.model.Gi.weight
    if self.backbone == "ULTRAGCN":
        return self.model.Gi.weight
    _, item_table = self._embedding_tables(evaluate=True)
    return item_table

LensKitBackboneAdapter

Bases: Module

Source code in recdistill/framework_backbone.py
class LensKitBackboneAdapter(nn.Module):
    def __init__(
        self,
        *,
        backbone: str,
        dataset: InteractionDataset,
        embedding_dim: int,
        l2_reg: float = 0.0,
        lightgcn_layers: int = 2,
        neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8),
        neumf_dropout: float = 0.0,
        device: torch.device | str | None = None,
    ):
        super().__init__()
        self.backbone = canonical_model_name(backbone)
        self.dataset = dataset
        self.embedding_dim = int(embedding_dim)
        self.l2_reg = float(l2_reg)
        self.device_name = torch.device(device) if device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.model = self._build_model(
            lightgcn_layers=int(lightgcn_layers),
            neumf_mlp_dims=neumf_mlp_dims,
            neumf_dropout=float(neumf_dropout),
        )

    @property
    def can_score_items_together(self) -> bool:
        return self.backbone != "NMF"

    def forward(self, users: torch.Tensor, pos_items: torch.Tensor, neg_items: torch.Tensor) -> FrameworkBatchOutput:
        pos_scores = self._score_pairs(users, pos_items)
        neg_scores = self._score_pairs(users, neg_items)
        base_loss = _bpr_loss(
            pos_scores,
            neg_scores,
            l2_reg=self.l2_reg,
            embeddings=self._regularized_embeddings(users, pos_items, neg_items),
        )
        return FrameworkBatchOutput(pos_scores=pos_scores, neg_scores=neg_scores, base_loss=base_loss)

    def compute_base_loss(self, batch_output: FrameworkBatchOutput) -> torch.Tensor:
        return batch_output.base_loss

    def score_items(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
        if items.ndim == 1:
            return self._score_pairs(users, items)
        expanded_users = users.unsqueeze(-1).expand(-1, items.size(1))
        return self._score_pairs(expanded_users, items)

    def score_items_for_user(self, user: int, num_items: int) -> torch.Tensor:
        items = torch.arange(num_items, dtype=torch.long, device=self.device_name)
        users = torch.full_like(items, int(user))
        return self.score_items(users, items)

    def get_all_user_embeddings(self) -> torch.Tensor:
        if self.backbone == "LGCN":
            embeddings = self.model.get_embedding(self.edge_index)
            return embeddings[: self.dataset.num_users]
        if self.backbone == "BPRMF":
            return self.model.u_embed.weight
        self._raise_unsupported()

    def get_all_item_embeddings(self) -> torch.Tensor:
        if self.backbone == "LGCN":
            embeddings = self.model.get_embedding(self.edge_index)
            return embeddings[self.dataset.num_users :]
        if self.backbone == "BPRMF":
            return self.model.i_embed.weight
        self._raise_unsupported()

    def _score_pairs(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
        users = users.to(self.device_name)
        items = items.to(self.device_name)
        if self.backbone == "BPRMF":
            return self.model(users, items)
        original_shape = users.shape
        edge_label_index = torch.stack(
            [users.reshape(-1), self._item_nodes(items).reshape(-1)],
            dim=0,
        )
        scores = self.model(self.edge_index, edge_label_index)
        return scores.reshape(original_shape)

    def _regularized_embeddings(
        self,
        users: torch.Tensor,
        pos_items: torch.Tensor,
        neg_items: torch.Tensor,
    ) -> tuple[torch.Tensor, ...]:
        users = users.to(self.device_name)
        pos_items = pos_items.to(self.device_name)
        neg_items = neg_items.to(self.device_name)
        if self.backbone == "LGCN":
            return (
                self.model.embedding.weight[users],
                self.model.embedding.weight[self._item_nodes(pos_items)],
                self.model.embedding.weight[self._item_nodes(neg_items)],
            )
        if self.backbone == "BPRMF":
            return (
                self.model.u_embed(users),
                self.model.i_embed(pos_items),
                self.model.i_embed(neg_items),
            )
        self._raise_unsupported()

    def _build_model(
        self,
        *,
        lightgcn_layers: int,
        neumf_mlp_dims: tuple[int, ...],
        neumf_dropout: float,
    ) -> nn.Module:
        if self.backbone == "BPRMF":
            from recommenders.lenskit.flexmf._model import FlexMFModel

            rng = torch.Generator(device="cpu")
            model = FlexMFModel(
                self.embedding_dim,
                self.dataset.num_users,
                self.dataset.num_items,
                rng,
                user_bias=False,
                item_bias=False,
                layers=0,
            )
            nn.init.xavier_normal_(model.u_embed.weight)
            nn.init.xavier_normal_(model.i_embed.weight)
            return model.to(self.device_name)
        if self.backbone == "LGCN":
            from recommenders.lenskit.graphs.lightgcn import LightGCN

            self.edge_index = self._edge_index().to(self.device_name)
            model = LightGCN(
                num_nodes=self.dataset.num_users + self.dataset.num_items,
                embedding_dim=self.embedding_dim,
                num_layers=lightgcn_layers,
            )
            return model.to(self.device_name)
        self._raise_unsupported()

    def _edge_index(self) -> torch.Tensor:
        rows: list[int] = []
        cols: list[int] = []
        for user, item in self.dataset.interactions:
            item_node = self.dataset.num_users + item
            rows.extend([user, item_node])
            cols.extend([item_node, user])
        return torch.tensor([rows, cols], dtype=torch.long)

    def _item_nodes(self, items: torch.Tensor) -> torch.Tensor:
        return items + self.dataset.num_users

    def _raise_unsupported(self):
        raise NotImplementedError(
            f"Unsupported LensKit backbone for RecDistill adapter: {self.backbone}. "
            "LensKit does not provide a native NeuMF implementation in this import; supported: BPRMF, LGCN."
        )

backbone = canonical_model_name(backbone) instance-attribute

dataset = dataset instance-attribute

embedding_dim = int(embedding_dim) instance-attribute

l2_reg = float(l2_reg) instance-attribute

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

model = self._build_model(lightgcn_layers=(int(lightgcn_layers)), neumf_mlp_dims=neumf_mlp_dims, neumf_dropout=(float(neumf_dropout))) instance-attribute

can_score_items_together: bool property

__init__(*, backbone: str, dataset: InteractionDataset, embedding_dim: int, l2_reg: float = 0.0, lightgcn_layers: int = 2, neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8), neumf_dropout: float = 0.0, device: torch.device | str | None = None)

Source code in recdistill/framework_backbone.py
def __init__(
    self,
    *,
    backbone: str,
    dataset: InteractionDataset,
    embedding_dim: int,
    l2_reg: float = 0.0,
    lightgcn_layers: int = 2,
    neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8),
    neumf_dropout: float = 0.0,
    device: torch.device | str | None = None,
):
    super().__init__()
    self.backbone = canonical_model_name(backbone)
    self.dataset = dataset
    self.embedding_dim = int(embedding_dim)
    self.l2_reg = float(l2_reg)
    self.device_name = torch.device(device) if device else torch.device("cuda" if torch.cuda.is_available() else "cpu")
    self.model = self._build_model(
        lightgcn_layers=int(lightgcn_layers),
        neumf_mlp_dims=neumf_mlp_dims,
        neumf_dropout=float(neumf_dropout),
    )

forward(users: torch.Tensor, pos_items: torch.Tensor, neg_items: torch.Tensor) -> FrameworkBatchOutput

Source code in recdistill/framework_backbone.py
def forward(self, users: torch.Tensor, pos_items: torch.Tensor, neg_items: torch.Tensor) -> FrameworkBatchOutput:
    pos_scores = self._score_pairs(users, pos_items)
    neg_scores = self._score_pairs(users, neg_items)
    base_loss = _bpr_loss(
        pos_scores,
        neg_scores,
        l2_reg=self.l2_reg,
        embeddings=self._regularized_embeddings(users, pos_items, neg_items),
    )
    return FrameworkBatchOutput(pos_scores=pos_scores, neg_scores=neg_scores, base_loss=base_loss)

compute_base_loss(batch_output: FrameworkBatchOutput) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def compute_base_loss(self, batch_output: FrameworkBatchOutput) -> torch.Tensor:
    return batch_output.base_loss

score_items(users: torch.Tensor, items: torch.Tensor) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def score_items(self, users: torch.Tensor, items: torch.Tensor) -> torch.Tensor:
    if items.ndim == 1:
        return self._score_pairs(users, items)
    expanded_users = users.unsqueeze(-1).expand(-1, items.size(1))
    return self._score_pairs(expanded_users, items)

score_items_for_user(user: int, num_items: int) -> torch.Tensor

Source code in recdistill/framework_backbone.py
def score_items_for_user(self, user: int, num_items: int) -> torch.Tensor:
    items = torch.arange(num_items, dtype=torch.long, device=self.device_name)
    users = torch.full_like(items, int(user))
    return self.score_items(users, items)

get_all_user_embeddings() -> torch.Tensor

Source code in recdistill/framework_backbone.py
def get_all_user_embeddings(self) -> torch.Tensor:
    if self.backbone == "LGCN":
        embeddings = self.model.get_embedding(self.edge_index)
        return embeddings[: self.dataset.num_users]
    if self.backbone == "BPRMF":
        return self.model.u_embed.weight
    self._raise_unsupported()

get_all_item_embeddings() -> torch.Tensor

Source code in recdistill/framework_backbone.py
def get_all_item_embeddings(self) -> torch.Tensor:
    if self.backbone == "LGCN":
        embeddings = self.model.get_embedding(self.edge_index)
        return embeddings[self.dataset.num_users :]
    if self.backbone == "BPRMF":
        return self.model.i_embed.weight
    self._raise_unsupported()

build_framework_backbone_adapter(*, framework: str, backbone: str, dataset: InteractionDataset, embedding_dim: int, l2_reg: float = 0.0, lightgcn_layers: int = 2, neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8), neumf_dropout: float = 0.0, device: torch.device | str | None = None) -> nn.Module

Source code in recdistill/framework_backbone.py
def build_framework_backbone_adapter(
    *,
    framework: str,
    backbone: str,
    dataset: InteractionDataset,
    embedding_dim: int,
    l2_reg: float = 0.0,
    lightgcn_layers: int = 2,
    neumf_mlp_dims: tuple[int, ...] = (64, 32, 16, 8),
    neumf_dropout: float = 0.0,
    device: torch.device | str | None = None,
) -> nn.Module:
    framework_key = str(framework or "recbole").strip().lower()
    adapter_cls: type[nn.Module]
    if framework_key == "recbole":
        adapter_cls = RecBoleBackboneAdapter
    elif framework_key == "elliot":
        adapter_cls = ElliotBackboneAdapter
    elif framework_key == "lenskit":
        adapter_cls = LensKitBackboneAdapter
    else:
        raise ValueError(f"Unsupported student framework: {framework}. Choose from recbole, elliot, lenskit.")
    return adapter_cls(
        backbone=backbone,
        dataset=dataset,
        embedding_dim=embedding_dim,
        l2_reg=l2_reg,
        lightgcn_layers=lightgcn_layers,
        neumf_mlp_dims=neumf_mlp_dims,
        neumf_dropout=neumf_dropout,
        device=device,
    )

Supported Models

REPORTED_TOTAL_MODELS: dict[str, int] = {'recbole': 91, 'elliot': 64, 'lenskit': 23} module-attribute

REPORTED_TORCH_COMPATIBLE_COUNTS: dict[str, int] = {'recbole': 91, 'elliot': 7, 'lenskit': 5} module-attribute

REPORTED_TORCH_COMPATIBLE_PERCENTAGES: dict[str, str] = {'recbole': '100%', 'elliot': '10.8%', 'lenskit': '21.7%', 'total': '57.9%'} module-attribute

REPORTED_TOTAL_IMPORTED_MODELS = 178 module-attribute

REPORTED_TOTAL_TORCH_COMPATIBLE_MODELS = 103 module-attribute

RECBOLE_TORCH_COMPATIBLE_MODELS: tuple[str, ...] = ('AFM', 'AutoInt', 'DCN', 'DCNV2', 'DeepFM', 'DSSM', 'EulerNet', 'FFM', 'FiGNN', 'FM', 'FNN', 'FwFM', 'KD_DAGFM', 'LR', 'NFM', 'PNN', 'WideDeep', 'xDeepFM', 'ADMMSLIM', 'AsymKNN', 'BPR', 'CDAE', 'ConvNCF', 'DGCF', 'DiffRec', 'DMF', 'EASE', 'ENMF', 'FISM', 'GCMC', 'ItemKNN', 'LightGCN', 'LINE', 'MacridVAE', 'MultiDAE', 'MultiVAE', 'NAIS', 'NCEPLRec', 'NCL', 'NeuMF', 'NGCF', 'NNCF', 'Pop', 'RaCT', 'Random', 'RecVAE', 'SGL', 'SimpleX', 'SLIMElastic', 'SpectralCF', 'CFKG', 'CKE', 'KGAT', 'KGCN', 'KGIN', 'KGNNLS', 'KTUP', 'MCCLK', 'MKR', 'RippleNet', 'BERT4Rec', 'Caser', 'CORE', 'DIEN', 'DIN', 'FDSA', 'FEARec', 'FOSSIL', 'FPMC', 'GCSAN', 'GRU4Rec', 'GRU4RecCPR', 'GRU4RecF', 'GRU4RecKG', 'HGN', 'HRM', 'KSR', 'LightSANs', 'NARM', 'NextItNet', 'NPE', 'RepeatNet', 'S3Rec', 'SASRec', 'SASRecCPR', 'SASRecF', 'SHAN', 'SINE', 'SRGNN', 'STAMP', 'TransRec') module-attribute

ELLIOT_TORCH_COMPATIBLE_MODELS: tuple[str, ...] = ('BPRMF', 'DGCF', 'LightGCN', 'NGCF', 'NeuMFTorch', 'SGL', 'UltraGCN') module-attribute

LENSKIT_TORCH_COMPATIBLE_MODELS: tuple[str, ...] = ('BPR', 'EASEScorer', 'FlexMFExplicitScorer', 'FlexMFImplicitScorer', 'LightGCNScorer') module-attribute

TORCH_COMPATIBLE_IMPORTED_MODELS: tuple[TorchCompatibleModel, ...] = tuple((TorchCompatibleModel('recbole', name)) for name in RECBOLE_TORCH_COMPATIBLE_MODELS) + tuple((TorchCompatibleModel('elliot', name, 'Torch implementation of Elliot NeuMF.')) for name in ELLIOT_TORCH_COMPATIBLE_MODELS) + tuple((TorchCompatibleModel('lenskit', name)) for name in LENSKIT_TORCH_COMPATIBLE_MODELS) module-attribute

TRAINABLE_BACKBONES: tuple[TrainableBackbone, ...] = (TrainableBackbone(framework='recbole', model='BPRMF', aliases=('BPR', 'BPRMF'), adapter='RecBoleBackboneAdapter', implementation='recommenders.recbole.model.general_recommender.bpr.BPR'), TrainableBackbone(framework='recbole', model='LINE', aliases=('LINE',), adapter='RecBoleBackboneAdapter', implementation='recommenders.recbole.model.general_recommender.line.LINE'), TrainableBackbone(framework='recbole', model='LGCN', aliases=('LGCN', 'LightGCN'), adapter='RecBoleBackboneAdapter', implementation='recommenders.recbole.model.general_recommender.lightgcn.LightGCN'), TrainableBackbone(framework='recbole', model='NGCF', aliases=('NGCF',), adapter='RecBoleBackboneAdapter', implementation='recommenders.recbole.model.general_recommender.ngcf.NGCF'), TrainableBackbone(framework='recbole', model='DGCF', aliases=('DGCF',), adapter='RecBoleBackboneAdapter', implementation='recommenders.recbole.model.general_recommender.dgcf.DGCF'), TrainableBackbone(framework='recbole', model='SGL', aliases=('SGL',), adapter='RecBoleBackboneAdapter', implementation='recommenders.recbole.model.general_recommender.sgl.SGL'), TrainableBackbone(framework='recbole', model='SPECTRALCF', aliases=('SpectralCF', 'SPECTRALCF'), adapter='RecBoleBackboneAdapter', implementation='recommenders.recbole.model.general_recommender.spectralcf.SpectralCF'), TrainableBackbone(framework='recbole', model='NMF', aliases=('NMF', 'NeuMF'), adapter='RecBoleBackboneAdapter', implementation='recommenders.recbole.model.general_recommender.neumf.NeuMF'), TrainableBackbone(framework='elliot', model='BPRMF', aliases=('BPR', 'BPRMF'), adapter='ElliotBackboneAdapter', implementation='recommenders.elliot.torch.bprmf.BPRMFModel'), TrainableBackbone(framework='elliot', model='NMF', aliases=('NMF', 'NeuMF'), adapter='ElliotBackboneAdapter', implementation='recommenders.elliot.neural.NeuMF.neural_matrix_factorization_torch_model.NeuralMatrixFactorizationTorchModel'), TrainableBackbone(framework='elliot', model='LGCN', aliases=('LGCN', 'LightGCN'), adapter='ElliotBackboneAdapter', implementation='recommenders.elliot.torch.lightgcn.LightGCNModel'), TrainableBackbone(framework='elliot', model='NGCF', aliases=('NGCF',), adapter='ElliotBackboneAdapter', implementation='recommenders.elliot.torch.ngcf.NGCFModel'), TrainableBackbone(framework='elliot', model='DGCF', aliases=('DGCF',), adapter='ElliotBackboneAdapter', implementation='recommenders.elliot.torch.dgcf.DGCFModel'), TrainableBackbone(framework='elliot', model='SGL', aliases=('SGL',), adapter='ElliotBackboneAdapter', implementation='recommenders.elliot.torch.sgl.SGLModel'), TrainableBackbone(framework='elliot', model='ULTRAGCN', aliases=('UltraGCN', 'ULTRAGCN'), adapter='ElliotBackboneAdapter', implementation='recommenders.elliot.torch.ultragcn.UltraGCNModel'), TrainableBackbone(framework='lenskit', model='BPRMF', aliases=('BPRMF',), adapter='LensKitBackboneAdapter', implementation='recommenders.lenskit.flexmf._model.FlexMFModel', notes='LensKit FlexMF configured as matrix factorization without biases.'), TrainableBackbone(framework='lenskit', model='LGCN', aliases=('LGCN', 'LightGCN'), adapter='LensKitBackboneAdapter', implementation='recommenders.lenskit.graphs.lightgcn.LightGCN')) module-attribute

UNSUPPORTED_KNOWN_BACKBONES: tuple[UnsupportedBackbone, ...] = (UnsupportedBackbone(framework='lenskit', model='NMF', reason='The imported LensKit models do not include a native NeuMF/NMF implementation.', recommended_path='Use RecBole/Elliot NeuMF, or import an external teacher with import_teacher.py.'),) module-attribute

TrainableBackbone dataclass

Source code in recdistill/supported_models.py
@dataclass(frozen=True)
class TrainableBackbone:
    framework: str
    model: str
    aliases: tuple[str, ...]
    adapter: str
    implementation: str
    notes: str = ""

framework: str instance-attribute

model: str instance-attribute

aliases: tuple[str, ...] instance-attribute

adapter: str instance-attribute

implementation: str instance-attribute

notes: str = '' class-attribute instance-attribute

__init__(framework: str, model: str, aliases: tuple[str, ...], adapter: str, implementation: str, notes: str = '') -> None

UnsupportedBackbone dataclass

Source code in recdistill/supported_models.py
@dataclass(frozen=True)
class UnsupportedBackbone:
    framework: str
    model: str
    reason: str
    recommended_path: str

framework: str instance-attribute

model: str instance-attribute

reason: str instance-attribute

recommended_path: str instance-attribute

__init__(framework: str, model: str, reason: str, recommended_path: str) -> None

TorchCompatibleModel dataclass

Source code in recdistill/supported_models.py
@dataclass(frozen=True)
class TorchCompatibleModel:
    framework: str
    name: str
    note: str = ""

framework: str instance-attribute

name: str instance-attribute

note: str = '' class-attribute instance-attribute

__init__(framework: str, name: str, note: str = '') -> None

torch_compatible_by_framework() -> dict[str, list[TorchCompatibleModel]]

Source code in recdistill/supported_models.py
def torch_compatible_by_framework() -> dict[str, list[TorchCompatibleModel]]:
    grouped: dict[str, list[TorchCompatibleModel]] = {}
    for model in TORCH_COMPATIBLE_IMPORTED_MODELS:
        grouped.setdefault(model.framework, []).append(model)
    return grouped

torch_compatible_summary_rows() -> list[dict[str, str]]

Source code in recdistill/supported_models.py
def torch_compatible_summary_rows() -> list[dict[str, str]]:
    rows: list[dict[str, str]] = []
    for framework in ("recbole", "elliot", "lenskit"):
        rows.append(
            {
                "framework": framework,
                "total_imported": str(REPORTED_TOTAL_MODELS[framework]),
                "torch_compatible": str(REPORTED_TORCH_COMPATIBLE_COUNTS[framework]),
                "percentage": REPORTED_TORCH_COMPATIBLE_PERCENTAGES[framework],
            }
        )
    rows.append(
        {
            "framework": "total",
            "total_imported": str(REPORTED_TOTAL_IMPORTED_MODELS),
            "torch_compatible": str(REPORTED_TOTAL_TORCH_COMPATIBLE_MODELS),
            "percentage": REPORTED_TORCH_COMPATIBLE_PERCENTAGES["total"],
        }
    )
    return rows

trainable_by_framework() -> dict[str, list[TrainableBackbone]]

Source code in recdistill/supported_models.py
def trainable_by_framework() -> dict[str, list[TrainableBackbone]]:
    grouped: dict[str, list[TrainableBackbone]] = {}
    for backbone in TRAINABLE_BACKBONES:
        grouped.setdefault(backbone.framework, []).append(backbone)
    return grouped

unsupported_by_framework() -> dict[str, list[UnsupportedBackbone]]

Source code in recdistill/supported_models.py
def unsupported_by_framework() -> dict[str, list[UnsupportedBackbone]]:
    grouped: dict[str, list[UnsupportedBackbone]] = {}
    for backbone in UNSUPPORTED_KNOWN_BACKBONES:
        grouped.setdefault(backbone.framework, []).append(backbone)
    return grouped

Model Registry

MODEL_ALIASES = {'bprmf': 'BPRMF', 'bpr': 'BPRMF', 'line': 'LINE', 'lgcn': 'LGCN', 'lightgcn': 'LGCN', 'ngcf': 'NGCF', 'dgcf': 'DGCF', 'sgl': 'SGL', 'ultragcn': 'ULTRAGCN', 'ultra_gcn': 'ULTRAGCN', 'spectralcf': 'SPECTRALCF', 'spectral_cf': 'SPECTRALCF', 'nmf': 'NMF', 'nfm': 'NMF', 'neumf': 'NMF', 'neumftorch': 'NMF'} module-attribute

DISTILLER_ALIASES = {'de': 'DE', 'distillation_experts': 'DE', 'rrd': 'RRD', 'relaxed_ranking_distillation': 'RRD', 'unkd': 'UNKD', 'unkd_distillation': 'UNKD', 'htd': 'HTD', 'hierarchical_topology_distillation': 'HTD', 'ftd': 'FTD', 'full_topology_distillation': 'FTD'} module-attribute

SUPPORTED_BACKBONES = frozenset({'BPRMF', 'LINE', 'LGCN', 'NGCF', 'DGCF', 'SGL', 'ULTRAGCN', 'SPECTRALCF', 'NMF'}) module-attribute

SUPPORTED_DISTILLERS = frozenset({'DE', 'RRD', 'UNKD', 'HTD', 'FTD'}) module-attribute

canonical_model_name(value: str) -> str

Source code in recdistill/registry.py
def canonical_model_name(value: str) -> str:
    key = _normalize_key(value)
    if key not in MODEL_ALIASES:
        raise ValueError(
            f"Unsupported model/backbone '{value}'. "
            f"Supported aliases: {', '.join(sorted(MODEL_ALIASES))}."
        )
    return MODEL_ALIASES[key]

canonical_distiller_name(value: str) -> str

Source code in recdistill/registry.py
def canonical_distiller_name(value: str) -> str:
    key = _normalize_key(value)
    if key not in DISTILLER_ALIASES:
        raise ValueError(
            f"Unsupported distiller '{value}'. "
            f"Supported aliases: {', '.join(sorted(DISTILLER_ALIASES))}."
        )
    return DISTILLER_ALIASES[key]

parse_distiller_methods(value: str | None) -> tuple[str, ...]

Source code in recdistill/registry.py
def parse_distiller_methods(value: str | None) -> tuple[str, ...]:
    if value is None:
        return ()
    raw = str(value).strip()
    if _normalize_key(raw) in DISTILLER_ALIASES:
        return (canonical_distiller_name(raw),)
    normalized = raw.replace("-", "_").replace("+", "_")
    if not normalized:
        return ()
    return tuple(canonical_distiller_name(part) for part in normalized.split("_") if part)

distiller_slug(value: str | None) -> str

Source code in recdistill/registry.py
def distiller_slug(value: str | None) -> str:
    methods = parse_distiller_methods(value)
    if not methods:
        return "none"
    return "_".join(method.lower() for method in methods)

model_slug(value: str) -> str

Source code in recdistill/registry.py
def model_slug(value: str) -> str:
    return canonical_model_name(value).lower()

Model Validation

EMBEDDING_DISTILLERS = frozenset({'DE', 'HTD', 'FTD'}) module-attribute

SCORING_DISTILLERS = frozenset({'RRD', 'UNKD'}) module-attribute

TOPOLOGY_DISTILLERS = frozenset({'HTD', 'FTD'}) module-attribute

DE_FIXED_DIM_UNSAFE_STUDENTS = frozenset({('elliot', 'ngcf'), ('recbole', 'ngcf'), ('recbole', 'spectralcf')}) module-attribute

validate_trainable_model(framework: str, model: str, *, role: str = 'model') -> str

Return the canonical model name if the framework/model pair is trainable by RecDistill.

Source code in recdistill/model_validation.py
def validate_trainable_model(framework: str, model: str, *, role: str = "model") -> str:
    """Return the canonical model name if the framework/model pair is trainable by RecDistill."""
    framework_key = _framework_key(framework)
    if model is None or not str(model).strip():
        raise ValueError(f"Missing {role}. Available {framework_key} models: {_available_models(framework_key)}.")
    raw_model = str(model).strip()
    model_key = _model_key(raw_model)

    for backbone in TRAINABLE_BACKBONES:
        if backbone.framework == framework_key and model_key in {_model_key(backbone.model), *map(_model_key, backbone.aliases)}:
            return backbone.model

    canonical = _canonical_or_raw(raw_model)
    unsupported = _unsupported_entry(framework_key, canonical)
    if unsupported is not None:
        raise ValueError(
            f"{role} '{raw_model}' cannot be trained with the RecDistill PyTorch loop for framework '{framework_key}'. "
            f"Reason: {unsupported.reason} Recommended path: {unsupported.recommended_path}"
        )

    other_frameworks = sorted(
        {
            backbone.framework
            for backbone in TRAINABLE_BACKBONES
            if model_key in {_model_key(backbone.model), *map(_model_key, backbone.aliases)}
        }
    )
    if other_frameworks:
        raise ValueError(
            f"{role} '{raw_model}' is not adapter-backed for framework '{framework_key}'. "
            f"It is currently available for: {', '.join(other_frameworks)}. "
            f"Available {framework_key} models: {_available_models(framework_key)}."
        )

    if _is_torch_compatible_import(framework_key, raw_model):
        raise ValueError(
            f"{role} '{raw_model}' from framework '{framework_key}' is torch-compatible in the imported definitions, "
            "but no RecDistill training adapter is currently wired for it. "
            f"Available adapter-backed {framework_key} models: {_available_models(framework_key)}."
        )

    raise ValueError(
        f"{role} '{raw_model}' is not available as a RecDistill PyTorch-trainable model for framework '{framework_key}'. "
        f"Available adapter-backed {framework_key} models: {_available_models(framework_key)}."
    )

validate_distillation_request(*, teacher_framework: str | None, teacher_model: str | None, student_framework: str, student_backbone: str, distiller: str, validate_teacher: bool = True) -> tuple[str | None, str]

Validate a composed distillation run and return canonical teacher/student names.

Source code in recdistill/model_validation.py
def validate_distillation_request(
    *,
    teacher_framework: str | None,
    teacher_model: str | None,
    student_framework: str,
    student_backbone: str,
    distiller: str,
    validate_teacher: bool = True,
) -> tuple[str | None, str]:
    """Validate a composed distillation run and return canonical teacher/student names."""
    if distiller is None or not str(distiller).strip():
        raise ValueError("Distillation strategy is required. Choose one of: DE, RRD, UnKD, HTD, FTD.")
    canonical_teacher = None
    if validate_teacher and teacher_model:
        canonical_teacher = validate_trainable_model(
            teacher_framework or "recbole",
            teacher_model,
            role="teacher model",
        )
    canonical_student = validate_trainable_model(
        student_framework,
        student_backbone,
        role="student backbone",
    )

    try:
        methods = set(parse_distiller_methods(distiller))
    except ValueError as exc:
        raise ValueError(f"Unsupported distillation strategy '{distiller}'. {exc}") from exc
    if not methods:
        raise ValueError("Distillation strategy must contain at least one method.")
    if TOPOLOGY_DISTILLERS.issubset(methods):
        raise ValueError("Incompatible distillation strategy: HTD and FTD cannot be active at the same time.")
    _validate_student_backbone_distiller(
        student_framework=student_framework,
        student_backbone=canonical_student,
        methods=methods,
    )

    # Adapter capability constraints. All currently trainable backbones expose embeddings and pair scoring,
    # but keep this check explicit so new adapters fail early with a useful message.
    if methods & EMBEDDING_DISTILLERS and canonical_student is None:
        raise ValueError("DE/HTD/FTD require an embedding-based student backbone.")
    if methods & SCORING_DISTILLERS and canonical_student is None:
        raise ValueError("RRD/UnKD require a student backbone that can score user-item pairs.")
    return canonical_teacher, canonical_student

validate_recdistill_config_dict(config: dict) -> None

Source code in recdistill/model_validation.py
def validate_recdistill_config_dict(config: dict) -> None:
    train_conf = config.get("distill_student", {})
    teacher_conf = train_conf.get("teacher", {}) or {}
    student_conf = train_conf.get("student", {}) or {}
    distill_conf = train_conf.get("distillation", {}) or {}
    strategy = distill_conf.get("strategy")
    validate_distillation_request(
        teacher_framework=teacher_conf.get("framework", "recbole"),
        teacher_model=teacher_conf.get("model"),
        student_framework=student_conf.get("framework", "recbole"),
        student_backbone=student_conf.get("backbone"),
        distiller=strategy,
        validate_teacher=not bool(teacher_conf.get("path")),
    )
    validate_teacher_representation_request(
        teacher_conf=teacher_conf,
        distiller=strategy,
    )

validate_teacher_representation_request(*, teacher_conf: dict, distiller: str | None) -> None

Source code in recdistill/model_validation.py
def validate_teacher_representation_request(*, teacher_conf: dict, distiller: str | None) -> None:
    try:
        methods = set(parse_distiller_methods(distiller))
    except ValueError:
        return
    if not methods:
        return

    representations = _declared_teacher_representations(teacher_conf)
    _validate_teacher_representation_shape(teacher_conf, representations)

    if len(representations) > 1:
        raise ValueError(
            "Ambiguous teacher representation: the config declares multiple teacher formats "
            f"({', '.join(sorted(representations))}). Choose exactly one of embeddings, scores, or top-k/ranking."
        )

    if not (methods & EMBEDDING_DISTILLERS):
        return

    representation = next(iter(representations), None)
    if representation in {"scores", "topk", "ranking"}:
        raise ValueError(
            f"Incompatible teacher representation/distiller: {', '.join(sorted(methods & EMBEDDING_DISTILLERS))} "
            f"requires an embedding-based teacher, but the config declares a {representation}-based teacher. "
            "Use RRD or UnKD with score/ranking teachers, or provide/import user and item embeddings."
        )

validate_loaded_teacher_for_distillation(teacher_state, distiller: str | None) -> None

Source code in recdistill/model_validation.py
def validate_loaded_teacher_for_distillation(teacher_state, distiller: str | None) -> None:
    methods = set(parse_distiller_methods(distiller))
    if methods & EMBEDDING_DISTILLERS and not bool(getattr(teacher_state, "has_embeddings", False)):
        available = "score/ranking scorer" if getattr(teacher_state, "scorer", None) is not None else "no embedding representation"
        raise ValueError(
            f"Incompatible loaded teacher/distiller: {', '.join(sorted(methods & EMBEDDING_DISTILLERS))} "
            f"requires user/item embeddings, but the loaded teacher provides {available}. "
            "Use RRD or UnKD with score/ranking teachers, or import an embedding-based .teacher."
        )