minitrain 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. minitrain/__init__.py +5 -0
  2. minitrain/__main__.py +7 -0
  3. minitrain/cli.py +116 -0
  4. minitrain/datasets/__init__.py +0 -0
  5. minitrain/datasets/cifar10.py +53 -0
  6. minitrain/datasets/download/__init__.py +0 -0
  7. minitrain/datasets/download/file.py +38 -0
  8. minitrain/datasets/fashionmnist.py +21 -0
  9. minitrain/datasets/loaders/__init__.py +1 -0
  10. minitrain/datasets/loaders/idx.py +50 -0
  11. minitrain/datasets/loaders/image_dataset.py +20 -0
  12. minitrain/datasets/loaders/registry.py +9 -0
  13. minitrain/datasets/mnist.py +21 -0
  14. minitrain/misc/__init__.py +0 -0
  15. minitrain/misc/ddp.py +37 -0
  16. minitrain/models/__init__.py +0 -0
  17. minitrain/models/classification/__init__.py +7 -0
  18. minitrain/models/classification/resnet.py +100 -0
  19. minitrain/models/classification/small_cnn.py +31 -0
  20. minitrain/models/classification/vit.py +79 -0
  21. minitrain/models/generation/__init__.py +5 -0
  22. minitrain/models/generation/samplers/__init__.py +6 -0
  23. minitrain/models/generation/samplers/ddim.py +14 -0
  24. minitrain/models/generation/samplers/ddpm.py +12 -0
  25. minitrain/models/generation/samplers/dpmpp.py +22 -0
  26. minitrain/models/generation/samplers/sampling.py +86 -0
  27. minitrain/models/generation/samplers/schedule.py +22 -0
  28. minitrain/models/generation/unet.py +109 -0
  29. minitrain/models/loading.py +28 -0
  30. minitrain/models/registry.py +18 -0
  31. minitrain/train/__init__.py +0 -0
  32. minitrain/train/artifacts.py +54 -0
  33. minitrain/train/classification.py +93 -0
  34. minitrain/train/diffusion.py +89 -0
  35. minitrain/train/loaders.py +18 -0
  36. minitrain/train/metrics/__init__.py +1 -0
  37. minitrain/train/metrics/classification.py +37 -0
  38. minitrain/train/optimizer.py +12 -0
  39. minitrain/train/recipes/__init__.py +45 -0
  40. minitrain/train/recipes/classification/cifar10-cct.yaml +35 -0
  41. minitrain/train/recipes/classification/cifar10-resnet20.yaml +28 -0
  42. minitrain/train/recipes/classification/cifar10-vit.yaml +34 -0
  43. minitrain/train/recipes/classification/cifar10-wrn28x10.yaml +35 -0
  44. minitrain/train/recipes/classification/fashionmnist-resnet20.yaml +27 -0
  45. minitrain/train/recipes/classification/fashionmnist-small-cnn.yaml +20 -0
  46. minitrain/train/recipes/classification/mnist-small-cnn.yaml +20 -0
  47. minitrain/train/recipes/generation/cifar10-unet.yaml +30 -0
  48. minitrain/train/recipes/generation/fashionmnist-unet.yaml +30 -0
  49. minitrain/train/recipes/generation/mnist-unet.yaml +22 -0
  50. minitrain/train/recipes/parsing.py +40 -0
  51. minitrain/train/recipes/run.py +40 -0
  52. minitrain/train/recipes/validation.py +114 -0
  53. minitrain/train/trainer/__init__.py +5 -0
  54. minitrain/train/trainer/checkpoint.py +118 -0
  55. minitrain/train/trainer/core.py +256 -0
  56. minitrain/train/trainer/ema.py +20 -0
  57. minitrain/train/trainer/logging.py +47 -0
  58. minitrain/train/trainer/precision.py +74 -0
  59. minitrain/train/trainer/scheduler.py +29 -0
  60. minitrain/train/trainer/warmup.py +6 -0
  61. minitrain/train/transforms.py +58 -0
  62. minitrain-0.1.0.dist-info/METADATA +53 -0
  63. minitrain-0.1.0.dist-info/RECORD +67 -0
  64. minitrain-0.1.0.dist-info/WHEEL +5 -0
  65. minitrain-0.1.0.dist-info/entry_points.txt +2 -0
  66. minitrain-0.1.0.dist-info/licenses/LICENSE +21 -0
  67. minitrain-0.1.0.dist-info/top_level.txt +1 -0
