{"id":37062988,"url":"https://github.com/hal-42/alchemycat","last_synced_at":"2026-01-14T07:01:12.453Z","repository":{"id":56085760,"uuid":"226537082","full_name":"HAL-42/AlchemyCat","owner":"HAL-42","description":"Alchemy Cat —— 🔥Config System for SOTA","archived":false,"fork":false,"pushed_at":"2025-12-18T14:21:36.000Z","size":4201,"stargazers_count":111,"open_issues_count":2,"forks_count":7,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-12-21T17:36:54.877Z","etag":null,"topics":["auto-tuning","computer-vision","config","deep-learning","machine-learning","parameter-tuning"],"latest_commit_sha":null,"homepage":"https://github.com/HAL-42/AlchemyCat","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/HAL-42.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2019-12-07T15:43:49.000Z","updated_at":"2025-12-18T14:21:40.000Z","dependencies_parsed_at":"2023-11-26T17:27:39.442Z","dependency_job_id":"bfbd22d7-e005-4617-87f5-b4e2a44c31b9","html_url":"https://github.com/HAL-42/AlchemyCat","commit_stats":null,"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/HAL-42/AlchemyCat","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HAL-42%2FAlchemyCat","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HAL-42%2FAlchemyCat/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HAL-42%2FAlchemyCat/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HAL-42%2FAlchemyCat/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HAL-42","download_url":"https://codeload.github.com/HAL-42/AlchemyCat/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HAL-42%2FAlchemyCat/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28412480,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T05:26:33.345Z","status":"ssl_error","status_checked_at":"2026-01-14T05:21:57.251Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auto-tuning","computer-vision","config","deep-learning","machine-learning","parameter-tuning"],"created_at":"2026-01-14T07:01:11.047Z","updated_at":"2026-01-14T07:01:12.426Z","avatar_url":"https://github.com/HAL-42.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Alchemy Cat —— 🔥Config System for SOTA\n\n\u003cdiv align=\"center\"\u003e\n\n![GitHub commit activity](https://img.shields.io/github/commit-activity/y/HAL-42/AlchemyCat)\n\u003cimg src=\"https://img.shields.io/github/stars/HAL-42/AlchemyCat?color=yellow\" alt=\"Stars\"\u003e\n\u003cimg src=\"https://img.shields.io/github/issues/HAL-42/AlchemyCat?color=red\" alt=\"Issues\"\u003e\n![GitHub License](https://img.shields.io/github/license/HAL-42/AlchemyCat?color=cyan)\n\u003cbr\u003e\n[![PyPI version](https://badge.fury.io/py/alchemy-cat.svg)](https://badge.fury.io/py/alchemy-cat)\n![PyPI - Downloads](https://img.shields.io/pypi/dm/alchemy-cat?color=yellow)\n\u003cimg src=\"https://img.shields.io/badge/python-3.9-purple.svg\" alt=\"Python\"\u003e \u003cbr\u003e\n\n\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n\u003ca href=\"README.md\"\u003eEnglish\u003c/a\u003e | \u003ca href=\"README_CN.md\"\u003e中文\u003c/a\u003e\n\u003c/div\u003e\n\u003cbr\u003e\n\n![banner](https://raw.githubusercontent.com/HAL-42/AlchemyCat/master/docs/figs/dl_config_logo.png)\n\n\u003cdiv align=\"center\"\u003e\n\n[🚀Introduction](https://github.com/HAL-42/AlchemyCat/blob/master/README.md#-introduction) | [📦Installation](https://github.com/HAL-42/AlchemyCat/blob/master/README.md#-installation) | [🚚Migration](https://github.com/HAL-42/AlchemyCat/blob/master/README.md#-migration) | [📖Documentation](https://github.com/HAL-42/AlchemyCat/blob/master/README.md#-documentation-)\n\n\u003c/div\u003e\n\n# \u003cdiv align=\"center\"\u003e🚀 Introduction\u003c/div\u003e\n\nWhen developing machine learning algorithms, we often bother with:\n* Config files (YAML / YACS / MMCV) are lengthy and complex. If entries are interdependent, extra caution is needed to avoid errors when modifying them.\n* Parameter tuning requires rewriting the config for each parameter set, leading to code duplication and difficulty in tracking changes.\n* Manually traversing the parameter space and summarizing results during parameter tuning is time-consuming and inefficient.\n* Insufficient parameter tuning can obscure effective designs.\n* Effective methods may not achieve SOTA due to insufficient parameter tuning, reducing persuasiveness.\n\nAlchemyCat is a config system designed for machine learning research to address such issues. It helps researchers to fully explore the parameter tuning potential by simplifying repetitive tasks like reproduction, modifying configs, and hyperparameter tuning\n\nThe table below compares AlchemyCat with existing config systems (😡 not support, 🤔 limited support, 🥳 supported):\n\n| Feature                    | argparse | yaml | YACS | mmcv | AlchemyCat |\n|----------------------------|----------|------|------|------|------------|\n| Reproducible               | 😡       | 🥳   | 🥳   | 🥳   | 🥳         |\n| IDE Jump                   | 😡       | 😡   | 🥳   | 🥳   | 🥳         |\n| Inheritance                | 😡       | 😡   | 🤔   | 🤔   | 🥳         |\n| Composition                | 😡       | 😡   | 🤔   | 🤔   | 🥳         |\n| dependency                 | 😡       | 😡   | 😡   | 😡   | 🥳         |\n| Automatic Parameter Tuning | 😡       | 😡   | 😡   | 😡   | 🥳         |\n\nAlchemyCat implements all features of current popular config systems, while fully considering various special cases, ensuring stability. AlchemyCat distinguishes itself by:\n* Readable: The syntax is simple, elegant, and Pythonic.\n* Reusable: Supports **inheritance** and **composition** of configs, reducing redundancy and enhancing reusability.\n* Maintainable: Allows for establishing **dependency** between config items, enabling global synchronization with a single change.\n* Supports auto parameter tuning and result summarization without needing to modify original configs or training codes.\n\n[Migrate](https://github.com/HAL-42/AlchemyCat/blob/master/README.md#-migration) from config systems listed above to AlchemyCat is effortless. Just spend 15 minutes reading the [documentation](https://github.com/HAL-42/AlchemyCat/blob/master/README.md#-documentation-) and apply AlchemyCat to your project, and your GPU will never be idle again!\n\n## Quick Glance\nDeep learning relies on numerous empirical hyperparameters, such as learning rate, loss weights, max iterations, sliding window size, drop probability, thresholds, and even random seeds.\n\nThe relationship between hyperparameters and performance is hard to predict theoretically. The only certainty is that arbitrarily chosen hyperparameters are unlikely to be optimal. Practice has shown that grid search through the hyperparameter space can significantly enhance model performance; sometimes its effect even surpasses so-called \"contributions.\" Achieving SOTA often depends on this!\n\nAlchemyCat offers an auto parameter-tuner that seamlessly integrates with existing config systems to explore the hyperparameter space and summarize experiment results automatically. Using this tool requires no modifications to the original config or training code.\n\nFor example, with [MMSeg](https://github.com/open-mmlab/mmsegmentation) users only need to write a tunable config inherited from MMSeg's base config and define the parameter search space:\n```python\n# -- configs/deeplabv3plus/tune_bs,iter/cfg.py --\nfrom alchemy_cat import Cfg2Tune, Param2Tune\n\n# Inherit from standard mmcv config.\ncfg = Cfg2Tune(caps='configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-40k_voc12aug-512x512.py')\n\n# Inherit and override\ncfg.model.auxiliary_head.loss_decode.loss_weight = 0.2\n\n# Tuning parameters: grid search batch_size and max_iters\ncfg.train_dataloader.batch_size = Param2Tune([4, 8])\ncfg.train_cfg.max_iters = Param2Tune([20_000, 40_000])\n# ...\n```\nNext, write a script specifying how to run a single config and read its results:\n```python\n# -- tools/tune_dist_train.py --\nimport argparse, subprocess\nfrom alchemy_cat.dl_config import Cfg2TuneRunner, Config\nfrom alchemy_cat.dl_config.examples.read_mmcv_metric import get_metric\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--cfg2tune', type=str)            # Path to the tunable config\nparser.add_argument('--num_gpu', type=int, default=2)  # Number of GPUs for each task\nargs = parser.parse_args()\n\nrunner = Cfg2TuneRunner(args.cfg2tune, experiment_root='work_dirs', work_gpu_num=args.num_gpu)\n\n@runner.register_work_fn  # Run experiment for each param combination with mmcv official train script\ndef work(pkl_idx: int, cfg: Config, cfg_pkl: str, cfg_rslt_dir: str, cuda_env: dict[str, str]):\n    mmcv_cfg = cfg.save_mmcv(cfg_rslt_dir + '/mmcv_config.py')\n    subprocess.run(f'./tools/dist_train.sh {mmcv_cfg} {args.num_gpu}', env=cuda_env, shell=True)\n\n@runner.register_gather_metric_fn    # Optional, gather metric of each config\ndef gather_metric(cfg: Config, cfg_rslt_dir: str, run_rslt, param_comb) -\u003e dict[str, float]:\n    return get_metric(cfg_rslt_dir)  # {'aAcc': xxx, 'mIoU': xxx, 'mAcc': xxx}\n\nrunner.tuning()\n```\nRun `CUDA_VISIBLE_DEVICES=0,1,2,3 python tools/tune_dist_train.py --cfg2tune configs/deeplabv3plus/tune_bs,iter/cfg.py`, which will automatically search the parameter space in parallel and summarize the experiment results as follows:\n\n\u003cdiv align = \"center\"\u003e\n\u003cimg  src=\"https://raw.githubusercontent.com/HAL-42/AlchemyCat/master/docs/figs/readme-teaser-excel.png\" width=\"500\" /\u003e\n\u003c/div\u003e\n\nIn fact, the above config is still incomplete for some hyperparameters are interdependent and need to be adjusted together. For instance, the learning rate should scale with the batch size. AlchemyCat uses **dependency** to manage these relationships; when a dependency source changes, related dependencies automatically update for consistency. The complete config with dependencies is:\n```python\n# -- configs/deeplabv3plus/tune_bs,iter/cfg.py --\nfrom alchemy_cat import Cfg2Tune, Param2Tune, P_DEP\n\n# Inherit from standard mmcv config.\ncfg = Cfg2Tune(caps='configs/deeplabv3plus/deeplabv3plus_r50-d8_4xb4-40k_voc12aug-512x512.py')\n\n# Inherit and override\ncfg.model.auxiliary_head.loss_decode.loss_weight = 0.2\n\n# Tuning parameters: grid search batch_size and max_iters\ncfg.train_dataloader.batch_size = Param2Tune([4, 8])\ncfg.train_cfg.max_iters = Param2Tune([20_000, 40_000])\n\n# Dependencies:\n# 1) learning rate increase with batch_size\ncfg.optim_wrapper.optimizer.lr = P_DEP(lambda c: (c.train_dataloader.batch_size / 8) * 0.01)\n\n# 2) end of param_scheduler increase with max_iters\n@cfg.set_DEP()\ndef param_scheduler(c):\n    return dict(\n        type='PolyLR',\n        eta_min=1e-4,\n        power=0.9,\n        begin=0,\n        end=c.train_cfg.max_iters,\n        by_epoch=False)\n```\n\u003e [!NOTE]\n\u003e In the example above, defining dependencies might seem needless since they can be computed directly. However, when combined with **inheritance**, setting dependencies in the base config allows tunable configs to focus on key hyperparameters without worrying about trivial dependency details. Refer to the [documentation](#dependency) for details.\n\n# \u003cdiv align=\"center\"\u003e📦 Installation\u003c/div\u003e\n```bash\npip install alchemy-cat\n```\n\n# \u003cdiv align=\"center\"\u003e🚚 Migration\u003c/div\u003e\n\u003cdetails\u003e\n\u003csummary\u003e How to migrate from YAML / YACS / MMCV \u003c/summary\u003e\n\nσ`∀´)σ Just kidding! No migration is needed. AlchemyCat can direct read and write YAML / YACS / MMCV config files:\n\n```python\nfrom alchemy_cat.dl_config import load_config, Config\n\n# READ YAML / YACS / MMCV config to alchemy_cat.Config\ncfg = load_config('path/to/yaml_config.yaml or yacs_config.py or mmcv_config.py')\n# Init alchemy_cat.Config with YAML / YACS / MMCV config\ncfg = Config('path/to/yaml_config.yaml or yacs_config.py or mmcv_config.py')\n# alchemy_cat.Config inherits from YAML / YACS / MMCV config\ncfg = Config(caps='path/to/yaml_config.yaml or yacs_config.py or mmcv_config.py')\n\nprint(cfg.model.backbone)  # Access config item\n\ncfg.save_yaml('path/to/save.yaml')  # Save to YAML config\ncfg.save_mmcv('path/to/save.py')    # Save to MMCV config\ncfg.save_py('path/to/save.py')      # Save to AlchemyCat config\n```\nWe also provide a script to convert between different config formats:\n```bash\npython -m alchemy_cat.dl_config.from_x_to_y --x X --y Y --y_type=yaml/mmcv/alchemy-cat\n```\nwhere:\n* `--x`: Source config file path, can be YAML / YACS / MMCV / AlchemyCat config.\n* `--y`: Target config file path.\n* `--y_type`: Target config format, can be `yaml`, `mmcv`, or `alchemy-cat`.\n\n\u003c/details\u003e\n\n# \u003cdiv align=\"center\"\u003e📖 Documentation \u003c/div\u003e\n\n## Basic Usage\nAlchemyCat ensures a one-to-one correspondence between each configuration and its unique experimental record, with the bijective relationship ensuring the experiment's reproducibility.\n```text\nconfig C + algorithm code A ——\u003e reproducible experiment E(C, A)\n```\nThe experimental directory is automatically generated, mirroring the relative path of the configuration file. This path can include multi-level directories and special characters such as spaces, commas, and equal signs. Such flexibility aids in categorizing experiments for clear management. For instance:\n```text\n.\n├── configs\n│   ├── MNIST\n│   │   ├── resnet18,wd=1e-5@run2\n│   │   │   └── cfg.py\n│   │   └── vgg,lr=1e-2\n│   │       └── cfg.py\n│   └── VOC2012\n│       └── swin-T,γ=10\n│           └── 10 epoch\n│               └── cfg.py\n└── experiment\n    ├── MNIST\n    │   ├── resnet18,wd=1e-5@run2\n    │   │   └── xxx.log\n    │   └── vgg,lr=1e-2\n    │       └── xxx.log\n    └── VOC2012\n        └── swin-T,γ=10\n            └── 10 epoch\n                └── xxx.log\n```\n\u003e [!TIP]\n\u003e **Best Practice: Avoid having '.' in the path. By following this best practice, relative imports can be used in `cfg.py`, and functions and classes defined within it can be pickled.**\n\n\nLet's begin with an incomplete example to demonstrate writing and loading a config. First, create the [config file](alchemy_cat/dl_config/examples/configs/mnist/plain_usage/cfg.py):\n```python\n# -- [INCOMPLETE] configs/mnist/plain_usage/cfg.py --\n\nfrom torchvision.datasets import MNIST\nfrom alchemy_cat.dl_config import Config\n\ncfg = Config()\n\ncfg.rand_seed = 0\n\ncfg.dt.cls = MNIST\ncfg.dt.ini.root = '/tmp/data'\ncfg.dt.ini.train = True\n\n# ... Code Omitted.\n```\nHere, we first instantiate a `Config` object `cfg`, and then add config items through attribute operator `.`. Config items can be any Python objects, including functions, methods, and classes.\n\n\u003e [!TIP]\n\u003e **Best Practice: We prefer specifying functions or classes directly in config over using strings/semaphores to control the program behavior. This enables IDE navigation, simplifying reading and debugging.** Refer to the \"Advanced Usage\" chapter's \"Dependency Injection Configuration\" for details.\n\n\n`Config` is a subclass of Python's `dict`. The above code defines a nested dictionary with a **tree structure**:\n```text\n\u003e\u003e\u003e print(cfg.to_dict())\n{'rand_seed': 0,\n 'dt': {'cls': \u003cclass 'torchvision.datasets.mnist.MNIST'\u003e,\n        'ini': {'root': '/tmp/data', 'train': True}}}\n```\n`Config` implements all API of Python `dict`:\n```test\n\u003e\u003e\u003e cfg.keys()\ndict_keys(['rand_seed', 'dt'])\n\n\u003e\u003e\u003e cfg['dt']['ini']['root']\n'/tmp/data'\n\n\u003e\u003e\u003e {**cfg['dt']['ini'], 'download': True}\n{'root': '/tmp/data', 'train': True, 'download': True}\n```\n\nYou can initialize a `Config` object using `dict` (yaml, json) or its subclasses (YACS, mmcv.Config).\n```text\n\u003e\u003e\u003e Config({'rand_seed': 0, 'dt': {'cls': MNIST, 'ini': {'root': '/tmp/data', 'train': True}}})\n{'rand_seed': 0, 'dt': {'cls': \u003cclass 'torchvision.datasets.mnist.MNIST'\u003e, 'ini': {'root': '/tmp/data', 'train': True}}}\n```\n\nUsing operator `.` to read and write `cfg` will be clearer. For instance, the following code creates and initializes the `MNIST` dataset based on the config:\n```text\n\u003e\u003e\u003e dataset = cfg.dt.cls(**cfg.dt.ini)\n\u003e\u003e\u003e dataset\nDataset MNIST\n    Number of datapoints: 60000\n    Root location: /tmp/data\n    Split: Train\n```\nAccessing a non-existent key returns an empty dictionary, which should be treated as `False`:\n```text\n\u003e\u003e\u003e cfg.not_exit\n{}\n```\n\nIn the [main code](alchemy_cat/dl_config/examples/train.py), use the following code to load the config:\n```python\n# # [INCOMPLETE] -- train.py --\n\nfrom alchemy_cat.dl_config import load_config\ncfg = load_config('configs/mnist/base/cfg.py', experiments_root='/tmp/experiment', config_root='configs')\n# ... Code Omitted.\ntorch.save(model.state_dict(), f\"{cfg.rslt_dir}/model_{epoch}.pth\")  # Save all experiment results to cfg.rslt_dir.\n```\n\nThe `load_config` imports `cfg` from `configs/mnist/base/cfg.py`, handling inheritance and dependencies. Given the experiment root directory `experiments_root` and config root directory `config_root`, it auto creates an experiment directory at `experiment/mnist/base` and assign it to `cfg.rslt_dir`. All experimental results should be saved to `cfg.rslt_dir`.\n\nThe loaded `cfg` is read-only by default (`cfg.is_frozen == True`). To modify, unfreeze `cfg` with `cfg.unfreeze()`.\n\n### Summary of This Chapter\n* The config file offers a `Config` object `cfg`, a nested dictionary with a tree structure, allowing read and write via the `.` operator.\n* Accessing non-existent keys in `cfg` returns a one-time empty dictionary considered as `False`.\n* Use `load_config` to load the config file. The experiment path will be auto created and assigned to `cfg.rslt_dir`.\n\n## Inheritance\nThe new config can inherit the existing base config, written as `cfg = Config(caps='base_cfg.py')`. The new config only needs to override or add items, with rest items reusing the base config. For example, with [base config](alchemy_cat/dl_config/examples/configs/mnist/plain_usage/cfg.py):\n```python\n# -- [INCOMPLETE] configs/mnist/plain_usage/cfg.py --\n\n# ... Code Omitted.\n\ncfg.loader.ini.batch_size = 128\ncfg.loader.ini.num_workers = 2\n\ncfg.opt.cls = optim.AdamW\ncfg.opt.ini.lr = 0.01\n\n# ... Code Omitted.\n```\nTo double the batch size, [new config](alchemy_cat/dl_config/examples/configs/mnist/plain_usage,2xbs/cfg.py) can be written as:\n```python\n# -- configs/mnist/plain_usage,2xbs/cfg.py --\n\nfrom alchemy_cat.dl_config import Config\n\ncfg = Config(caps='configs/mnist/plain_usage/cfg.py')  # Inherit from base config.\n\ncfg.loader.ini.batch_size = 128 * 2  # Double batch size.\n\ncfg.opt.ini.lr = 0.01 * 2  # Linear scaling rule, see https://arxiv.org/abs/1706.02677\n```\nInheritance behaves like `dict.update`. The key difference is that if both config have keys with the same name and their values are `Config` instance (naming config subtree), we recursively update within these subtrees. Thus, the new config can modify `cfg.loader.ini.batch_size` while inheriting `cfg.loader.ini.num_workers`.\n```text\n\u003e\u003e\u003e base_cfg = load_config('configs/mnist/plain_usage/cfg.py', create_rslt_dir=False)\n\u003e\u003e\u003e new_cfg = load_config('configs/mnist/plain_usage,2xbs/cfg.py', create_rslt_dir=False)\n\u003e\u003e\u003e base_cfg.loader.ini\n{'batch_size': 128, 'num_workers': 2}\n\u003e\u003e\u003e new_cfg.loader.ini\n{'batch_size': 256, 'num_workers': 2}\n```\nTo overwrite the entire config subtree in the new config, set this subtree to \"override\", [e.g.](alchemy_cat/dl_config/examples/configs/mnist/plain_usage,override_loader/cfg.py) :\n```python\n# -- configs/mnist/plain_usage,override_loader/cfg.py --\n\nfrom alchemy_cat.dl_config import Config\n\ncfg = Config(caps='configs/mnist/plain_usage/cfg.py')  # Inherit from base config.\n\ncfg.loader.ini.override()  # Set subtree as whole.\ncfg.loader.ini.shuffle = False\ncfg.loader.ini.drop_last = False\n```\n`cfg.loader.ini` will now be solely defined by the new config:\n```text\n\u003e\u003e\u003e base_cfg = load_config('configs/mnist/plain_usage/cfg.py', create_rslt_dir=False)\n\u003e\u003e\u003e new_cfg = load_config('configs/mnist/plain_usage,2xbs/cfg.py', create_rslt_dir=False)\n\u003e\u003e\u003e base_cfg.loader.ini\n{'batch_size': 128, 'num_workers': 2}\n\u003e\u003e\u003e new_cfg.loader.ini\n{'shuffle': False, 'drop_last': False}\n```\nNaturally, a base config can inherit from another base config, known as chain inheritance.\n\nMultiple inheritance is also supported, written as `cfg = Config(caps=('base.py', 'patch1.py', 'patch2.py', ...))`, creating an inheritance chain of `base -\u003e patch1 -\u003e patch2 -\u003e current cfg`. The base configs on the right are often used patches to batch add config items. For example, this [patch](alchemy_cat/dl_config/examples/configs/patches/cifar10.py) includes CIFAR10 dataset configurations:\n```python\n# -- configs/patches/cifar10.py --\n\nimport torchvision.transforms as T\nfrom torchvision.datasets import CIFAR10\n\nfrom alchemy_cat.dl_config import Config\n\ncfg = Config()\n\ncfg.dt.override()\ncfg.dt.cls = CIFAR10\ncfg.dt.ini.root = '/tmp/data'\ncfg.dt.ini.transform = T.Compose([T.ToTensor(), T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n```\nTo switch to CIFAR10, [new config](alchemy_cat/dl_config/examples/configs/mnist/plain_usage,cifar10/cfg.py) only need to inherit the patch:\n```python\n# -- configs/mnist/plain_usage,cifar10/cfg.py --\n\nfrom alchemy_cat.dl_config import Config\n\ncfg = Config(caps=('configs/mnist/plain_usage/cfg.py', 'alchemy_cat/dl_config/examples/configs/patches/cifar10.py'))\n```\n```text\n\u003e\u003e\u003e cfg = load_config('configs/mnist/plain_usage,cifar10/cfg.py', create_rslt_dir=False)\n\u003e\u003e\u003e cfg.dt\n{'cls': torchvision.datasets.cifar.CIFAR10,\n 'ini': {'root': '/tmp/data',\n  'transform': Compose(\n      ToTensor()\n      Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n  )}}\n```\n\u003e _Inheritance Implementation Details_\n\u003e\n\u003e We copy the base config tree and update it with the new config, ensuring isolation between them. This means changes to the new config do not affect the base. Complex inheritance like diamond inheritance is supported but not recommended due to readability issues. \\\n\u003e Note that leaf node values are passed by reference; modifying them inplace will affect the entire inheritance chain.\n\n### Summary of This Chapter\n* The new config can leverage inheritance to reuse the base config and modifies or adds some items.\n* The new config updates the base config recursively. Use `Config.override` to revert to the `dict.update` method for updates.\n* `Config` supports chain and multiple inheritance, allowing for more fine-grained reuse.\n\n## Dependency\nIn the [previous](#inheritance) example, changing the batch size in the new configuration also alters the learning rate. This interdependence is called \"dependency.\"\n\nWhen modifying a config item, it's common to forget its dependencies. AlchemyCat lets you define dependencies, changing the dependency source updates all dependent items automatically. [For example](alchemy_cat/dl_config/examples/configs/mnist/base/cfg.py):\n\n```python\n# -- [INCOMPLETE] configs/mnist/base/cfg.py --\n\nfrom alchemy_cat.dl_config import Config, DEP\n# ... Code Omitted.\n\ncfg.loader.ini.batch_size = 128\n# ... Code Omitted.\ncfg.opt.ini.lr = DEP(lambda c: c.loader.ini.batch_size // 128 * 0.01)  # Linear scaling rule.\n\n# ... Code Omitted.\n```\nThe learning rate `cfg.opt.ini.lr` is calculated as a dependency `DEP` using the batch size `cfg.loader.ini.batch_size`. `DEP` takes a function with `cfg` as an argument and returns the dependency value.\n\nIn the [new config](alchemy_cat/dl_config/examples/configs/mnist/base,2xbs/cfg.py), we only need to modify the batch size, and the learning rate will update automatically:\n```python\n# -- configs/mnist/base,2xbs/cfg.py --\n\nfrom alchemy_cat.dl_config import Config\n\ncfg = Config(caps='configs/mnist/base/cfg.py')\n\ncfg.loader.ini.batch_size = 128 * 2  # Double batch size, learning rate will be doubled automatically.\n```\n```text\n\u003e\u003e\u003e cfg = load_config('configs/mnist/base,2xbs/cfg.py', create_rslt_dir=False)\n\u003e\u003e\u003e cfg.loader.ini.batch_size\n256\n\u003e\u003e\u003e cfg.opt.ini.lr\n0.02\n```\nBelow is a more complex [example](alchemy_cat/dl_config/examples/configs/mnist/base/cfg.py):\n```python\n# -- configs/mnist/base/cfg.py --\n\n# ... Code Omitted.\n\ncfg.sched.epochs = 30\n@cfg.sched.set_DEP(name='warm_epochs', priority=0)  # kwarg `name` is not necessary\ndef warm_epochs(c: Config) -\u003e int:  # warm_epochs = 10% of total epochs\n    return round(0.1 * c.sched.epochs)\n\ncfg.sched.warm.cls = sched.LinearLR\ncfg.sched.warm.ini.total_iters = DEP(lambda c: c.sched.warm_epochs, priority=1)\ncfg.sched.warm.ini.start_factor = 1e-5\ncfg.sched.warm.ini.end_factor = 1.\n\ncfg.sched.main.cls = sched.CosineAnnealingLR\ncfg.sched.main.ini.T_max = DEP(lambda c: c.sched.epochs - c.sched.warm.ini.total_iters,\n                               priority=2)  # main_epochs = total_epochs - warm_epochs\n\n# ... Code Omitted.\n```\n```text\n\u003e\u003e\u003e print(cfg.sched.to_txt(prefix='cfg.sched.'))  # A pretty print of the config tree.\ncfg.sched = Config()\n# ------- ↓ LEAVES ↓ ------- #\ncfg.sched.epochs = 30\ncfg.sched.warm_epochs = 3\ncfg.sched.warm.cls = \u003cclass 'torch.optim.lr_scheduler.LinearLR'\u003e\ncfg.sched.warm.ini.total_iters = 3\ncfg.sched.warm.ini.start_factor = 1e-05\ncfg.sched.warm.ini.end_factor = 1.0\ncfg.sched.main.cls = \u003cclass 'torch.optim.lr_scheduler.CosineAnnealingLR'\u003e\ncfg.sched.main.ini.T_max = 27\n```\nIn the code, `cfg.sched.epochs` determines total training epochs, which is also the dependency source. Warm-up epochs `cfg.sched.warm_epochs` are 10% of this total, and main epochs `cfg.sched.main.ini.T_max` is the remainder. Adjusting total training epochs updates both warm-up and main epochs automatically.\n\nThe dependency `cfg.sched.warm_epochs` is defined using the `Config.set_DEP` decorator. The decorated function, passed as the first parameter of `DEP`, computes the dependency. The key name of dependency can be specified via the keyword argument `name`; if omitted, it defaults to the function's name. For complex computations, using a decorator for definition is recommended.\n\nWhen a dependency relies on another dependency, they must be computed in the correct order. By default, this is the defined order. The `priority` parameter can specify computation order: smaller `priority` compute earlier. For instance, `cfg.sched.warm_epochs` depended by `cfg.sched.warm.ini.total_iters`, which is depended by `cfg.sched.main.ini.T_max`, so their `priority` increase sequentially.\n\n### Summary of This Chapter\n* A dependency is defined when one config item relies on another. Changing the dependency source will automatically recalculate the dependency based on the calculation function.\n* Dependencies can be defined by `DEP(...)` or the `Config.set_DEP` decorator.\n* If dependencies are interdependent, use the `priority` parameter to specify the computation order; otherwise, they resolve in the order of definition.\n\n## Composition\nComposition allows reusing configs by compose predefined config subtrees to form a complete config. For instance, the following [config subtree](alchemy_cat/dl_config/examples/configs/addons/linear_warm_cos_sched.py) defines a learning rate strategy:\n\n```python\n# -- configs/addons/linear_warm_cos_sched.py --\nimport torch.optim.lr_scheduler as sched\n\nfrom alchemy_cat.dl_config import Config, DEP\n\ncfg = Config()\n\ncfg.epochs = 30\n\n@cfg.set_DEP(priority=0)  # warm_epochs = 10% of total epochs\ndef warm_epochs(c: Config) -\u003e int:\n    return round(0.1 * c.epochs)\n\ncfg.warm.cls = sched.LinearLR\ncfg.warm.ini.total_iters = DEP(lambda c: c.warm_epochs, priority=1)\ncfg.warm.ini.start_factor = 1e-5\ncfg.warm.ini.end_factor = 1.\n\ncfg.main.cls = sched.CosineAnnealingLR\ncfg.main.ini.T_max = DEP(lambda c: c.epochs - c.warm.ini.total_iters,\n                         priority=2)  # main_epochs = total_epochs - warm_epochs\n\n```\nIn the [final config](alchemy_cat/dl_config/examples/configs/mnist/base,sched_from_addon/cfg.py), we compose this set of learning rate strategy:\n```python\n# -- configs/mnist/base,sched_from_addon/cfg.py --\n# ... Code Omitted.\n\ncfg.sched = Config('configs/addons/linear_warm_cos_sched.py')\n\n# ... Code Omitted.\n```\n```text\n\u003e\u003e\u003e print(cfg.sched.to_txt(prefix='cfg.sched.'))  # A pretty print of the config tree.\ncfg.sched = Config()\n# ------- ↓ LEAVES ↓ ------- #\ncfg.sched.epochs = 30\ncfg.sched.warm_epochs = 3\ncfg.sched.warm.cls = \u003cclass 'torch.optim.lr_scheduler.LinearLR'\u003e\ncfg.sched.warm.ini.total_iters = 3\ncfg.sched.warm.ini.start_factor = 1e-05\ncfg.sched.warm.ini.end_factor = 1.0\ncfg.sched.main.cls = \u003cclass 'torch.optim.lr_scheduler.CosineAnnealingLR'\u003e\ncfg.sched.main.ini.T_max = 27\n```\n\nIt looks very simple! Just assign/mount the predefined config sub-subtree to the final config. `Config('path/to/cfg.py')` returns a copy of the `cfg` object in the config file, ensuring modifications before and after copying are isolated.\n\n\u003e _Implementation Details of Composition and Dependency_\n\u003e\n\u003e Attentive readers might wonder how `DEP` determines the parameter `c` for the dependency computation function, specifically which Config object is passed. In this chapter's example, `c` is the config subtree of learning rate; thus, the calculation function for `cfg.warm.ini.total_iters` is `lambda c: c.warm_epochs`. However, in the [previous chapter's](#dependency) example, `c` is the final config; hence, the calculation function for `cfg.sched.warm.ini.total_iters` is `lambda c: c.sched.warm_epochs`.\n\u003e\n\u003e In fact, `c` is the root node of the configuration tree where `DEP` was first mounted. The `Config` is a bidirectional tree. When `DEP` is first mounted, it records its relative distance to the root. During computation, it traces back this distance to find and pass the corresponding config tree into the computation function.\n\u003e\n\u003e To prevent this default behavior, set `DEP(lambda c: ..., rel=False)`, ensuring `c` is always the complete configuration.\n\n**Best Practice: Both composition and inheritance aim to reuse config. Composition is more flexible and loosely coupled, so it should be prioritized over inheritance.**\n\n### Summary of This Chapter\n* Define config subtree and compose them to create a complete config.\n\n## Full Example\n\n\u003cdetails\u003e\n\u003csummary\u003e Expand full example \u003c/summary\u003e\n\n[Config subtree](alchemy_cat/dl_config/examples/configs/addons/linear_warm_cos_sched.py) related to learning rate:\n```python\n# -- configs/addons/linear_warm_cos_sched.py --\n\nimport torch.optim.lr_scheduler as sched\n\nfrom alchemy_cat.dl_config import Config, DEP\n\ncfg = Config()\n\ncfg.epochs = 30\n\n@cfg.set_DEP(priority=0)  # warm_epochs = 10% of total epochs\ndef warm_epochs(c: Config) -\u003e int:\n    return round(0.1 * c.epochs)\n\ncfg.warm.cls = sched.LinearLR\ncfg.warm.ini.total_iters = DEP(lambda c: c.warm_epochs, priority=1)\ncfg.warm.ini.start_factor = 1e-5\ncfg.warm.ini.end_factor = 1.\n\ncfg.main.cls = sched.CosineAnnealingLR\ncfg.main.ini.T_max = DEP(lambda c: c.epochs - c.warm.ini.total_iters,\n                         priority=2)  # main_epochs = total_epochs - warm_epochs\n```\nThe composed [base config](alchemy_cat/dl_config/examples/configs/mnist/base,sched_from_addon/cfg.py):\n```python\n# -- configs/mnist/base/cfg.py --\n\nimport torchvision.models as model\nimport torchvision.transforms as T\nfrom torch import optim\nfrom torchvision.datasets import MNIST\n\nfrom alchemy_cat.dl_config import Config, DEP\n\ncfg = Config()\n\ncfg.rand_seed = 0\n\n# -* Set datasets.\ncfg.dt.cls = MNIST\ncfg.dt.ini.root = '/tmp/data'\ncfg.dt.ini.transform = T.Compose([T.Grayscale(3), T.ToTensor(), T.Normalize((0.1307,), (0.3081,)),])\n\n# -* Set data loader.\ncfg.loader.ini.batch_size = 128\ncfg.loader.ini.num_workers = 2\n\n# -* Set model.\ncfg.model.cls = model.resnet18\ncfg.model.ini.num_classes = DEP(lambda c: len(c.dt.cls.classes))\n\n# -* Set optimizer.\ncfg.opt.cls = optim.AdamW\ncfg.opt.ini.lr = DEP(lambda c: c.loader.ini.batch_size // 128 * 0.01)  # Linear scaling rule.\n\n# -* Set scheduler.\ncfg.sched = Config('configs/addons/linear_warm_cos_sched.py')\n\n# -* Set logger.\ncfg.log.save_interval = DEP(lambda c: c.sched.epochs // 5, priority=1)  # Save model at every 20% of total epochs.\n```\nInherited from the base config, batch size doubled, number of epochs halved [new config](alchemy_cat/dl_config/examples/configs/mnist/base,sched_from_addon,2xbs,2÷epo/cfg.py):\n\n```python\n# -- configs/mnist/base,sched_from_addon,2xbs,2÷epo/cfg.py --\n\nfrom alchemy_cat.dl_config import Config\n\ncfg = Config(caps='configs/mnist/base,sched_from_addon/cfg.py')\n\ncfg.loader.ini.batch_size = 256\n\ncfg.sched.epochs = 15\n```\nNote that dependencies such as learning rate, warm-up epochs, and main epochs will be automatically updated:\n```text\n\u003e\u003e\u003e cfg = load_config('configs/mnist/base,sched_from_addon,2xbs,2÷epo/cfg.py', create_rslt_dir=False)\n\u003e\u003e\u003e print(cfg)\ncfg = Config()\ncfg.override(False).set_attribute('_cfgs_update_at_parser', ('configs/mnist/base,sched_from_addon/cfg.py',))\n# ------- ↓ LEAVES ↓ ------- #\ncfg.rand_seed = 0\ncfg.dt.cls = \u003cclass 'torchvision.datasets.mnist.MNIST'\u003e\ncfg.dt.ini.root = '/tmp/data'\ncfg.dt.ini.transform = Compose(\n    Grayscale(num_output_channels=3)\n    ToTensor()\n    Normalize(mean=(0.1307,), std=(0.3081,))\n)\ncfg.loader.ini.batch_size = 256\ncfg.loader.ini.num_workers = 2\ncfg.model.cls = \u003cfunction resnet18 at 0x7f5bcda68a40\u003e\ncfg.model.ini.num_classes = 10\ncfg.opt.cls = \u003cclass 'torch.optim.adamw.AdamW'\u003e\ncfg.opt.ini.lr = 0.02\ncfg.sched.epochs = 15\ncfg.sched.warm_epochs = 2\ncfg.sched.warm.cls = \u003cclass 'torch.optim.lr_scheduler.LinearLR'\u003e\ncfg.sched.warm.ini.total_iters = 2\ncfg.sched.warm.ini.start_factor = 1e-05\ncfg.sched.warm.ini.end_factor = 1.0\ncfg.sched.main.cls = \u003cclass 'torch.optim.lr_scheduler.CosineAnnealingLR'\u003e\ncfg.sched.main.ini.T_max = 13\ncfg.log.save_interval = 3\ncfg.rslt_dir = 'mnist/base,sched_from_addon,2xbs,2÷epo'\n```\n[Training code](alchemy_cat/dl_config/examples/train.py):\n```python\n# -- train.py --\nimport argparse\nimport json\n\nimport torch\nimport torch.nn.functional as F\nfrom rich.progress import track\nfrom torch.optim.lr_scheduler import SequentialLR\n\nfrom alchemy_cat.dl_config import load_config\nfrom utils import eval_model\n\nparser = argparse.ArgumentParser(description='AlchemyCat MNIST Example')\nparser.add_argument('-c', '--config', type=str, default='configs/mnist/base,sched_from_addon,2xbs,2÷epo/cfg.py')\nargs = parser.parse_args()\n\n# Folder 'experiment/mnist/base' will be auto created by `load` and assigned to `cfg.rslt_dir`\ncfg = load_config(args.config, experiments_root='/tmp/experiment', config_root='configs')\nprint(cfg)\n\ntorch.manual_seed(cfg.rand_seed)  # Use `cfg` to set random seed\n\ndataset = cfg.dt.cls(**cfg.dt.ini)  # Use `cfg` to set dataset type and its initial parameters\n\n# Use `cfg` to set changeable parameters of loader,\n# other fixed parameter like `shuffle` is set in main code\nloader = torch.utils.data.DataLoader(dataset, shuffle=True, **cfg.loader.ini)\n\nmodel = cfg.model.cls(**cfg.model.ini).train().to('cuda')  # Use `cfg` to set model\n\n# Use `cfg` to set optimizer, and get `model.parameters()` in run time\nopt = cfg.opt.cls(model.parameters(), **cfg.opt.ini, weight_decay=0.)\n\n# Use `cfg` to set warm and main scheduler, and `SequentialLR` to combine them\nwarm_sched = cfg.sched.warm.cls(opt, **cfg.sched.warm.ini)\nmain_sched = cfg.sched.main.cls(opt, **cfg.sched.main.ini)\nsched = SequentialLR(opt, [warm_sched, main_sched], [cfg.sched.warm_epochs])\n\nfor epoch in range(1, cfg.sched.epochs + 1):  # train `cfg.sched.epochs` epochs\n    for data, target in track(loader, description=f\"Epoch {epoch}/{cfg.sched.epochs}\"):\n        F.cross_entropy(model(data.to('cuda')), target.to('cuda')).backward()\n        opt.step()\n        opt.zero_grad()\n\n    sched.step()\n\n    # If cfg.log is defined, save model to `cfg.rslt_dir` at every `cfg.log.save_interval`\n    if cfg.log and epoch % cfg.log.save_interval == 0:\n        torch.save(model.state_dict(), f\"{cfg.rslt_dir}/model_{epoch}.pth\")\n\n    eval_model(model)\n\nif cfg.log:\n    eval_ret = eval_model(model)\n    with open(f\"{cfg.rslt_dir}/eval.json\", 'w') as json_f:\n        json.dump(eval_ret, json_f)\n```\nRun `python train.py --config 'configs/mnist/base,sched_from_addon,2xbs,2÷epo/cfg.py'`, and it will use the settings in the config file to train with `train.py` and save the results to the `/tmp/experiment/mnist/base,sched_from_addon,2xbs,2÷epo` directory.\n\u003c/details\u003e\n\n## Auto Parameter Tuning\nIn the [example above](#full-example), running `python train.py --config path/to/cfg.py` each time yields an experimental result for a set of parameters.\n\nHowever, we often need to perform grid search over the parameter space to find the optimal parameter combination. Writing a config for each combination is laborious and error-prone. Can we define the entire parameter space in a \"tunable config\"? Then let the program automatically traverse all combinations, generate configs, run them, and summarize results for comparison.\n\nThe auto-tuner traverses through tunable config's parameter combinations, generates `N` sub-configs, runs them to obtain `N` experimental records, and summarizes all experimental results into an Excel sheet:\n\n```text\nconfig to be tuned T ───\u003e config C1 + algorithm code A ───\u003e reproducible experiment E1(C1, A) ───\u003e summary table S(T,A)\n                     │                                                                          │ \n                     ├──\u003e config C2 + algorithm code A ───\u003e reproducible experiment E1(C2, A) ──│ \n                    ...                                                                         ...\n```\n### Tunable Config\nTo use the auto-tuner, we first need to write a tunable config:\n```python\n# -- configs/tune/tune_bs_epoch/cfg.py --\n\nfrom alchemy_cat.dl_config import Cfg2Tune, Param2Tune\n\ncfg = Cfg2Tune(caps='configs/mnist/base,sched_from_addon/cfg.py')\n\ncfg.loader.ini.batch_size = Param2Tune([128, 256, 512])\n\ncfg.sched.epochs = Param2Tune([5, 15])\n```\nIts writing style is similar to the [normal configuration](alchemy_cat/dl_config/examples/configs/mnist/base,sched_from_addon,2xbs,2÷epo/cfg.py) in the previous chapter. It supports attribute reading and writing, inheritance, dependency, and combination. The difference lies in:\n* The type of config is `Cfg2Tune`, a subclass of `Config`.\n* For grid search parameters, use `Param2Tune([v1, v2, ...])` with optional values `v1, v2, ...`.\n\nThe tunable config above will search a parameter space of size 3×2=6 and generate these 6 sub-configs:\n```text\nbatch_size  epochs  child_configs\n128         5       configs/tune/tune_bs_epoch/batch_size=128,epochs=5/cfg.pkl\n            15      configs/tune/tune_bs_epoch/batch_size=128,epochs=15/cfg.pkl\n256         5       configs/tune/tune_bs_epoch/batch_size=256,epochs=5/cfg.pkl\n            15      configs/tune/tune_bs_epoch/batch_size=256,epochs=15/cfg.pkl\n512         5       configs/tune/tune_bs_epoch/batch_size=512,epochs=5/cfg.pkl\n            15      configs/tune/tune_bs_epoch/batch_size=512,epochs=15/cfg.pkl\n```\nSet the `priority` parameter of `Param2Tune` to specify the search order. The default is the defined order. Use `optional_value_names` to assign readable names to parameter values. [For example](alchemy_cat/dl_config/examples/configs/tune/tune_bs_epoch,pri,name/cfg.py):\n\n```python\n# -- configs/tune/tune_bs_epoch,pri,name/cfg.py --\n\nfrom alchemy_cat.dl_config import Cfg2Tune, Param2Tune\n\ncfg = Cfg2Tune(caps='configs/mnist/base,sched_from_addon/cfg.py')\n\ncfg.loader.ini.batch_size = Param2Tune([128, 256, 512], optional_value_names=['1xbs', '2xbs', '4xbs'], priority=1)\n\ncfg.sched.epochs = Param2Tune([5, 15], priority=0)\n```\nwhose search space is:\n```text\nepochs batch_size  child_configs\n5      1xbs        configs/tune/tune_bs_epoch,pri,name/epochs=5,batch_size=1xbs/cfg.pkl\n       2xbs        configs/tune/tune_bs_epoch,pri,name/epochs=5,batch_size=2xbs/cfg.pkl\n       4xbs        configs/tune/tune_bs_epoch,pri,name/epochs=5,batch_size=4xbs/cfg.pkl\n15     1xbs        configs/tune/tune_bs_epoch,pri,name/epochs=15,batch_size=1xbs/cfg.pkl\n       2xbs        configs/tune/tune_bs_epoch,pri,name/epochs=15,batch_size=2xbs/cfg.pkl\n       4xbs        configs/tune/tune_bs_epoch,pri,name/epochs=15,batch_size=4xbs/cfg.pk\n```\n\nWe can set constraints between parameters to eliminate unnecessary combinations. For example, the following [example](alchemy_cat/dl_config/examples/configs/tune/tune_bs_epoch,subject_to/cfg.py) limits total iterations to a maximum of 15×128:\n```python\n# -- configs/tune/tune_bs_epoch,subject_to/cfg.py --\n\nfrom alchemy_cat.dl_config import Cfg2Tune, Param2Tune\n\ncfg = Cfg2Tune(caps='configs/mnist/base,sched_from_addon/cfg.py')\n\ncfg.loader.ini.batch_size = Param2Tune([128, 256, 512])\n\ncfg.sched.epochs = Param2Tune([5, 15],\n                              subject_to=lambda cur_val: cur_val * cfg.loader.ini.batch_size.cur_val \u003c= 15 * 128)\n```\nwhose search space is:\n```text\nbatch_size epochs  child_configs\n128        5       configs/tune/tune_bs_epoch,subject_to/batch_size=128,epochs=5/cfg.pkl\n           15      configs/tune/tune_bs_epoch,subject_to/batch_size=128,epochs=15/cfg.pkl\n256        5       configs/tune/tune_bs_epoch,subject_to/batch_size=256,epochs=5/cfg.pkl\n```\n\n### Running auto-tuner\nWe also need to write a small script to run the auto-tuner:\n```python\n# -- tune_train.py --\nimport argparse, json, os, subprocess, sys\nfrom alchemy_cat.dl_config import Config, Cfg2TuneRunner\n\nparser = argparse.ArgumentParser(description='Tuning AlchemyCat MNIST Example')\nparser.add_argument('-c', '--cfg2tune', type=str)\nargs = parser.parse_args()\n\n# Will run `torch.cuda.device_count() // work_gpu_num`  of configs in parallel\nrunner = Cfg2TuneRunner(args.cfg2tune, experiment_root='/tmp/experiment', work_gpu_num=1)\n\n@runner.register_work_fn  # How to run config\ndef work(pkl_idx: int, cfg: Config, cfg_pkl: str, cfg_rslt_dir: str, cuda_env: dict[str, str]) -\u003e ...:\n    subprocess.run([sys.executable, 'train.py', '-c', cfg_pkl], env=cuda_env)\n\n@runner.register_gather_metric_fn  # How to gather metric for summary\ndef gather_metric(cfg: Config, cfg_rslt_dir: str, run_rslt: ..., param_comb: dict[str, tuple[..., str]]) -\u003e dict[str, ...]:\n    return json.load(open(os.path.join(cfg_rslt_dir, 'eval.json')))\n\nrunner.tuning()\n```\nThe script performs these operations:\n* Instantiates the auto-tuner with `runner = Cfg2TuneRunner(...)`, passing in the tunable config path. By default, it runs sub-configs sequentially. Set the parameter `work_gpu_num` to run `len(os.environ['CUDA_VISIBLE_DEVICES']) // work_gpu_num` sub-configs in parallel.\n* Registers a worker that executes each sub-config. The function parameters are:\n  - `pkl_idx`: index of the sub-config\n  - `cfg`: the sub-config\n  - `cfg_pkl`: pickle save path for this sub-config\n  - `cfg_rslt_dir`: experiment directory.\n  - `cuda_env`: If `work_gpu_num` is set, then `cuda_env` will allocate non-overlapping `CUDA_VISIBLE_DEVICES` environment variables for parallel sub-configs.\n\n  Commonly, we only need to pass `cfg_pkl` as the config file into the training script, since `load_cfg` supports reading config in pickle format. For deep learning tasks, different `CUDA_VISIBLE_DEVICES` are needed for each sub-config.\n* Registers a summary function that returns an experimental result as a `{metric_name: metric_value}` dictionary. The auto-tunner will traverse all experimental results and summary into a table. The summary function accepts these parameters:\n  - `cfg`: the sub-configuration\n  - `cfg_rslt_dir`: experiment directory\n  - `run_rslt`: returned from working functions\n  - `param_comb`: parameter combinations for that particular sub-configuration.\n\n  Generally, only need to read results from `cfg_rslt_dir` and return them.\n* Calls `runner.tuning()` to start automatic tuning.\n\nAfter tuning, the tuning results will be printed:\n```text\nMetric Frame:\n                  test_loss    acc\nbatch_size epochs\n128        5       1.993285  32.63\n           15      0.016772  99.48\n256        5       1.889874  37.11\n           15      0.020811  99.49\n512        5       1.790593  41.74\n           15      0.024695  99.33\n\nSaving Metric Frame at /tmp/experiment/tune/tune_bs_epoch/metric_frame.xlsx\n```\nAs the prompt says, the tuning results will also be saved to the `/tmp/experiment/tune/tune_bs_epoch/metric_frame.xlsx` table:\n\u003cdiv align = \"center\"\u003e\n\u003cimg  src=\"https://github.com/HAL-42/AlchemyCat/raw/master/docs/figs/readme-cfg2tune-excel.png\" width=\"400\" /\u003e\n\u003c/div\u003e\n\n\u003e [!TIP]\n\u003e **Best Practice: The auto-tuner is separate from the standard workflow. Write configs and code without considering it. When tuning, add extra code to define parameter space, specify invocation and result methods. After tuning, remove the auto-tuner, keeping only the best config and algorithm.**\n\n### Summary of This Chapter\n* Define a tunable config `Cfg2Tune` with `Param2Tune` to specify the parameter space.\n* Use the auto-tuner `Cfg2TuneRunner` to traverse the parameter space, generate sub-configs, run them, and summarize the results.\n\n## Advanced Usage\n\n\u003cdetails\u003e\n\u003csummary\u003e Expand advanced usage \u003c/summary\u003e\n\n### Pretty Print\nThe `__str__` method of `Config` is overloaded to print the tree structure with keys separated by `.`:\n\n```text\n\u003e\u003e\u003e cfg = Config()\n\u003e\u003e\u003e cfg.foo.bar.a = 1\n\u003e\u003e\u003e cfg.bar.foo.b = ['str1', 'str2']\n\u003e\u003e\u003e cfg.whole.override()\n\u003e\u003e\u003e print(cfg)\ncfg = Config()\ncfg.whole.override(True)\n# ------- ↓ LEAVES ↓ ------- #\ncfg.foo.bar.a = 1\ncfg.bar.foo.b = ['str1', 'str2']\n```\n\nWhen all leaf nodes are built-in types, the pretty print output of `Config` can be executed as Python code to get the same configuration:\n```text\n\u003e\u003e\u003e exec(cfg.to_txt(prefix='new_cfg.'), globals(), (l_dict := {}))\n\u003e\u003e\u003e l_dict['new_cfg'] == cfg\nTrue\n```\n\nFor invalid attribute names, `Config` will fall back to the print format of `dict`:\n```text\n\u003e\u003e\u003e cfg = Config()\n\u003e\u003e\u003e cfg['Invalid Attribute Name'].foo = 10\n\u003e\u003e\u003e cfg.bar['def'] = {'a': 1, 'b': 2}\n\u003e\u003e\u003e print(cfg)\ncfg = Config()\n# ------- ↓ LEAVES ↓ ------- #\ncfg['Invalid Attribute Name'].foo = 10\ncfg.bar['def'] = {'a': 1, 'b': 2}\n```\n\n### Auto Capture Experiment Logs\nFor deep learning tasks, we recommend using `init_env` instead of `load_config`. In addition to loading the config, `init_env` can also initialize the deep learning environment, such as setting the torch device, gradient, random seed, and distributed training:\n\n```python\nfrom alchemy_cat.torch_tools import init_env\n\nif __name__ == '__main__':\n    import argparse\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument('-c', '--config', type=str)\n    parser.add_argument('--local_rank', type=int, default=-1)\n    args = parser.parse_args()\n\n    device, cfg = init_env(config_path=args.config,             # config file path，read to `cfg`\n                           is_cuda=True,                        # if True，`device` is cuda，else cpu\n                           is_benchmark=bool(args.benchmark),   # torch.backends.cudnn.benchmark = is_benchmark\n                           is_train=True,                       # torch.set_grad_enabled(is_train)\n                           experiments_root=\"experiment\",       # root of experiment dir\n                           rand_seed=True,                      # set python, numpy, torch rand seed. If True, read cfg.rand_seed as seed, else use actual parameter as rand seed.\n                           cv2_num_threads=0,                   # set cv2 num threads\n                           verbosity=True,                      # print more env init info\n                           log_stdout=True,                     # where fork stdout to log file\n                           loguru_ini=True,                     # config a pretty loguru format\n                           reproducibility=False,               # set pytorch to reproducible mode\n                           local_rank=...,                      # dist.init_process_group(..., local_rank=local_rank)\n                           silence_non_master_rank=True,        # if True, non-master rank will not print to stdout, but only log to file\n                           is_debug=bool(args.is_debug))        # is debug mode\n```\nIf `log_stdout=True`, `init_env` will fork `sys.stdout` and `sys.stderr` to the log file `cfg.rslt_dir/{local-time}.log`. This will not interfere with normal `print`, but all screen output will be recorded in the log. Therefore, there is no need to manually write logs, what you see on the screen is what you get in the log.\n\nDetails can be found in the docstring of `init_env`.\n\n### Attribute Dict\nIf you are a user of [addict](https://github.com/mewwts/addict), our `ADict` can be used as a drop-in replacement for `addict.Dict`: `from alchemy_cat.dl_config import ADict as Dict`.\n\n`ADict` has all the interfaces of `addict.Dict`. However, all methods are re-implemented to optimize execution efficiency and cover more corner cases (such as circular references). `Config` is actually a subclass of `ADict`.\n\nIf you haven't used `addict` before, read this [documentation](https://github.com/mewwts/addict). Research code often involves complex dictionaries. `addict.Dict` or `ADict` supports attribute-style access for nested dictionaries.\n\n### Circular References\nThe initialization, inheritance, and composition of `ADict` and `Config` require a `branch_copy` operation, which is between shallow and deep copy, that is, copying the tree structure but not the leaf nodes. `ADict.copy`, `Config.copy`, and `copy.copy(cfg)` all call `branch_copy`, not the `copy` method of `dict`.\n\nIn theory, `ADict.branch_copy` can handle circular references, such as:\n```text\n\u003e\u003e\u003e dic = {'num': 0,\n           'lst': [1, 'str'],\n           'sub_dic': {'sub_num': 3}}\n\u003e\u003e\u003e dic['lst'].append(dic['sub_dic'])\n\u003e\u003e\u003e dic['sub_dic']['parent'] = dic\n\u003e\u003e\u003e dic\n{'num': 0,\n 'lst': [1, 'str', {'sub_num': 3, 'parent': {...}}],\n 'sub_dic': {'sub_num': 3, 'parent': {...}}}\n\n\u003e\u003e\u003e adic = ADict(dic)\n\u003e\u003e\u003e adic.sub_dic.parent is adic is not dic\nTrue\n\u003e\u003e\u003e adic.lst[-1] is adic.sub_dic is not dic['sub_dic']\nTrue\n```\nDifferent from `ADict`, the data model of `Config` is a bidirectional tree, and circular references will form a cycle. To avoid cycles, if a subtree is mounted to different parent configs multiple times, the subtree will be copied to an independent config tree before mounting. In normal use, circular references should not appear in the config tree.\n\nIn summary, although circular references are supported, they are neither necessary nor recommended.\n\n### Traverse the Config Tree\n`Config.named_branchs` and `Config.named_ckl` respectively traverse all branches and leaves of the config tree (the branch, key name, and value they are in):\n```text\n\u003e\u003e\u003e list(cfg.named_branches)\n[('', {'foo': {'bar': {'a': 1}},\n       'bar': {'foo': {'b': ['str1', 'str2']}},\n       'whole': {}}),\n ('foo', {'bar': {'a': 1}}),\n ('foo.bar', {'a': 1}),\n ('bar', {'foo': {'b': ['str1', 'str2']}}),\n ('bar.foo', {'b': ['str1', 'str2']}),\n ('whole', {})]\n\n\u003e\u003e\u003e list(cfg.ckl)\n[({'a': 1}, 'a', 1), ({'b': ['str1', 'str2']}, 'b', ['str1', 'str2'])]\n```\n\n### Lazy Inheritance\n```text\n\u003e\u003e\u003e from alchemy_cat.dl_config import Config\n\u003e\u003e\u003e cfg = Config(caps='configs/mnist/base,sched_from_addon/cfg.py')\n\u003e\u003e\u003e cfg.loader.ini.batch_size = 256\n\u003e\u003e\u003e cfg.sched.epochs = 15\n\u003e\u003e\u003e print(cfg)\n\ncfg = Config()\ncfg.override(False).set_attribute('_cfgs_update_at_parser', ('configs/mnist/base,sched_from_addon/cfg.py',))\n# ------- ↓ LEAVES ↓ ------- #\ncfg.loader.ini.batch_size = 256\ncfg.sched.epochs = 15\n```\nWhen inheriting, the parent configs `caps` is not immediately updated, but is loaded when `load_config` is called. Lazy inheritance allows the config system to have an eager-view of the entire inheritance chain, and a few features rely on this.\n\n### Work with Git\n\nFor `config C + algorithm code A ——\u003e reproducible experiment E(C, A)`, meaning that when the config `C` and the algorithm code `A` are determined, the experiment `E` can always be reproduced. Therefore, it is recommended to submit the configuration file and algorithm code to the Git repository together for reproducibility.\n\nWe also provide a [script](alchemy_cat/torch_tools/scripts/tag_exps.py) that runs `pyhon -m alchemy_cat.torch_tools.scripts.tag_exps -s commit_ID -a commit_ID`, interactively lists the new configs added by the commit, and tags the commit according to the config path. This helps quickly trace back the config and algorithm of a historical experiment.\n\n### Automatically Allocate idle GPUs\nThe `work` function receives the idle GPU automatically allocated by `Cfg2TuneRunner` through the `cuda_env` parameter. We can further control the definition of 'idle GPU':\n```python\nrunner = Cfg2TuneRunner(args.cfg2tune, experiment_root='/tmp/experiment', work_gpu_num=1,\n                        block=True,             # Try to allocate idle GPU\n                        memory_need=10 * 1024,  # Need 10 GB memory\n                        max_process=2)          # Max 2 process already ran on each GPU\n```\nwhere:\n- `block`: Defaults is `True`. If set to `False`, GPUs are allocated sequentially, regardless of whether they are idle.\n- `memory_need`: The amount of GPU memory required for each sub-config, in MB. The free memory on an idle GPU must be ≥ `memory_need`. Default is `-1.`, indicating need all memory.\n- `max_process`: Maximum number of existing processes. The number of existing processes on an idle GPU must be ≤ `max_process`. Default value is `-1`, indicating no limit.\n\n### Pickling Lambda Functions\nSub-configs generated by `Cfg2Tune` will be saved using pickle. However, if `Cfg2Tune` defines dependencies as `DEP(lambda c: ...)`, these lambda functions cannot be pickled. Workarounds include:\n* Using the decorator `@Config.set_DEP` to define the dependency's computation function.\n* Defining the dependency's calculation function in a separate module and passing it to `DEP`.\n* Defining dependencies in the parent configs since inheritance is handled lazily, so sub-configs temporarily exclude dependencies.\n* If the dependency source is a tunable parameter, use `P_DEP`, which resolves after generating sub-configs of `Cfg2Tune` but before saving them as pickle.\n\n### More Inheritance Tricks\n\n#### Deleting During Inheritance\nThe `Config.empty_leaf()` combines `Config.clear()` and `Config.override()` to get an empty and \"override\" subtree. This is commonly used to represent the \"delete\" semantics during inheritance, that is, using an empty config to override a subtree of the base config.\n\n#### `update` Method\nLet `cfg` be a `Config` instance and `base_cfg` be a `dict` instance. The effects of `cfg.dict_update(base_cfg)`, `cfg.update(base_cfg)`, and `cfg |= base_cfg` are similar to inheriting `Config(base_cfg)` from `cfg`.\n\nRun `cfg.dict_update(base_cfg, incremental=True)` to ensure only incremental updates, that is, only add keys that do not exist in `cfg` without overwriting existing keys.\n\n### Best Practice: Dependency Injection Configuration\nWhen configuring runtime data structures (such as functions, classes), there are two different writing styles.\n\nStyle A:\n```python\n# Config code snippet\ncfg = Config()\n\ncfg.dt.cls = 'MNIST'\ncfg.dt.root = '/tmp/data'\ncfg.dt.train = True\n\n# Runtime code snippet\nimport torchvision.datasets as tv_datasets\n\ndataset_cls = getattr(tv_datasets, cfg.dt.cls)\ndataset = dataset_cls(root=cfg.dt.root, train=cfg.dt.train)\n```\n\nStyle B:\n```python\n# Config code snippet\nfrom torchvision.datasets import MNIST\n\ncfg = Config()\n\ncfg.dt.cls = MNIST  # 免反射\ncfg.dt.ini.root = '/tmp/data'\ncfg.dt.ini.train = True\n\n# Runtime code snippet\ndataset = cfg.dt.cls(**cfg.dt.ini)  # 直通传参\n```\n\nCompared to style A, style B is more robust, flexible, and maintainable due to these two improvements:\n- *Reflection-free*: In style B, `cfg.dt.cls` directly references the class object, avoiding runtime reflection lookups. This approach is more IDE-friendly, allowing for error detection during code writing, facilitating auto-completion, definition navigation, and synchronized updates during refactoring.\n- *Direct parameter passing*: In style B, `cfg.dt.ini` directly stores initialization key-value pairs, which are then passed to the constructor using `**` expansion, eliminating the need for manual parameter mapping in runtime code. This approach adheres to the \"Open/Closed Principle,\" decoupling runtime code from parameters: changes to the class or parameter modifications only require updates to the configuration, without altering the runtime code. Additionally, direct parameter passing will immediately raise errors when setting redundant or incorrect parameters, whereas style A may lead to hidden bugs if the runtime code is not updated accordingly.\n\nWe collectively refer to the two changes in style B, *reflection-free* and *direct parameter passing*, as **Dependency Injection Configuration**. When using `alchemy_cat.dl_config`, it is strongly recommended to adopt Dependency Injection Configuration, as this approach is more robust, convenient, flexible, and safe.\n\n\u003c/details\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhal-42%2Falchemycat","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhal-42%2Falchemycat","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhal-42%2Falchemycat/lists"}