Skip to content

API Reference

This page collects the core public modules that are used across the RecDistillery runtime. Topic-specific pages contain the same APIs grouped by workflow.

Core Runtime

RecDistill configuration integration with the new centralized config system.

load_recdistill_config_from_file(config_path: Union[str, Path]) -> RecDistillConfig

Load and validate RecDistill configuration from YAML file.

Parameters:

Name Type Description Default
config_path Union[str, Path]

Path to configuration YAML file

required

Returns:

Type Description
RecDistillConfig

Validated RecDistillConfig object

Raises:

Type Description
FileNotFoundError

If config file doesn't exist

ValidationError

If config doesn't match schema

Source code in recdistill/config_integration.py
def load_recdistill_config_from_file(config_path: Union[str, Path]) -> RecDistillConfig:
    """
    Load and validate RecDistill configuration from YAML file.

    Args:
        config_path: Path to configuration YAML file

    Returns:
        Validated RecDistillConfig object

    Raises:
        FileNotFoundError: If config file doesn't exist
        ValidationError: If config doesn't match schema
    """
    path = Path(config_path)
    if not path.exists():
        raise FileNotFoundError(f"Configuration file not found: {path}")

    with path.open("r", encoding="utf-8") as fp:
        raw_config = yaml.safe_load(fp) or {}

    normalized = normalize_recdistill_config(raw_config)
    return RecDistillConfig(**normalized)

load_recdistill_experiment(dataset_name: str, teacher_model: str, distiller_strategy: str, student_backbone: Optional[str] = None, teacher_framework: str = 'recbole', student_framework: str = 'recbole', overrides: Optional[Dict[str, Any]] = None) -> RecDistillConfig

Programmatically load RecDistill experiment with centralized configurations.

Parameters:

Name Type Description Default
dataset_name str

Dataset name (amazon_cd, bookcrossing, citeulike)

required
teacher_model str

Teacher model (bprmf, nmf, lgcn)

required
distiller_strategy str

Distillation strategy (de, htd, ftd, unkd)

required
student_backbone Optional[str]

Student backbone (default: same as teacher)

None
overrides Optional[Dict[str, Any]]

Dict of configuration overrides

None

Returns:

Type Description
RecDistillConfig

Validated RecDistillConfig object

Example

config = load_recdistill_experiment( ... dataset_name='citeulike', ... teacher_model='nmf', ... distiller_strategy='de', ... overrides={ ... 'distill_student.optimization.epochs': 50, ... 'distill_student.runtime.seed': 123 ... } ... )

Source code in recdistill/config_integration.py
def load_recdistill_experiment(
    dataset_name: str,
    teacher_model: str,
    distiller_strategy: str,
    student_backbone: Optional[str] = None,
    teacher_framework: str = "recbole",
    student_framework: str = "recbole",
    overrides: Optional[Dict[str, Any]] = None
) -> RecDistillConfig:
    """
    Programmatically load RecDistill experiment with centralized configurations.

    Args:
        dataset_name: Dataset name (amazon_cd, bookcrossing, citeulike)
        teacher_model: Teacher model (bprmf, nmf, lgcn)
        distiller_strategy: Distillation strategy (de, htd, ftd, unkd)
        student_backbone: Student backbone (default: same as teacher)
        overrides: Dict of configuration overrides

    Returns:
        Validated RecDistillConfig object

    Example:
        >>> config = load_recdistill_experiment(
        ...     dataset_name='citeulike',
        ...     teacher_model='nmf',
        ...     distiller_strategy='de',
        ...     overrides={
        ...         'distill_student.optimization.epochs': 50,
        ...         'distill_student.runtime.seed': 123
        ...     }
        ... )
    """
    if student_backbone is None:
        student_backbone = teacher_model

    loader = get_config_loader()
    config_dict = loader.compose_recdistill_experiment(
        dataset_name=dataset_name,
        teacher_model=teacher_model,
        distiller_strategy=distiller_strategy,
        student_backbone=student_backbone,
        teacher_framework=teacher_framework,
        student_framework=student_framework,
    )

    # Apply overrides if provided
    if overrides:
        config_dict = _apply_overrides(config_dict, overrides)

    return RecDistillConfig(**normalize_recdistill_config(config_dict))

normalize_recdistill_config(config: Dict[str, Any]) -> Dict[str, Any]

