PyTorch
File size: 5,067 Bytes
bd992b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import dataclasses
from typing import Callable, Generator

import torch
import torch.nn as nn

Batch = tuple[torch.Tensor, torch.Tensor, torch.Tensor]
BatchGenerator = Generator[Batch, None, None]


@dataclasses.dataclass
class ModelEntry:
    name: str
    make_model: Callable[[int, int, int], nn.Module]
    make_optimizer: Callable[[nn.Module], torch.optim.Optimizer] | None = None
    train_step: Callable[
                    [nn.Module, torch.optim.Optimizer, torch.Tensor, torch.Tensor, torch.Tensor], float] | None = None
    config_tester: Callable | None = None
    config_defaults: dict | None = None


_model_registry: dict[str, ModelEntry] = {}


def _get_or_create_arch(name: str) -> ModelEntry:
    if name not in _model_registry:
        # noinspection PyTypeChecker
        _model_registry[name] = ModelEntry(name=name, make_model=None)
    return _model_registry[name]


def model_init(model_name: str):
    """
    Register a model factory function.
    The decorated function must have signature:
        (n_params: int, vocab_size: int, seq_len: int) -> nn.Module

    :param model_name: The name of the model to register.
    :return: None
    """

    def decorator(func: Callable) -> Callable:
        entry = _get_or_create_arch(model_name)
        entry.make_model = func
        return func

    return decorator


def optimizer(model_name: str):
    """
    Optionally override the default optimizer for a model.
    If not provided, the default optimizer (AdamW) will be used.
    The decorated function must have signature:
        (model: nn.Module) -> torch.optim.Optimizer

    :param model_name: The name of the model to register the optimizer for.
    :return: None
    """

    def decorator(func: Callable) -> Callable:
        entry = _get_or_create_arch(model_name)
        entry.make_optimizer = func
        return func

    return decorator


def train_step(model_name: str):
    """
    Optionally override the default training step for a model.
    The decorated function must have signature:
        (model, optimizer, input_ids, target_ids, loss_mask) -> float

    :param model_name: The name of the model to register the training step for.
    :return: None
    """

    def decorator(func: Callable) -> Callable:
        entry = _get_or_create_arch(model_name)
        entry.train_step = func
        return func

    return decorator


def config_tester(model_name: str, **defaults):
    """
    Register a param counter for a simple config UI.
    Decorator kwargs are the architecture-specific fields and their defaults.
    The decorated function must have signature:
        (vocab_size: int, seq_len: int, **kwargs) -> int
    where **kwargs matches the decorator kwargs.

    :param model_name: The name of the model to register the param counter for.
    :param defaults: Params with default values for all params that the config UI should vary.
    :return: None
    """

    def decorator(func: Callable) -> Callable:
        entry = _get_or_create_arch(model_name)
        entry.config_tester = func
        entry.config_defaults = defaults
        return func

    return decorator


@dataclasses.dataclass
class TaskEntry:
    name: str
    vocab_size: int | Callable[[int], int]
    batch_generator: Callable[[int, int, int | None], BatchGenerator]
    seq_len: int


_task_registry: dict[str, TaskEntry] = {}


def task(name: str, vocab_size: int | Callable[[int], int], seq_len: int = 64):
    """
    Register a task generator.

    The decorated function must have signature:
        (seq_len: int, batch_size: int, seed: int | None = None) -> Generator[Batch, None, None]

    where Batch = (input_ids, target_ids, loss_mask), all (B, T) tensors.
    input_ids and target_ids are torch.long; loss_mask is torch.bool.

    vocab_size may be a plain int or a callable (seq_len) -> int for tasks
    whose vocab grows with sequence length.

    :param name: The name of the task to register.
    :param vocab_size: The plain int or callable (seq_len) -> int for tasks.
    :param seq_len: The sequence length to use for this task.
    :return: None
    """

    def decorator(func: Callable) -> Callable:
        _task_registry[name] = TaskEntry(
            name=name,
            vocab_size=vocab_size,
            batch_generator=func,
            seq_len=seq_len,
        )
        return func

    return decorator


def get_model(model_name: str) -> ModelEntry:
    if model_name not in _model_registry:
        raise KeyError(f"No arch registered under name '{model_name}'.")
    if _model_registry[model_name].make_model is None:
        raise KeyError(f"Model '{model_name}' has no @model_init function.")
    return _model_registry[model_name]


def get_task(task_name: str) -> TaskEntry:
    if task_name not in _task_registry:
        raise KeyError(f"No task registered under name '{task_name}'.")
    return _task_registry[task_name]


def all_models() -> dict[str, ModelEntry]:
    return dict(_model_registry)


def all_tasks() -> dict[str, TaskEntry]:
    return dict(_task_registry)