minitrain 0.1.0__tar.gz

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 (77) hide show
  1. minitrain-0.1.0/LICENSE +21 -0
  2. minitrain-0.1.0/PKG-INFO +53 -0
  3. minitrain-0.1.0/README.md +38 -0
  4. minitrain-0.1.0/pyproject.toml +29 -0
  5. minitrain-0.1.0/setup.cfg +4 -0
  6. minitrain-0.1.0/src/minitrain/__init__.py +5 -0
  7. minitrain-0.1.0/src/minitrain/__main__.py +7 -0
  8. minitrain-0.1.0/src/minitrain/cli.py +116 -0
  9. minitrain-0.1.0/src/minitrain/datasets/__init__.py +0 -0
  10. minitrain-0.1.0/src/minitrain/datasets/cifar10.py +53 -0
  11. minitrain-0.1.0/src/minitrain/datasets/download/__init__.py +0 -0
  12. minitrain-0.1.0/src/minitrain/datasets/download/file.py +38 -0
  13. minitrain-0.1.0/src/minitrain/datasets/fashionmnist.py +21 -0
  14. minitrain-0.1.0/src/minitrain/datasets/loaders/__init__.py +1 -0
  15. minitrain-0.1.0/src/minitrain/datasets/loaders/idx.py +50 -0
  16. minitrain-0.1.0/src/minitrain/datasets/loaders/image_dataset.py +20 -0
  17. minitrain-0.1.0/src/minitrain/datasets/loaders/registry.py +9 -0
  18. minitrain-0.1.0/src/minitrain/datasets/mnist.py +21 -0
  19. minitrain-0.1.0/src/minitrain/misc/__init__.py +0 -0
  20. minitrain-0.1.0/src/minitrain/misc/ddp.py +37 -0
  21. minitrain-0.1.0/src/minitrain/models/__init__.py +0 -0
  22. minitrain-0.1.0/src/minitrain/models/classification/__init__.py +7 -0
  23. minitrain-0.1.0/src/minitrain/models/classification/resnet.py +100 -0
  24. minitrain-0.1.0/src/minitrain/models/classification/small_cnn.py +31 -0
  25. minitrain-0.1.0/src/minitrain/models/classification/vit.py +79 -0
  26. minitrain-0.1.0/src/minitrain/models/generation/__init__.py +5 -0
  27. minitrain-0.1.0/src/minitrain/models/generation/samplers/__init__.py +6 -0
  28. minitrain-0.1.0/src/minitrain/models/generation/samplers/ddim.py +14 -0
  29. minitrain-0.1.0/src/minitrain/models/generation/samplers/ddpm.py +12 -0
  30. minitrain-0.1.0/src/minitrain/models/generation/samplers/dpmpp.py +22 -0
  31. minitrain-0.1.0/src/minitrain/models/generation/samplers/sampling.py +86 -0
  32. minitrain-0.1.0/src/minitrain/models/generation/samplers/schedule.py +22 -0
  33. minitrain-0.1.0/src/minitrain/models/generation/unet.py +109 -0
  34. minitrain-0.1.0/src/minitrain/models/loading.py +28 -0
  35. minitrain-0.1.0/src/minitrain/models/registry.py +18 -0
  36. minitrain-0.1.0/src/minitrain/train/__init__.py +0 -0
  37. minitrain-0.1.0/src/minitrain/train/artifacts.py +54 -0
  38. minitrain-0.1.0/src/minitrain/train/classification.py +93 -0
  39. minitrain-0.1.0/src/minitrain/train/diffusion.py +89 -0
  40. minitrain-0.1.0/src/minitrain/train/loaders.py +18 -0
  41. minitrain-0.1.0/src/minitrain/train/metrics/__init__.py +1 -0
  42. minitrain-0.1.0/src/minitrain/train/metrics/classification.py +37 -0
  43. minitrain-0.1.0/src/minitrain/train/optimizer.py +12 -0
  44. minitrain-0.1.0/src/minitrain/train/recipes/__init__.py +45 -0
  45. minitrain-0.1.0/src/minitrain/train/recipes/classification/cifar10-cct.yaml +35 -0
  46. minitrain-0.1.0/src/minitrain/train/recipes/classification/cifar10-resnet20.yaml +28 -0
  47. minitrain-0.1.0/src/minitrain/train/recipes/classification/cifar10-vit.yaml +34 -0
  48. minitrain-0.1.0/src/minitrain/train/recipes/classification/cifar10-wrn28x10.yaml +35 -0
  49. minitrain-0.1.0/src/minitrain/train/recipes/classification/fashionmnist-resnet20.yaml +27 -0
  50. minitrain-0.1.0/src/minitrain/train/recipes/classification/fashionmnist-small-cnn.yaml +20 -0
  51. minitrain-0.1.0/src/minitrain/train/recipes/classification/mnist-small-cnn.yaml +20 -0
  52. minitrain-0.1.0/src/minitrain/train/recipes/generation/cifar10-unet.yaml +30 -0
  53. minitrain-0.1.0/src/minitrain/train/recipes/generation/fashionmnist-unet.yaml +30 -0
  54. minitrain-0.1.0/src/minitrain/train/recipes/generation/mnist-unet.yaml +22 -0
  55. minitrain-0.1.0/src/minitrain/train/recipes/parsing.py +40 -0
  56. minitrain-0.1.0/src/minitrain/train/recipes/run.py +40 -0
  57. minitrain-0.1.0/src/minitrain/train/recipes/validation.py +114 -0
  58. minitrain-0.1.0/src/minitrain/train/trainer/__init__.py +5 -0
  59. minitrain-0.1.0/src/minitrain/train/trainer/checkpoint.py +118 -0
  60. minitrain-0.1.0/src/minitrain/train/trainer/core.py +256 -0
  61. minitrain-0.1.0/src/minitrain/train/trainer/ema.py +20 -0
  62. minitrain-0.1.0/src/minitrain/train/trainer/logging.py +47 -0
  63. minitrain-0.1.0/src/minitrain/train/trainer/precision.py +74 -0
  64. minitrain-0.1.0/src/minitrain/train/trainer/scheduler.py +29 -0
  65. minitrain-0.1.0/src/minitrain/train/trainer/warmup.py +6 -0
  66. minitrain-0.1.0/src/minitrain/train/transforms.py +58 -0
  67. minitrain-0.1.0/src/minitrain.egg-info/PKG-INFO +53 -0
  68. minitrain-0.1.0/src/minitrain.egg-info/SOURCES.txt +75 -0
  69. minitrain-0.1.0/src/minitrain.egg-info/dependency_links.txt +1 -0
  70. minitrain-0.1.0/src/minitrain.egg-info/entry_points.txt +2 -0
  71. minitrain-0.1.0/src/minitrain.egg-info/requires.txt +5 -0
  72. minitrain-0.1.0/src/minitrain.egg-info/top_level.txt +1 -0
  73. minitrain-0.1.0/tests/test_checkpoint.py +46 -0
  74. minitrain-0.1.0/tests/test_datasets.py +41 -0
  75. minitrain-0.1.0/tests/test_model_loading.py +58 -0
  76. minitrain-0.1.0/tests/test_recipes.py +70 -0
  77. minitrain-0.1.0/tests/test_samplers.py +65 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Juyeop Kim
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.4
2
+ Name: minitrain
3
+ Version: 0.1.0
4
+ Summary: Mini-models. Mini-data. Uni-recipe.
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: matplotlib
10
+ Requires-Dist: numpy
11
+ Requires-Dist: PyYAML
12
+ Requires-Dist: torch>=2.5
13
+ Requires-Dist: tqdm
14
+ Dynamic: license-file
15
+
16
+ # minitrain
17
+
18
+ Mini-models. Mini-data. Uni-recipe.
19
+
20
+ Run small-scale machine learning experiments from YAML or JSON recipes.
21
+
22
+ ## Quickstart
23
+
24
+ Use Python 3.10 or newer. Install from the checkout with
25
+ `python -m pip install .`, or use `pip install minitrain` once released on PyPI.
26
+
27
+ ```bash
28
+ minitrain classification/cifar10-resnet20
29
+ minitrain path/to/experiment.yaml
30
+ ```
31
+
32
+ Missing data files are downloaded automatically. Use `minitrain --help` to
33
+ list the bundled presets. Recipes control training, output paths, and resume.
34
+
35
+ ## Inference
36
+
37
+ ```python
38
+ import minitrain
39
+
40
+ model = minitrain.load_model("outputs/cifar10/last.ckpt")
41
+ ```
42
+
43
+ Built-in models load by checkpoint alone, in evaluation mode on CPU. The loader
44
+ prefers EMA weights when available. Use `device="cuda"` for GPU inference,
45
+ `use_ema=False` for regular weights, or `model=YourModel(...)` for a custom
46
+ architecture or older checkpoint. Apply the recipe’s evaluation preprocessing
47
+ to classifier inputs.
48
+
49
+ - [Recipe options, outputs, and resume](src/minitrain/train/recipes/README.md)
50
+ - [Model options and diffusion sampling](src/minitrain/models/README.md)
51
+
52
+ For development, run `python -m pip install -e .` and
53
+ `python -m unittest discover -v`.
@@ -0,0 +1,38 @@
1
+ # minitrain
2
+
3
+ Mini-models. Mini-data. Uni-recipe.
4
+
5
+ Run small-scale machine learning experiments from YAML or JSON recipes.
6
+
7
+ ## Quickstart
8
+
9
+ Use Python 3.10 or newer. Install from the checkout with
10
+ `python -m pip install .`, or use `pip install minitrain` once released on PyPI.
11
+
12
+ ```bash
13
+ minitrain classification/cifar10-resnet20
14
+ minitrain path/to/experiment.yaml
15
+ ```
16
+
17
+ Missing data files are downloaded automatically. Use `minitrain --help` to
18
+ list the bundled presets. Recipes control training, output paths, and resume.
19
+
20
+ ## Inference
21
+
22
+ ```python
23
+ import minitrain
24
+
25
+ model = minitrain.load_model("outputs/cifar10/last.ckpt")
26
+ ```
27
+
28
+ Built-in models load by checkpoint alone, in evaluation mode on CPU. The loader
29
+ prefers EMA weights when available. Use `device="cuda"` for GPU inference,
30
+ `use_ema=False` for regular weights, or `model=YourModel(...)` for a custom
31
+ architecture or older checkpoint. Apply the recipe’s evaluation preprocessing
32
+ to classifier inputs.
33
+
34
+ - [Recipe options, outputs, and resume](src/minitrain/train/recipes/README.md)
35
+ - [Model options and diffusion sampling](src/minitrain/models/README.md)
36
+
37
+ For development, run `python -m pip install -e .` and
38
+ `python -m unittest discover -v`.
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "minitrain"
7
+ version = "0.1.0"
8
+ description = "Mini-models. Mini-data. Uni-recipe."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = [
14
+ "matplotlib",
15
+ "numpy",
16
+ "PyYAML",
17
+ "torch>=2.5",
18
+ "tqdm",
19
+ ]
20
+
21
+ [project.scripts]
22
+ minitrain = "minitrain.cli:main"
23
+
24
+ [tool.setuptools.packages.find]
25
+ where = ["src"]
26
+ namespaces = false
27
+
28
+ [tool.setuptools.package-data]
29
+ "minitrain.train.recipes" = ["classification/*.yaml", "generation/*.yaml"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -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"]
@@ -0,0 +1,7 @@
1
+ """Support launching minitrain through Python."""
2
+
3
+ from .cli import main
4
+
5
+
6
+ if __name__ == "__main__":
7
+ main()
@@ -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)
@@ -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
@@ -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)))