Normalize RecDistill config dictionaries into RecDistillConfig shape.

Source code in recdistill/config_integration.py
def normalize_recdistill_config(config: Dict[str, Any]) -> Dict[str, Any]:
    """
    Normalize RecDistill config dictionaries into RecDistillConfig shape.
    """
    if isinstance(config, dict) and "preset" in config and "config" in config:
        config = config["config"]

    if isinstance(config, dict):
        config = get_config_loader().resolve_config_modules(config)

    normalized = copy.deepcopy(config or {})
    if "distill_student" not in normalized:
        raise ValueError("RecDistill configs must define a top-level 'distill_student' block.")
    train_conf = normalized.get("distill_student") or {}
    normalized["distill_student"] = train_conf

    student_conf = train_conf.setdefault("student", {})
    teacher_conf = train_conf.setdefault("teacher", {})
    distill_conf = train_conf.setdefault("distillation", {})

    strategy = (
        distill_conf.get("strategy")
        or _infer_strategy_from_distillation_block(distill_conf)
        or "DE"
    )
    strategy = str(strategy).replace("-", "_").upper()
    distill_conf["strategy"] = strategy
    student_conf.pop("model", None)
    active_methods = {part for part in strategy.replace("+", "_").split("_") if part}
    if "DE" not in active_methods:
        distill_conf["lambda_de"] = 0.0

    if "model" in teacher_conf and teacher_conf["model"] is not None:
        teacher_conf["model"] = str(teacher_conf["model"]).upper()
    if "backbone" in student_conf and student_conf["backbone"] is not None:
        student_conf["backbone"] = str(student_conf["backbone"]).upper()

    for key in (
        "temperature",
        "lambda_de",
        "lambda_kl",
        "lambda_rrd",
        "lambda_unkd",
        "num_experts",
    ):
        if key in student_conf and key not in distill_conf:
            distill_conf[key] = student_conf[key]

    optimization_conf = train_conf.setdefault("optimization", {})
    if "early_stopping" in train_conf:
        raise ValueError("Use distill_student.optimization.early_stopping, not distill_student.early_stopping.")
    optimization_conf.setdefault("early_stopping", {})
    train_conf.setdefault("runtime", {})
    train_conf.setdefault("evaluation", {})
    return normalized

recdistill_config_to_dict(config: Union[RecDistillConfig, Dict[str, Any]]) -> Dict[str, Any]

Return a plain normalized dictionary for runner code.

Source code in recdistill/config_integration.py
def recdistill_config_to_dict(config: Union[RecDistillConfig, Dict[str, Any]]) -> Dict[str, Any]:
    """Return a plain normalized dictionary for runner code."""
    if isinstance(config, RecDistillConfig):
        return config.model_dump()
    return normalize_recdistill_config(config)

get_default_dataset_path(dataset_name: str, file_type: str = 'train') -> str

Get default data path for a dataset.

Parameters:

Name Type Description Default
dataset_name str

Dataset name

required
file_type str

'train', 'val', or 'test'

'train'

Returns:

Type Description
str

Path to dataset file

Example

path = get_default_dataset_path('citeulike', 'train') print(path) data/citeulike/train.tsv

Source code in recdistill/config_integration.py
def get_default_dataset_path(dataset_name: str, file_type: str = 'train') -> str:
    """
    Get default data path for a dataset.

    Args:
        dataset_name: Dataset name
        file_type: 'train', 'val', or 'test'

    Returns:
        Path to dataset file

    Example:
        >>> path = get_default_dataset_path('citeulike', 'train')
        >>> print(path)
        data/citeulike/train.tsv
    """
    loader = get_config_loader()
    dataset_cfg = loader.load_dataset_config(dataset_name)

    if file_type == 'train':
        return dataset_cfg.train_path
    elif file_type == 'val':
        return dataset_cfg.validation_path or dataset_cfg.train_path
    elif file_type == 'test':
        return dataset_cfg.test_path
    else:
        raise ValueError(f"Unknown file_type: {file_type}")

print_config_summary(config: RecDistillConfig) -> None

Print a summary of RecDistill configuration.

Parameters:

Name Type Description Default
config RecDistillConfig

RecDistillConfig object

