Efficient workflow and reproducibility are extremely important components in every machine learning projects, which enable to:
PyTorch Lightning and Hydra serve as the foundation upon this template. Such reasonable technology stack for deep learning prototyping offers a comprehensive and seamless solution, allowing you to effortlessly explore different tasks across a variety of hardware accelerators such as CPUs, multi-GPUs, and TPUs. Furthermore, it includes a curated collection of best practices and extensive documentation for greater clarity and comprehension.
This template could be used as is for some basic tasks like Classification, Segmentation or Metric Learning, or be easily extended for any other tasks due to high-level modularity and scalable structure.
As a baseline I have used gorgeous Lightning Hydra Template, reshaped and polished it, and implemented more features which can improve overall efficiency of workflow and reproducibility.
# clone template git clone https://github.com/gorodnitskiy/yet-another-lightning-hydra-template cd yet-another-lightning-hydra-template # install requirements pip install -r requirements.txt
Or run the project in docker. See more in Docker section.
PyTorch Lightning - a lightweight deep learning framework / PyTorch wrapper for professional AI researchers and machine learning engineers who need maximal flexibility without sacrificing performance at scale.
Hydra - a framework that simplifies configuring complex applications. The key feature is the ability to dynamically create a hierarchical configuration by composition and override it through config files and the command line.
The structure of a machine learning project can vary depending on the specific requirements and goals of the project, as well as the tools and frameworks being used. However, here is a general outline of a common directory structure for a machine learning project:
src/data/logs/tests/notebooks/, docs/, etc.In this particular case, the directory structure looks like:
├── configs <- Hydra configuration files
│ ├── callbacks <- Callbacks configs
│ ├── datamodule <- Datamodule configs
│ ├── debug <- Debugging configs
│ ├── experiment <- Experiment configs
│ ├── extras <- Extra utilities configs
│ ├── hparams_search <- Hyperparameter search configs
│ ├── hydra <- Hydra settings configs
│ ├── local <- Local configs
│ ├── logger <- Logger configs
│ ├── module <- Module configs
│ ├── paths <- Project paths configs
│ ├── trainer <- Trainer configs
│ │
│ ├── eval.yaml <- Main config for evaluation
│ └── train.yaml <- Main config for training
│
├── data <- Project data
├── logs <- Logs generated by hydra, lightning loggers, etc.
├── notebooks <- Jupyter notebooks.
├── scripts <- Shell scripts
│
├── src <- Source code
│ ├── callbacks <- Additional callbacks
│ ├── datamodules <- Lightning datamodules
│ ├── modules <- Lightning modules
│ ├── utils <- Utility scripts
│ │
│ ├── eval.py <- Run evaluation
│ └── train.py <- Run training
│
├── tests <- Tests of any kind
│
├── .dockerignore <- List of files ignored by docker
├── .gitattributes <- List of additional attributes to pathnames
├── .gitignore <- List of files ignored by git
├── .pre-commit-config.yaml <- Configuration of pre-commit hooks for code formatting
├── Dockerfile <- Dockerfile
├── Makefile <- Makefile with commands like `make train` or `make test`
├── pyproject.toml <- Configuration options for testing and linting
├── requirements.txt <- File for installing python dependencies
├── setup.py <- File for installing project as a package
└── README.md
Before starting a project, you need to think about the following things to unsure in results reproducibility:
This template could be used as is for some basic tasks like Classification, Segmentation or Metric Learning approach, but if you need to do something more complex, here it is a general workflow:
python src/train.py experiment=experiment_name.yaml
# using Hydra multirun mode python src/train.py -m hparams_search=mnist_optuna
python src/train.py -m logger=csv module.optimizer.weight_decay=0.,0.00001,0.0001
The template contains example with MNIST classification, which uses for tests by the way.
If you run python src/train.py, you will get something like this:

