File size: 1,146 Bytes
04ae9bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""Registry for pluggable model architectures."""

from __future__ import annotations

from copy import deepcopy
from typing import Any, Dict, Type

import torch.nn as nn


MODEL_REGISTRY: Dict[str, Type[nn.Module]] = {}


def register_model(name: str):
    def deco(cls: Type[nn.Module]):
        if name in MODEL_REGISTRY:
            raise ValueError(f"Model already registered: {name}")
        MODEL_REGISTRY[name] = cls
        cls.model_name = name
        return cls

    return deco


def build_model(cfg: Dict[str, Any], input_dim: int, output_dim: int) -> nn.Module:
    name = cfg["name"]
    if name not in MODEL_REGISTRY:
        raise KeyError(f"Unknown model '{name}'. Available: {sorted(MODEL_REGISTRY)}")
    params = deepcopy(cfg.get("params", {}))
    params.pop("input_dim", None)
    params.pop("output_dim", None)
    params.pop("output_type", None)
    output_type = cfg.get("output_type", "regression")
    return MODEL_REGISTRY[name](
        input_dim=input_dim,
        output_dim=output_dim,
        output_type=output_type,
        **params,
    )


def list_models() -> list[str]:
    return sorted(MODEL_REGISTRY)