required
Source code in recdistill/config_integration.py
def print_config_summary(config: RecDistillConfig) -> None:
    """
    Print a summary of RecDistill configuration.

    Args:
        config: RecDistillConfig object
    """
    train_cfg = config.distill_student

    print("\n" + "=" * 70)
    print("RECDISTILL CONFIGURATION SUMMARY")
    print("=" * 70)

    print("\n📊 DATA")
    print(f"  Dataset: {train_cfg.dataset}")

    print("\n👨‍🏫 TEACHER")
    print(f"  Model: {train_cfg.teacher.model}")
    print(f"  Embedding Dim: {train_cfg.teacher.embedding_dim}")
    print(f"  Path: {train_cfg.teacher.path or 'Not specified (will be auto-located)'}")

    print("\n👨‍🎓 STUDENT")
    print(f"  Backbone: {train_cfg.student.backbone}")
    print(f"  Distiller: {train_cfg.distillation.strategy}")
    print(f"  Embedding Dim: {train_cfg.student.embedding_dim}")

    print("\n🔬 DISTILLATION")
    print(f"  Strategy: {train_cfg.distillation.strategy}")
    print(f"  Temperature: {train_cfg.distillation.temperature}")
    if hasattr(train_cfg.distillation, 'lambda_kl'):
        print(f"  Lambda KL: {train_cfg.distillation.lambda_kl}")
    if hasattr(train_cfg.distillation, 'lambda_de'):
        print(f"  Lambda DE: {train_cfg.distillation.lambda_de}")

    print("\n⚙️  OPTIMIZATION")
    print(f"  Epochs: {train_cfg.optimization.epochs}")
    print(f"  Batch Size: {train_cfg.optimization.batch_size}")
    print(f"  Learning Rate: {train_cfg.optimization.learning_rate}")
    print(f"  L2 Reg: {train_cfg.optimization.l2_reg}")

    print("\n🏃 RUNTIME")
    print(f"  Seed: {train_cfg.runtime.seed}")
    print(f"  Device: {train_cfg.runtime.device or 'Auto (cuda if available)'}")
    print(f"  Num Workers: {train_cfg.runtime.num_workers}")
    print(f"  Output Path: {train_cfg.runtime.output_path}")
    if train_cfg.runtime.wandb.get('enabled'):
        print(f"  W&B: Enabled")

    print("\n📈 EVALUATION")
    print(f"  K: {train_cfg.evaluation.k}")
    print(f"  Every N epochs: {train_cfg.evaluation.every}")
    print(f"  Validation Only: {train_cfg.evaluation.val_only}")
    print(f"  Selection Metric: {train_cfg.evaluation.selection_metric}")

    print("\n⏸️  EARLY STOPPING")
    early_stopping = train_cfg.optimization.early_stopping
    if early_stopping:
        print(f"  Enabled: {early_stopping.enabled}")
        print(f"  Metric: {early_stopping.metric}")
        print(f"  Patience: {early_stopping.patience}")
        print(f"  Min Delta: {early_stopping.min_delta}")
    else:
        print(f"  Disabled")

    print("\n" + "=" * 70 + "\n")

validate_config(config: RecDistillConfig) -> bool

Validate RecDistill configuration for common issues.

Parameters:

Name Type Description Default
config RecDistillConfig

RecDistillConfig object

required

Returns:

Type Description
bool

True if configuration is valid, False otherwise

Source code in recdistill/config_integration.py
def validate_config(config: RecDistillConfig) -> bool:
    """
    Validate RecDistill configuration for common issues.

    Args:
        config: RecDistillConfig object

    Returns:
        True if configuration is valid, False otherwise
    """
    train_cfg = config.distill_student
    issues = []

    # Check embedding dimensions
    if train_cfg.student.embedding_dim >= train_cfg.teacher.embedding_dim:
        issues.append(
            f"⚠️  Student embedding dim ({train_cfg.student.embedding_dim}) "
            f"should be smaller than teacher ({train_cfg.teacher.embedding_dim})"
        )

    # Check early stopping if enabled
    early_stopping = train_cfg.optimization.early_stopping
    if early_stopping and early_stopping.enabled:
        if early_stopping.patience > train_cfg.optimization.epochs:
            issues.append(
                f"Early stopping patience ({early_stopping.patience}) "
                f"should be smaller than total epochs ({train_cfg.optimization.epochs})"
            )

    if issues:
        print("\n⚠️  Configuration warnings:")
        for issue in issues:
            print(f"  {issue}")
        return False

    print("Configuration validation passed.")
    return True

