YACS 介绍与使用说明

github 地址:YACS
(本博客是我阅读 yacs github 介绍后,个人理解的翻译版,如果有疑问,欢迎留言。)

一个定义和管理深度学习算法 python 代码配置的工具。官方的定位是 your code + a YACS config for experiment E (+ external dependencies + hardware + other nuisance terms ...) = reproducible experiment E

使用方法

有两种方法:Configuration as local variable(官方推荐)、Configuration as a global singleton。

要在项目中使用YACS,首先要创建一个项目配置文件,通常称为config.py或defaults.py。该文件是所有可配置选项的一站式参考点。它应该有很好的代码注释(说明参数的作用),并为所有选项提供合理的默认值。

# my_project/config.py
from yacs.config import CfgNode as CN


_C = CN()

_C.SYSTEM = CN()
# Number of GPUS to use in the experiment
_C.SYSTEM.NUM_GPUS = 8
# Number of workers for doing things
_C.SYSTEM.NUM_WORKERS = 4

_C.TRAIN = CN()
# A very important hyperparameter
_C.TRAIN.HYPERPARAMETER_1 = 0.1
# The all important scales for the stuff
_C.TRAIN.SCALES = (2, 4, 8, 16)


def get_cfg_defaults():
  """Get a yacs CfgNode object with default values for my_project."""
  # Return a clone so that the defaults will not be altered
  # This is for the "local variable" use pattern
  return _C.clone()

# Alternatively, provide a way to import the defaults as
# a global singleton:
# cfg = _C  # users can `from config import cfg`

接着,创建 yaml 配置文件。推荐的做法是每个实验写一个 yaml 文件。每个 yaml 配置文件覆写对应实验要改变的选项值。

# my_project/experiment1.yaml
SYSTEM:
  NUM_GPUS: 2
TRAIN:
  SCALES: (1, 2)

最后,在项目代码里使用 yacs 。在初始化后,推荐调用 freeze() 方法以阻止在代码运行过程中对选项的修改。如下例所示,配置选项既可以通过导入 cfg 并直接访问它来使用全局选项集,也可以复制 cfg 并作为参数传递。

# my_project/main.py

import my_project
from config import get_cfg_defaults  # local variable usage pattern, or:
# from config import cfg  # global singleton usage pattern


if __name__ == "__main__":
  cfg = get_cfg_defaults()
  cfg.merge_from_file("experiment.yaml")
  cfg.freeze()
  print(cfg)

  # Example of using the cfg as global access to options
  if cfg.SYSTEM.NUM_GPUS > 0:
    my_project.setup_multi_gpu_support()

  model = my_project.create_model(cfg)

猜你喜欢

转载自blog.csdn.net/Snakehj/article/details/129249569