minitrain/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Recipe-driven training for small image models."""
2
+
3
+ from .models.loading import load_model
4
+
5
+ __all__ = ["load_model"]
minitrain/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Support launching minitrain through Python."""
2
+
3
+ from .cli import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ main()
minitrain/cli.py ADDED
@@ -0,0 +1,116 @@
1
+ """Download data and train a classifier or denoiser from a recipe."""
2
+
3
+ import argparse
4
+ import os
5
+ import random
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import torch
11
+ from torch import distributed as dist
12
+
13
+ from .datasets.loaders.registry import DATASETS, IMAGE_SHAPES
14
+ from .misc.ddp import distributed, is_distributed, is_primary
15
+ from .models.registry import TASK_MODELS
16
+ from .train.artifacts import plot_metrics
17
+ from .train.classification import ClassificationTask, classifier_loaders
18
+ from .train.diffusion import DiffusionTask, diffusion_loader
19
+ from .train.recipes import PRESETS
20
+ from .train.recipes.run import load_run_recipe
21
+ from .train.trainer import Trainer
22
+
23
+
24
+ TASKS = {"classification": ClassificationTask, "generation": DiffusionTask}
25
+
26
+
27
+ def default_data_root():
28
+ cache = Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache")
29
+ return cache.expanduser() / "minitrain" / "data"
30
+
31
+
32
+ def build_model(task, dataset, config):
33
+ name = config["name"]
34
+ channels, height, _ = IMAGE_SHAPES[dataset]
35
+ options = config.get("options", {})
36
+ defaults = {"in_channels": channels}
37
+ if task == "classification":
38
+ defaults["num_classes"] = 10
39
+ if name == "vit":
40
+ defaults["image_size"] = height
41
+ if defaults.keys() & options.keys():
42
+ raise ValueError("Input channels, class count, and ViT image size come from the dataset")
43
+ return TASK_MODELS[task][name](**defaults, **options)
44
+
45
+
46
+ def ensure_data(dataset, root):
47
+ fetch = DATASETS[dataset].download_files
48
+ if not is_distributed():
49
+ fetch(root)
50
+ return
51
+
52
+ failure = [None]
53
+ if is_primary():
54
+ try:
55
+ fetch(root)
56
+ except (OSError, ValueError) as error:
57
+ failure[0] = str(error)
58
+ dist.broadcast_object_list(failure, src=0)
59
+ if failure[0] is not None:
60
+ raise RuntimeError(f"Could not download {dataset}: {failure[0]}")
61
+
62
+
63
+ def main():
64
+ presets = ", ".join(f"{task}/{name}" for task, names in PRESETS.items() for name in names)
65
+ parser = argparse.ArgumentParser(description=__doc__, epilog=f"Bundled presets: {presets}")
66
+ parser.add_argument("recipe", help="task/preset or a YAML/JSON file path")
67
+ args = parser.parse_args()
68
+ try:
69
+ recipe, paths = load_run_recipe(args.recipe, default_data_root=default_data_root())
70
+ task, dataset = recipe["task"], recipe["dataset"]
71
+ if dataset not in DATASETS:
72
+ raise ValueError(f"dataset must be one of {', '.join(DATASETS)}")
73
+ if recipe["model"]["name"] not in TASK_MODELS[task]:
74
+ raise ValueError(f"model.name for {task} must be one of {', '.join(TASK_MODELS[task])}")
75
+ trainer = Trainer.from_recipe(TASKS[task], recipe)
76
+ except (OSError, TypeError, ValueError) as error:
77
+ parser.error(str(error))
78
+
79
+ runtime = recipe.get("runtime", {})
80
+ processes = runtime.get("processes", 1)
81
+ data_root = paths["data_root"]
82
+ if processes > 1 and "LOCAL_RANK" not in os.environ:
83
+ try:
84
+ ensure_data(dataset, data_root)
85
+ except (OSError, ValueError) as error:
86
+ parser.error(f"Could not download {dataset}: {error}")
87
+ os.execv(sys.executable, [
88
+ sys.executable, "-m", "torch.distributed.run", "--standalone",
89
+ f"--nproc-per-node={processes}", "-m", "minitrain", args.recipe,
90
+ ])
91
+
92
+ with distributed(runtime.get("device", "auto")) as device:
93
+ seed = runtime.get("seed", 0) + (dist.get_rank() if is_distributed() else 0)
94
+ random.seed(seed)
95
+ np.random.seed(seed % 2**32)
96
+ torch.manual_seed(seed)
97
+ try:
98
+ model = build_model(task, dataset, recipe["model"])
99
+ ensure_data(dataset, data_root)
100
+ except (OSError, TypeError, ValueError, RuntimeError) as error:
101
+ parser.error(str(error))
102
+
103
+ loader_args = (dataset, data_root, recipe["batch_size"])
104
+ data = recipe.get("data", {})
105
+ if task == "classification":
106
+ train, validation = classifier_loaders(*loader_args, **data)
107
+ else:
108
+ train, validation = diffusion_loader(*loader_args, **data), None
109
+ run_dir = paths["run_dir"]
110
+ run = trainer.fit(
111
+ model, train, device=device, validation_loader=validation,
112
+ run_dir=run_dir, resume_from=paths.get("resume_from"),
113
+ )
114
+ if is_primary():
115
+ plot_metrics(run.history, run_dir)
116
+ print(f"Completed epoch {run.epoch} ({run.updates} updates). Outputs in {run_dir}.")
File without changes
@@ -0,0 +1,53 @@
1
+ import tarfile
2
+ from pathlib import Path
3
+
4
+ import numpy as np
5
+
6
+ from .download.file import download_file
7
+ from .loaders.image_dataset import ImageDataset
8
+
9
+
10
+ class CIFAR10(ImageDataset):
11
+ """Color images from the official CIFAR-10 binary archive."""
12
+
13
+ url = "https://cave.cs.toronto.edu/kriz/cifar-10-binary.tar.gz"
14
+ checksum = "c32a1d4ab5d03f1284b67883e8d87530"
15
+ archive_path = Path("cifar10/cifar-10-binary.tar.gz")
16
+
17
+ @classmethod
18
+ def download_files(cls, root):
19
+ download_file(cls.url, Path(root) / cls.archive_path, cls.checksum)
20
+
21
+ @classmethod
22
+ def prepare(cls, root):
23
+ """Download the binary archive and verify both splits can be loaded."""
24
+ cls.download_files(root)
25
+ for train in (True, False):
26
+ cls(root, train=train)
27
+
28
+ def __init__(self, root, train=True, download=False, transform=None):
29
+ if download:
30
+ self.download_files(root)
31
+ path = Path(root) / self.archive_path
32
+
33
+ names = (
34
+ [f"data_batch_{i}.bin" for i in range(1, 6)]
35
+ if train
36
+ else ["test_batch.bin"]
37
+ )
38
+ count = len(names) * 10_000
39
+ images = np.empty((count, 3, 32, 32), dtype=np.uint8)
40
+ labels = np.empty(count, dtype=np.uint8)
41
+ with tarfile.open(path, "r:gz") as archive:
42
+ for i, name in enumerate(names):
43
+ member = archive.getmember(f"cifar-10-batches-bin/{name}")
44
+ if not member.isfile() or member.size != 10_000 * 3073:
45
+ raise ValueError(f"Unexpected CIFAR-10 batch: {name}")
46
+ with archive.extractfile(member) as batch:
47
+ records = np.frombuffer(batch.read(), dtype=np.uint8).reshape(
48
+ 10_000, 3073
49
+ )
50
+ rows = slice(i * 10_000, (i + 1) * 10_000)
51
+ labels[rows] = records[:, 0]
52
+ images[rows] = records[:, 1:].reshape(10_000, 3, 32, 32)
53
+ super().__init__(images, labels, transform)
File without changes
@@ -0,0 +1,38 @@
1
+ """Download a file and cache it after checking its published checksum."""
2
+
3
+ import hashlib
4
+ from pathlib import Path
5
+ from tempfile import NamedTemporaryFile
6
+ from urllib.request import urlopen
7
+
8
+ from tqdm import tqdm
9
+
10
+
11
+ def download_file(url, path, md5):
12
+ if path.is_file():
13
+ return
14
+
15
+ path.parent.mkdir(parents=True, exist_ok=True)
16
+ digest = hashlib.md5(usedforsecurity=False)
17
+ with NamedTemporaryFile(dir=path.parent, delete=False) as output:
18
+ temporary = Path(output.name)
19
+ try:
20
+ with temporary.open("wb") as output, urlopen(url, timeout=60) as response:
21
+ length = response.headers.get("Content-Length", "")
22
+ total = int(length) if length.isdecimal() else None
23
+ with tqdm(
24
+ total=total,
25
+ desc=path.name,
26
+ unit="B",
27
+ unit_scale=True,
28
+ unit_divisor=1024,
29
+ ) as progress:
30
+ while chunk := response.read(1024 * 1024):
31
+ digest.update(chunk)
32
+ output.write(chunk)
33
+ progress.update(len(chunk))
34
+ if digest.hexdigest() != md5:
35
+ raise ValueError(f"Checksum mismatch for {url}")
36
+ temporary.replace(path)
37
+ finally:
38
+ temporary.unlink(missing_ok=True)
@@ -0,0 +1,21 @@
1
+ from .loaders.idx import IDXDataset
2
+
3
+
4
+ class FashionMNIST(IDXDataset):
5
+ """Fashion images from Zalando Research."""
6
+
7
+ directory = "fashionmnist"
8
+ url = "https://raw.githubusercontent.com/zalandoresearch/fashion-mnist/master/data/fashion"
9
+ checksums = {
10
+ "train-images-idx3-ubyte.gz": "8d4fb7e6c68d591d4c3dfef9ec88bf0d",
11
+ "train-labels-idx1-ubyte.gz": "25c81989df183df01b3e8a0aad5dffbe",
12
+ "t10k-images-idx3-ubyte.gz": "bef4ecab320f06d8554ea6380940ec79",
13
+ "t10k-labels-idx1-ubyte.gz": "bb300cfdad3c16e7a12a480ee83cd310",
14
+ }
15
+
16
+ @classmethod
17
+ def prepare(cls, root):
18
+ """Download the IDX files and verify both splits can be loaded."""
19
+ cls.download_files(root)
20
+ for train in (True, False):
21
+ cls(root, train=train)
@@ -0,0 +1 @@
1
+ """Shared dataset loaders and sample interfaces."""
@@ -0,0 +1,50 @@
1
+ """Load gzip-compressed unsigned-byte IDX images and labels."""
2
+
3
+ import gzip
4
+ from pathlib import Path
5
+ from struct import unpack
6
+
7
+ import numpy as np
8
+
9
+ from ..download.file import download_file
10
+ from .image_dataset import ImageDataset
11
+
12
+
13
+ def read_idx(path, shape):
14
+ with gzip.open(path, "rb") as source:
15
+ header = source.read(4 + 4 * len(shape))
16
+ if len(header) != 4 + 4 * len(shape):
17
+ raise ValueError(f"Incomplete IDX header in {path}")
18
+ magic, *dimensions = unpack(f">{len(shape) + 1}I", header)
19
+ if magic != 0x0800 + len(shape) or tuple(dimensions) != shape:
20
+ raise ValueError(f"Unexpected IDX header in {path}")
21
+ return np.frombuffer(source.read(), dtype=np.uint8).reshape(shape).copy()
22
+
23
+
24
+ class IDXDataset(ImageDataset):
25
+ @classmethod
26
+ def _split_files(cls, root, train):
27
+ directory = Path(root) / cls.directory
28
+ prefix = "train" if train else "t10k"
29
+ return (
30
+ directory / f"{prefix}-images-idx3-ubyte.gz",
31
+ directory / f"{prefix}-labels-idx1-ubyte.gz",
32
+ )
33
+
34
+ @classmethod
35
+ def download_files(cls, root, train=None):
36
+ splits = (True, False) if train is None else (train,)
37
+ for split in splits:
38
+ for path in cls._split_files(root, split):
39
+ download_file(f"{cls.url}/{path.name}", path, cls.checksums[path.name])
40
+
41
+ def __init__(self, root, train=True, download=False, transform=None):
42
+ if download:
43
+ self.download_files(root, train)
44
+ images, labels = self._split_files(root, train)
45
+ count = 60_000 if train else 10_000
46
+ super().__init__(
47
+ read_idx(images, (count, 28, 28))[:, None],
48
+ read_idx(labels, (count,)),
49
+ transform,
50
+ )
@@ -0,0 +1,20 @@
1
+ """Shared sample interface for labeled image datasets."""
2
+
3
+ import torch
4
+ from torch.utils.data import Dataset
5
+
6
+
7
+ class ImageDataset(Dataset):
8
+ def __init__(self, images, labels, transform=None):
9
+ self.images = images
10
+ self.labels = labels
11
+ self.transform = transform
12
+
13
+ def __len__(self):
14
+ return len(self.labels)
15
+
16
+ def __getitem__(self, index):
17
+ image = torch.from_numpy(self.images[index]).to(torch.float32).div_(255)
18
+ if self.transform is not None:
19
+ image = self.transform(image)
20
+ return image, int(self.labels[index])
@@ -0,0 +1,9 @@
1
+ """Dataset classes keyed by their command-line names."""
2
+
3
+ from ..cifar10 import CIFAR10
4
+ from ..fashionmnist import FashionMNIST
5
+ from ..mnist import MNIST
6
+
7
+ DATASETS = {"mnist": MNIST, "fashionmnist": FashionMNIST, "cifar10": CIFAR10}
8
+
9
+ IMAGE_SHAPES = {"mnist": (1, 28, 28), "fashionmnist": (1, 28, 28), "cifar10": (3, 32, 32)}
@@ -0,0 +1,21 @@
1
+ from .loaders.idx import IDXDataset
2
+
3
+
4
+ class MNIST(IDXDataset):
5
+ """Handwritten digits from the CVDF mirror."""
6
+
7
+ directory = "mnist"
8
+ url = "https://storage.googleapis.com/cvdf-datasets/mnist"
9
+ checksums = {
10
+ "train-images-idx3-ubyte.gz": "f68b3c2dcbeaaa9fbdd348bbdeb94873",
11
+ "train-labels-idx1-ubyte.gz": "d53e105ee54ea40749a09fcbcd1e9432",
12
+ "t10k-images-idx3-ubyte.gz": "9fb629c4189551a2d022fa330f9573f3",
13
+ "t10k-labels-idx1-ubyte.gz": "ec29112dd5afa0611ce80d1b7f02629c",
14
+ }
15
+
16
+ @classmethod
17
+ def prepare(cls, root):
18
+ """Download the IDX files and verify both splits can be loaded."""
19
+ cls.download_files(root)
20
+ for train in (True, False):
21
+ cls(root, train=train)
File without changes
minitrain/misc/ddp.py ADDED
@@ -0,0 +1,37 @@
1
+ """Process-group setup for single-process and torchrun jobs."""
2
+
3
+ import os
4
+ from contextlib import contextmanager
5
+
6
+ import torch
7
+ from torch import distributed as dist
8
+
9
+
10
+ def is_distributed():
11
+ return dist.is_available() and dist.is_initialized()
12
+
13
+
14
+ def is_primary():
15
+ return not is_distributed() or dist.get_rank() == 0
16
+
17
+
18
+ @contextmanager
19
+ def distributed(device="auto"):
20
+ """Yield the local device and manage the process group when needed."""
21
+ if device == "auto":
22
+ device = "cuda" if torch.cuda.is_available() else "cpu"
23
+ device = torch.device(device)
24
+ launched = int(os.environ.get("WORLD_SIZE", "1")) > 1
25
+ if device.type == "cuda":
26
+ index = int(os.environ["LOCAL_RANK"]) if launched else device.index
27
+ device = torch.device("cuda", torch.cuda.current_device() if index is None else index)
28
+ torch.cuda.set_device(device)
29
+
30
+ owns_group = launched and not is_distributed()
31
+ if owns_group:
32
+ dist.init_process_group("nccl" if device.type == "cuda" else "gloo")
33
+ try:
34
+ yield device
35
+ finally:
36
+ if owns_group:
37
+ dist.destroy_process_group()
File without changes
@@ -0,0 +1,7 @@
1
+ """Classifier architectures for small images."""
2
+
3
+ from .resnet import ResNet
4
+ from .small_cnn import SmallCNN
5
+ from .vit import VisionTransformer
6
+
7
+ __all__ = ["ResNet", "SmallCNN", "VisionTransformer"]
@@ -0,0 +1,100 @@
1
+ """Residual classifier with a small-image stem and configurable stages."""
2
+
3
+ from torch import nn
4
+
5
+
6
+ class ResidualBlock(nn.Module):
7
+ def __init__(self, in_channels, out_channels, stride):
8
+ super().__init__()
9
+ self.body = nn.Sequential(
10
+ nn.Conv2d(in_channels, out_channels, 3, stride, padding=1, bias=False),
11
+ nn.BatchNorm2d(out_channels),
12
+ nn.ReLU(),
13
+ nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
14
+ nn.BatchNorm2d(out_channels),
15
+ )
16
+ self.shortcut = nn.Identity()
17
+ if stride != 1 or in_channels != out_channels:
18
+ self.shortcut = nn.Sequential(
19
+ nn.Conv2d(in_channels, out_channels, 1, stride, bias=False),
20
+ nn.BatchNorm2d(out_channels),
21
+ )
22
+ self.activation = nn.ReLU()
23
+
24
+ def forward(self, images):
25
+ return self.activation(self.body(images) + self.shortcut(images))
26
+
27
+
28
+ class PreActivationBlock(nn.Module):
29
+ """Wide ResNet block with normalization before each convolution."""
30
+
31
+ def __init__(self, in_channels, out_channels, stride, dropout):
32
+ super().__init__()
33
+ self.preact = nn.Sequential(nn.BatchNorm2d(in_channels), nn.ReLU())
34
+ self.body = nn.Sequential(
35
+ nn.Conv2d(in_channels, out_channels, 3, stride, padding=1, bias=False),
36
+ nn.BatchNorm2d(out_channels),
37
+ nn.ReLU(),
38
+ nn.Dropout(dropout),
39
+ nn.Conv2d(out_channels, out_channels, 3, padding=1, bias=False),
40
+ )
41
+ self.project = stride != 1 or in_channels != out_channels
42
+ self.shortcut = (
43
+ nn.Conv2d(in_channels, out_channels, 1, stride, bias=False)
44
+ if self.project else nn.Identity()
45
+ )
46
+
47
+ def forward(self, images):
48
+ features = self.preact(images)
49
+ shortcut = self.shortcut(features if self.project else images)
50
+ return self.body(features) + shortcut
51
+
52
+
53
+ class ResNet(nn.Module):
54
+ """The default stage depths follow the CIFAR ResNet-20 layout."""
55
+
56
+ def __init__(
57
+ self, in_channels, num_classes=10, *, width=16, blocks=(3, 3, 3),
58
+ widen_factor=1, preactivation=False, dropout=0.0,
59
+ ):
60
+ super().__init__()
61
+ if width < 1 or widen_factor < 1 or not blocks or any(count < 1 for count in blocks):
62
+ raise ValueError("width, widen_factor, and stage depths must be positive")
63
+ if not 0 <= dropout < 1 or (dropout and not preactivation):
64
+ raise ValueError("dropout must be in [0, 1) and requires preactivation when nonzero")
65
+ self._minitrain_config = {
66
+ "name": "resnet",
67
+ "options": dict(
68
+ in_channels=in_channels, num_classes=num_classes, width=width,
69
+ blocks=list(blocks), widen_factor=widen_factor, preactivation=preactivation, dropout=dropout,
70
+ ),
71
+ }
72
+ stem = [nn.Conv2d(in_channels, width, 3, padding=1, bias=False)]
73
+ if not preactivation:
74
+ stem.extend((nn.BatchNorm2d(width), nn.ReLU()))
75
+ self.stem = nn.Sequential(*stem)
76
+
77
+ def make_block(before, after, stride):
78
+ if preactivation:
79
+ return PreActivationBlock(before, after, stride, dropout)
80
+ return ResidualBlock(before, after, stride)
81
+
82
+ stages = []
83
+ channels = width
84
+ for stage, count in enumerate(blocks):
85
+ out_channels = width * widen_factor * 2**stage
86
+ stages.append(make_block(channels, out_channels, 2 if stage else 1))
87
+ stages.extend(make_block(out_channels, out_channels, 1) for _ in range(count - 1))
88
+ channels = out_channels
89
+ if preactivation:
90
+ stages.extend((nn.BatchNorm2d(channels), nn.ReLU()))
91
+ self.features = nn.Sequential(*stages)
92
+ self.classifier = nn.Sequential(
93
+ nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(channels, num_classes)
94
+ )
95
+ for layer in self.modules():
96
+ if isinstance(layer, nn.Conv2d):
97
+ nn.init.kaiming_normal_(layer.weight, mode="fan_out", nonlinearity="relu")
98
+
99
+ def forward(self, images):
100
+ return self.classifier(self.features(self.stem(images)))
@@ -0,0 +1,31 @@
1
+ """A lightweight LeNet-style classifier for small images."""
2
+
3
+ from torch import nn
4
+
5
+
6
+ class SmallCNN(nn.Module):
7
+ def __init__(self, in_channels, num_classes=10):
8
+ super().__init__()
9
+ self._minitrain_config = {
10
+ "name": "small_cnn", "options": dict(in_channels=in_channels, num_classes=num_classes),
11
+ }
12
+ self.features = nn.Sequential(
13
+ nn.Conv2d(in_channels, 6, kernel_size=5),
14
+ nn.ReLU(),
15
+ nn.AvgPool2d(2),
16
+ nn.Conv2d(6, 16, kernel_size=5),
17
+ nn.ReLU(),
18
+ nn.AvgPool2d(2),
19
+ nn.AdaptiveAvgPool2d(4),
20
+ )
21
+ self.classifier = nn.Sequential(
22
+ nn.Flatten(),
23
+ nn.Linear(16 * 4 * 4, 120),
24
+ nn.ReLU(),
25
+ nn.Linear(120, 84),
26
+ nn.ReLU(),
27
+ nn.Linear(84, num_classes),
28
+ )
29
+
30
+ def forward(self, images):
31
+ return self.classifier(self.features(images))
@@ -0,0 +1,79 @@
1
+ """A compact image transformer with patch or convolutional tokenization."""
2
+
3
+ import torch
4
+ from torch import nn
5
+
6
+
7
+ class VisionTransformer(nn.Module):
8
+ def __init__(
9
+ self, in_channels, num_classes=10, *, image_size=32, patch_size=4,
10
+ dim=128, depth=4, heads=4, mlp_dim=256, dropout=0.1,
11
+ conv_layers=0, pooling="cls", positional_embedding=True,
12
+ ):
13
+ super().__init__()
14
+ if image_size < 1 or conv_layers < 0:
15
+ raise ValueError("image_size must be positive and conv_layers nonnegative")
16
+ if depth < 1 or heads < 1 or dim < 1 or dim % heads or mlp_dim < 1:
17
+ raise ValueError("Expected positive dimensions and dim divisible by heads")
18
+ if pooling not in ("cls", "attention"):
19
+ raise ValueError("pooling must be cls or attention")
20
+ self._minitrain_config = {
21
+ "name": "vit",
22
+ "options": dict(
23
+ in_channels=in_channels, num_classes=num_classes, image_size=image_size,
24
+ patch_size=patch_size, dim=dim, depth=depth, heads=heads, mlp_dim=mlp_dim,
25
+ dropout=dropout, conv_layers=conv_layers, pooling=pooling,
26
+ positional_embedding=positional_embedding,
27
+ ),
28
+ }
29
+ self.image_size = image_size
30
+ if conv_layers:
31
+ layers = []
32
+ grid = image_size
33
+ for _ in range(conv_layers):
34
+ layers.extend((
35
+ nn.Conv2d(in_channels, dim, 3, padding=1, bias=False),
36
+ nn.ReLU(),
37
+ nn.MaxPool2d(3, stride=2, padding=1),
38
+ ))
39
+ in_channels = dim
40
+ grid = (grid + 1) // 2
41
+ self.patches = nn.Sequential(*layers)
42
+ else:
43
+ if patch_size < 1 or image_size % patch_size:
44
+ raise ValueError("image_size must be a positive multiple of patch_size")
45
+ self.patches = nn.Conv2d(in_channels, dim, patch_size, stride=patch_size)
46
+ grid = image_size // patch_size
47
+
48
+ self.class_token = nn.Parameter(torch.zeros(1, 1, dim)) if pooling == "cls" else None
49
+ self.token_score = nn.Linear(dim, 1) if pooling == "attention" else None
50
+ tokens = grid**2 + (pooling == "cls")
51
+ self.position = None
52
+ if positional_embedding:
53
+ self.position = nn.Parameter(torch.empty(1, tokens, dim))
54
+ nn.init.trunc_normal_(self.position, std=0.02)
55
+ self.dropout = nn.Dropout(dropout)
56
+ self.layers = nn.Sequential(*(
57
+ nn.TransformerEncoderLayer(
58
+ dim, heads, mlp_dim, dropout, activation="gelu",
59
+ batch_first=True, norm_first=True,
60
+ )
61
+ for _ in range(depth)
62
+ ))
63
+ self.classifier = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, num_classes))
64
+
65
+ def forward(self, images):
66
+ if images.shape[-2:] != (self.image_size, self.image_size):
67
+ raise ValueError(f"Expected {self.image_size}x{self.image_size} images")
68
+ tokens = self.patches(images).flatten(2).transpose(1, 2)
69
+ if self.class_token is not None:
70
+ token = self.class_token.to(tokens.dtype).expand(len(images), -1, -1)
71
+ tokens = torch.cat((token, tokens), dim=1)
72
+ if self.position is not None:
73
+ tokens = tokens + self.position.to(tokens.dtype)
74
+ tokens = self.layers(self.dropout(tokens))
75
+ if self.token_score is None:
76
+ return self.classifier(tokens[:, 0])
77
+ tokens = self.classifier[0](tokens)
78
+ weights = self.token_score(tokens).softmax(dim=1)
79
+ return self.classifier[1]((tokens * weights).sum(dim=1))
@@ -0,0 +1,5 @@
1
+ """Generative model architectures."""
2
+
3
+ from .unet import DiffusionUNet
4
+
5
+ __all__ = ["DiffusionUNet"]
@@ -0,0 +1,6 @@
1
+ """Samplers for discrete epsilon-prediction diffusion models."""
2
+
3
+ from .sampling import sample
4
+ from .schedule import NoiseSchedule
5
+
6
+ __all__ = ["NoiseSchedule", "sample"]
@@ -0,0 +1,14 @@
1
+ """DDIM updates with configurable stochasticity."""
2
+
3
+ import torch
4
+
5
+
6
+ def ddim_step(clean, epsilon, alpha, next_alpha, eta, generator):
7
+ variance = (1 - next_alpha) / (1 - alpha) * (1 - alpha / next_alpha)
8
+ sigma = eta * variance.sqrt()
9
+ direction = (1 - next_alpha - sigma.square()).clamp_min(0).sqrt()
10
+ result = next_alpha.sqrt() * clean + direction * epsilon
11
+ if eta:
12
+ noise = torch.randn(clean.shape, device=clean.device, dtype=clean.dtype, generator=generator)
13
+ result = result + sigma * noise
14
+ return result
@@ -0,0 +1,12 @@
1
+ """Ancestral DDPM updates with the posterior variance."""
2
+
3
+ import torch
4
+
5
+
6
+ def ddpm_step(noisy, clean, alpha, next_alpha, generator):
7
+ beta = 1 - alpha / next_alpha
8
+ variance = beta * (1 - next_alpha) / (1 - alpha)
9
+ clean_weight = next_alpha.sqrt() * beta / (1 - alpha)
10
+ noisy_weight = (alpha / next_alpha).sqrt() * (1 - next_alpha) / (1 - alpha)
11
+ noise = torch.randn(noisy.shape, device=noisy.device, dtype=noisy.dtype, generator=generator)
12
+ return clean_weight * clean + noisy_weight * noisy + variance.sqrt() * noise