list_example_experiments() -> None

Print available pre-configured experiments.

Source code in recdistill/config_integration.py
def list_example_experiments() -> None:
    """Print available pre-configured experiments."""
    loader = get_config_loader()

    print("\n" + "=" * 70)
    print("AVAILABLE EXPERIMENTS")
    print("=" * 70)

    datasets = loader.list_datasets()
    models = loader.list_models()
    distillers = loader.list_distillers()

    print("\nPredefine combinations:")
    for dataset in datasets:
        for distiller in distillers:
            for teacher in models['teacher']:
                print(f"  python train_distiller.py \\")
                print(f"    --dataset {dataset} \\")
                print(f"    --teacher {teacher} \\")
                print(f"    --distiller {distiller}")

    print("\n" + "=" * 70 + "\n")

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)

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,
    )

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."
        )

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_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()

Experiment Runtime

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

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)

evaluate_embeddings(user_embeddings: torch.Tensor, item_embeddings: torch.Tensor, train_seen: dict[int, set[int]], ground_truth: dict[int, set[int]], top_k: int, batch_size: int, device: torch.device, scorer: TeacherScorer | None = None) -> tuple[dict[str, float], int]

Evaluate top-k recommendations from embeddings or a scorer.

Parameters:

Name Type Description Default
user_embeddings Tensor

User embedding matrix, or None when scorer can score users directly.

required
item_embeddings Tensor

Item embedding matrix, or None for scorer-only teachers.

required
train_seen dict[int, set[int]]

Training items keyed by user. These items are masked before ranking.

required
ground_truth dict[int, set[int]]

Held-out target items keyed by user.

required
top_k int

Recommendation cutoff.

required
batch_size int

Number of users per embedding-ranking batch.

required
device device

Torch device used for score computation.

required
scorer TeacherScorer | None

Optional object implementing score_items_for_user.

None

Returns:

Type Description
dict[str, float]

A pair containing the metric dictionary and the number of users whose

int

raw top-k list still contained a training item before final filtering.

Source code in recdistill/evaluation.py
def evaluate_embeddings(
    user_embeddings: torch.Tensor,
    item_embeddings: torch.Tensor,
    train_seen: dict[int, set[int]],
    ground_truth: dict[int, set[int]],
    top_k: int,
    batch_size: int,
    device: torch.device,
    scorer: TeacherScorer | None = None,
) -> tuple[dict[str, float], int]:
    """Evaluate top-k recommendations from embeddings or a scorer.

    Args:
        user_embeddings: User embedding matrix, or `None` when `scorer` can
            score users directly.
        item_embeddings: Item embedding matrix, or `None` for scorer-only
            teachers.
        train_seen: Training items keyed by user. These items are masked before
            ranking.
        ground_truth: Held-out target items keyed by user.
        top_k: Recommendation cutoff.
        batch_size: Number of users per embedding-ranking batch.
        device: Torch device used for score computation.
        scorer: Optional object implementing `score_items_for_user`.

    Returns:
        A pair containing the metric dictionary and the number of users whose
        raw top-k list still contained a training item before final filtering.
    """
    eval_users = sorted(user for user, items in ground_truth.items() if items)
    if not eval_users:
        return _metrics_at_k({}, ground_truth, top_k), 0

    recommendations, leaked_users = _build_topk_recommendations(
        user_embeddings=user_embeddings,
        item_embeddings=item_embeddings,
        users=eval_users,
        train_seen=train_seen,
        top_k=top_k,
        batch_size=batch_size,
        device=device,
        scorer=scorer,
    )
    return _metrics_at_k(recommendations, ground_truth, top_k), leaked_users

evaluate_teacher(teacher_state: TeacherState, train_seen: dict[int, set[int]], val_gt: dict[int, set[int]], test_gt: dict[int, set[int]], top_k: int, batch_size: int, device: torch.device, eval_val_only: bool = False) -> dict[str, dict[str, float] | int]

Evaluate a serialized or imported teacher on validation/test splits.

The teacher may expose either user/item embeddings or a scorer-only representation such as a precomputed score matrix or top-k predictions. Training interactions are masked before ranking so the metrics are computed only over unseen candidate items.

Parameters:

Name Type Description Default
teacher_state TeacherState

Runtime teacher representation loaded from a .teacher artifact or an import adapter.