At the start, you need to create PyTorch Dataset for you task. It has to include __getitem__ and __len__ methods.
Maybe you can use as is or easily modify already implemented Datasets in the template.
See more details in PyTorch documentation.
Also, it could be useful to see section about how it is possible to save data for training and evaluation.
Then, you need to create DataModule using PyTorch Lightning DataModule API. By default, API has the following methods:
prepare_data (optional): perform data operations on CPU via a single process, like load and preprocess data, etc.setup (optional): perform data operations on every GPU, like train/val/test splits, create datasets, etc.train_dataloader: used to generate the training dataloader(s)val_dataloader: used to generate the validation dataloader(s)test_dataloader: used to generate the test dataloader(s)predict_dataloader (optional): used to generate the prediction dataloader(s)</details>from typing import Any, Dict, List, Optional, Union from torch.utils.data import DataLoader, Dataset from pytorch_lightning import LightningDataModule class YourDataModule(LightningDataModule): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__() self.train_set: Optional[Dataset] = None self.valid_set: Optional[Dataset] = None self.test_set: Optional[Dataset] = None self.predict_set: Optional[Dataset] = None ... def prepare_data(self) -> None: # (Optional) Perform data operations on CPU via a single process # - load data # - preprocess data # - etc. ... def setup(self, stage: str) -> None: # (Optional) Perform data operations on every GPU: # - count number of classes # - build vocabulary # - perform train/val/test splits # - create datasets # - apply transforms (which defined explicitly in your datamodule) # - etc. if not self.train_set and not self.valid_set and not self.test_set: self.train_set = ... self.valid_set = ... self.test_set = ... if (stage == "predict") and not self.predict_set: self.predict_set = ... def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]: # Used to generate the training dataloader(s) # This is the dataloader that the Trainer `fit()` method uses return DataLoader(self.train_set, ...) def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # Used to generate the validation dataloader(s) # This is the dataloader that the Trainer `fit()` and `validate()` methods uses return DataLoader(self.valid_set, ...) def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # Used to generate the test dataloader(s) # This is the dataloader that the Trainer `test()` method uses return DataLoader(self.test_set, ...) def predict_dataloader(self) -> Union[DataLoader, List[DataLoader]]: # Used to generate the prediction dataloader(s) # This is the dataloader that the Trainer `predict()` method uses return DataLoader(self.predict_set, ...) def teardown(self, stage: str) -> None: # Used to clean-up when the run is finished ...
See examples of datamodule configs in configs/datamodule folder.
By default, the template contains the following DataModules:
train_dataloader, val_dataloader and
test_dataloader return single DataLoader, predict_dataloader returns list of DataLoaderstrain_dataloader return dict of DataLoaders,
val_dataloader, test_dataloader and predict_dataloader return list of DataLoadersIn the template, DataModules has _get_dataset_ method to simplify Datasets instantiation.
Next, your need to create LightningModule using PyTorch Lightning LightningModule API. Minimum API has the following methods:
forward: use for inference only (separate from training_step)training_step: the complete training loopvalidation_step: the complete validation looptest_step: the complete test looppredict_step: the complete prediction loopconfigure_optimizers: define optimizers and LR schedulersAlso, you can override optional methods for each step to perform additional logic:
training_step_end: training step end operationstraining_epoch_end: training epoch end operationsvalidation_step_end: validation step end operationsvalidation_epoch_end: validation epoch end operationstest_step_end: test step end operationstest_epoch_end: test epoch end operations</details>from typing import Any from pytorch_lightning import LightningModule class LitModel(LightningModule): def __init__(self, *args: Any, **kwargs: Any): super().__init__() ... def forward(self, *args: Any, **kwargs: Any): ... def training_step(self, *args: Any, **kwargs: Any): ... def training_step_end(self, step_output: Any): ... def training_epoch_end(self, outputs: Any): ... def validation_step(self, *args: Any, **kwargs: Any): ... def validation_step_end(self, step_output: Any): ... def validation_epoch_end(self, outputs: Any): ... def test_step(self, *args: Any, **kwargs: Any): ... def test_step_end(self, step_output: Any): ... def test_epoch_end(self, outputs: Any): ... def configure_optimizers(self): ... def any_extra_hook(self, *args: Any, **kwargs: Any): ...
In the template, LightningModule has model_step method to adjust repeated operations, like forward or loss
calculation, which are required in training_step, validation_step and test_step.
The template offers the following Metrics API:
main metric: main metric, which also uses for all callbacks or trackers like model_checkpoint, early_stopping
or scheduler.monitor.valid_best metric: use for tracking the best validation metric. Usually it can be MaxMetric or MinMetric.additional metrics: additional metrics.Each metric config should contain _target_ key with metric class name and other parameters which are required by
metric. The template allows to use any metrics, for example from
torchmetrics or implemented by yourself (see examples in
modules/metrics/components/ or torchmetrics API).
See more details about implemented Metrics API and metrics config as a part of
network configs in configs/module/network folder.
Metric config example:
metrics: main: _target_: "torchmetrics.Accuracy" task: "binary" valid_best: _target_: "torchmetrics.MaxMetric" additional: AUROC: _target_: "torchmetrics.AUROC" task: "binary"
Also, the template includes few manually implemented metrics:
The template offers the following Losses API:
_target_ key with loss class name and other parameters which are required by loss.weight string in name will be wrapped by torch.tensor and cast to torch.float type before
passing to loss due to requirements from most of the losses.The template allows to use any losses, for example from
PyTorch or implemented by yourself (see examples in
modules/losses/components/).
See more details about implemented Losses API and loss config as a part of
network configs in configs/module/network folder.
Loss config examples:
loss: _target_: "torch.nn.CrossEntropyLoss"
loss: _target_: "torch.nn.BCEWithLogitsLoss" pos_weight: [0.25]
loss: _target_:


AI辅助编程,代码自动修复
Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。


AI一键生成PPT,就用博思AIPPT!
博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。


AI赋能电商视觉革命,一站式智能商拍平台
潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。


企业专属的AI法律顾问
iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。


稳定高效的流量提升解决方案,助力品牌曝光
稳定高效的流量提升解决方案,助力品牌曝光


最新版Sora2模型免费使用,一键生成无水印视频
最新版Sora2模型免费使用,一键生成无水印视频


实时语音翻译/同声传译工具
Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。


选题、配图、成文,一站式创作,让内容运营更高效
讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。


最强AI数据分析助手
小浣熊家族Raccoon,您的AI智能助手,致力于通过先进 的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。


像人一样思考的AI智能体
imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。
最新AI工具、AI资讯
独家AI资源、AI项目落地

微信扫一扫关注公众号