required
train_seen dict[int, set[int]]

Mapping from user index to training items that must be removed from the ranked candidate set.

required
val_gt dict[int, set[int]]

Validation ground-truth items keyed by user index.

required
test_gt dict[int, set[int]]

Test ground-truth items keyed by user index.

required
top_k int

Recommendation cutoff used by precision, recall, NDCG and hit ratio.

required
batch_size int

Number of users evaluated per embedding-ranking batch.

required
device device

Torch device used for score computation.

required
eval_val_only bool

When True, skip the test split and return validation metrics only.

False

Returns:

Type Description
dict[str, dict[str, float] | int]

A dictionary with split metrics and train-leakage counters. The metric

dict[str, dict[str, float] | int]

dictionaries contain users, precision, recall, ndcg, and hr.

Source code in recdistill/evaluation.py
def evaluate_teacher(
    teacher_state: TeacherState,
    train_seen: dict[int, set[int]],
    val_gt: dict[int, set[int]],
    test_gt: dict[int, set[int]],
    top_k: int,
    batch_size: int,
    device: torch.device,
    eval_val_only: bool = False,
) -> dict[str, dict[str, float] | int]:
    """Evaluate a serialized or imported teacher on validation/test splits.

    The teacher may expose either user/item embeddings or a scorer-only
    representation such as a precomputed score matrix or top-k predictions.
    Training interactions are masked before ranking so the metrics are computed
    only over unseen candidate items.

    Args:
        teacher_state: Runtime teacher representation loaded from a `.teacher`
            artifact or an import adapter.
        train_seen: Mapping from user index to training items that must be
            removed from the ranked candidate set.
        val_gt: Validation ground-truth items keyed by user index.
        test_gt: Test ground-truth items keyed by user index.
        top_k: Recommendation cutoff used by precision, recall, NDCG and hit
            ratio.
        batch_size: Number of users evaluated per embedding-ranking batch.
        device: Torch device used for score computation.
        eval_val_only: When `True`, skip the test split and return validation
            metrics only.

    Returns:
        A dictionary with split metrics and train-leakage counters. The metric
        dictionaries contain `users`, `precision`, `recall`, `ndcg`, and `hr`.
    """
    val_metrics, val_leaks = evaluate_embeddings(
        user_embeddings=teacher_state.user_embeddings,
        item_embeddings=teacher_state.item_embeddings,
        train_seen=train_seen,
        ground_truth=val_gt,
        top_k=top_k,
        batch_size=batch_size,
        device=device,
        scorer=teacher_state.scorer,
    )
    if eval_val_only:
        return {"val": val_metrics, "leaked_users_val": val_leaks}
    test_metrics, test_leaks = evaluate_embeddings(
        user_embeddings=teacher_state.user_embeddings,
        item_embeddings=teacher_state.item_embeddings,
        train_seen=train_seen,
        ground_truth=test_gt,
        top_k=top_k,
        batch_size=batch_size,
        device=device,
        scorer=teacher_state.scorer,
    )
    return {
        "val": val_metrics,
        "test": test_metrics,
        "leaked_users_val": val_leaks,
        "leaked_users_test": test_leaks,
    }

evaluate_student(model: torch.nn.Module, train_seen: dict[int, set[int]], val_gt: dict[int, set[int]], test_gt: dict[int, set[int]], top_k: int, batch_size: int, device: torch.device, eval_val_only: bool = False) -> dict[str, dict[str, float] | int]

Evaluate a trained student model on validation and test splits.

The student must expose get_all_user_embeddings and get_all_item_embeddings. If it also implements score_items_for_user, that scorer is used for ranking.

Source code in recdistill/evaluation.py
def evaluate_student(
    model: torch.nn.Module,
    train_seen: dict[int, set[int]],
    val_gt: dict[int, set[int]],
    test_gt: dict[int, set[int]],
    top_k: int,
    batch_size: int,
    device: torch.device,
    eval_val_only: bool = False,
) -> dict[str, dict[str, float] | int]:
    """Evaluate a trained student model on validation and test splits.

    The student must expose `get_all_user_embeddings` and
    `get_all_item_embeddings`. If it also implements `score_items_for_user`,
    that scorer is used for ranking.
    """
    model.eval()
    user_embeddings = model.get_all_user_embeddings().detach()
    item_embeddings = model.get_all_item_embeddings().detach()
    scorer = model if hasattr(model, "score_items_for_user") else None
    val_metrics, val_leaks = evaluate_embeddings(
        user_embeddings=user_embeddings,
        item_embeddings=item_embeddings,
        train_seen=train_seen,
        ground_truth=val_gt,
        top_k=top_k,
        batch_size=batch_size,
        device=device,
        scorer=scorer,
    )
    if eval_val_only:
        return {"val": val_metrics, "leaked_users_val": val_leaks}
    test_metrics, test_leaks = evaluate_embeddings(
        user_embeddings=user_embeddings,
        item_embeddings=item_embeddings,
        train_seen=train_seen,
        ground_truth=test_gt,
        top_k=top_k,
        batch_size=batch_size,
        device=device,
        scorer=scorer,
    )
    return {
        "val": val_metrics,
        "test": test_metrics,
        "leaked_users_val": val_leaks,
        "leaked_users_test": test_leaks,
    }

STUDENT_CHECKPOINT_FORMAT = 'recdistill.student.v1' module-attribute

config_hash(config: dict[str, Any] | None) -> str | None

Source code in recdistill/checkpointing.py
def config_hash(config: dict[str, Any] | None) -> str | None:
    if config is None:
        return None
    encoded = json.dumps(config, sort_keys=True, default=str, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()

current_git_commit(repo_root: Path | None = None) -> str | None

Source code in recdistill/checkpointing.py
def current_git_commit(repo_root: Path | None = None) -> str | None:
    repo_root = repo_root or Path(__file__).resolve().parents[1]
    try:
        result = subprocess.run(
            ["git", "rev-parse", "HEAD"],
            cwd=repo_root,
            check=True,
            capture_output=True,
            text=True,
        )
    except Exception:
        return None
    commit = result.stdout.strip()
    return commit or None

enrich_student_checkpoint_payload(payload: dict[str, Any]) -> dict[str, Any]

Source code in recdistill/checkpointing.py
def enrich_student_checkpoint_payload(payload: dict[str, Any]) -> dict[str, Any]:
    config = payload.get("config") if isinstance(payload.get("config"), dict) else {}
    enriched = dict(payload)
    enriched.setdefault("format_version", STUDENT_CHECKPOINT_FORMAT)
    enriched.setdefault("created_at_utc", utc_now_iso())
    enriched.setdefault("config_hash", config_hash(config))
    enriched.setdefault("git_commit", current_git_commit())
    enriched.setdefault("dataset", config.get("dataset"))
    enriched.setdefault("teacher", config.get("teacher_model"))
    enriched.setdefault("student", config.get("student_backbone"))
    enriched.setdefault("distiller", _distiller_from_config(config))
    metadata = dict(enriched.get("metadata") or {})
    metadata.setdefault("format_version", enriched["format_version"])
    metadata.setdefault("created_at_utc", enriched["created_at_utc"])
    metadata.setdefault("config_hash", enriched["config_hash"])
    metadata.setdefault("git_commit", enriched["git_commit"])
    metadata.setdefault("dataset", enriched.get("dataset"))
    metadata.setdefault("teacher", enriched.get("teacher"))
    metadata.setdefault("student", enriched.get("student"))
    metadata.setdefault("distiller", enriched.get("distiller"))
    enriched["metadata"] = metadata
    return enriched

save_student_checkpoint(path: str | Path, payload: dict[str, Any]) -> dict[str, Any]

Source code in recdistill/checkpointing.py
def save_student_checkpoint(path: str | Path, payload: dict[str, Any]) -> dict[str, Any]:
    checkpoint_path = Path(path)
    checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
    enriched = enrich_student_checkpoint_payload(payload)
    torch.save(enriched, checkpoint_path)
    return enriched

load_student_checkpoint(path: str | Path, map_location: str | torch.device = 'cpu') -> dict[str, Any]

Source code in recdistill/checkpointing.py
def load_student_checkpoint(path: str | Path, map_location: str | torch.device = "cpu") -> dict[str, Any]:
    payload = torch.load(Path(path), map_location=map_location, weights_only=False)
    if not isinstance(payload, dict):
        raise TypeError(f"Unsupported checkpoint payload type: {type(payload)!r}")
    if "student_state_dict" not in payload:
        raise KeyError(f"`student_state_dict` missing in checkpoint: {path}")
    return payload