diff --git a/testbed/facebookresearch__hydra/.circleci/config.yml b/testbed/facebookresearch__hydra/.circleci/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..77cb727e8c56fa66c534cc39ef286e6aef583652 --- /dev/null +++ b/testbed/facebookresearch__hydra/.circleci/config.yml @@ -0,0 +1,277 @@ +version: 2.1 + +jobs: + # Mac + py36_mac: + macos: + xcode: "10.0.0" + steps: + - checkout + - run: + name: "Installing Conda" + command: | + curl -o Miniconda3-latest-MacOSX-x86_64.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh + bash ./Miniconda3-latest-MacOSX-x86_64.sh -b + ~/miniconda3/bin/conda init bash + - run: + name: "Preparing environment" + command: | + brew update + brew install fish + conda create -n hydra python=3.6 -yq + conda run -n hydra pip install nox + - run: + name: "Testing Hydra" + no_output_timeout: 10m + command: | + export NOX_PYTHON_VERSIONS=3.6 + conda activate hydra + pip install nox dataclasses + nox + + py37_mac: + macos: + xcode: "10.0.0" + steps: + - checkout + - run: + name: "Installing Conda" + command: | + curl -o Miniconda3-latest-MacOSX-x86_64.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh + bash ./Miniconda3-latest-MacOSX-x86_64.sh -b + ~/miniconda3/bin/conda init bash + - run: + name: "Preparing environment" + command: | + brew update + brew install fish + conda create -n hydra python=3.7 -yq + conda run -n hydra pip install nox + - run: + name: "Testing Hydra" + no_output_timeout: 10m + command: | + export NOX_PYTHON_VERSIONS=3.7 + conda activate hydra + pip install nox + nox + + py38_mac: + macos: + xcode: "10.0.0" + steps: + - checkout + - run: + name: "Installing Conda" + command: | + curl -o Miniconda3-latest-MacOSX-x86_64.sh https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh + bash ./Miniconda3-latest-MacOSX-x86_64.sh -b + ~/miniconda3/bin/conda init bash + - run: + name: "Preparing environment" + command: | + brew update + brew install fish + conda create -n hydra python=3.8 -yq + conda run -n hydra pip install nox + - run: + name: "Testing Hydra" + no_output_timeout: 10m + command: | + export NOX_PYTHON_VERSIONS=3.8 + conda activate hydra + pip install nox + nox + + # Linux + py36_linux: + docker: + - image: circleci/python:3.6 + steps: + - checkout + - run: + name: "Preparing environment" + command: | + sudo apt-get update + sudo apt-get install -y expect fish + sudo pip install nox + - run: + name: "Testing Hydra" + command: | + export NOX_PYTHON_VERSIONS=3.6 + pip install nox dataclasses + nox + + py37_linux: + docker: + - image: circleci/python:3.7 + steps: + - checkout + - run: + name: "Preparing environment" + command: | + sudo apt-get update + sudo apt-get install -y expect fish + sudo pip install nox + - run: + name: "Testing Hydra" + command: | + export NOX_PYTHON_VERSIONS=3.7 + pip install nox + nox + + py38_linux: + docker: + - image: circleci/python:3.8 + steps: + - checkout + - run: + name: "Preparing environment" + command: | + sudo apt-get update + sudo apt-get install -y expect fish + sudo pip install nox + - run: + name: "Testing Hydra" + command: | + export NOX_PYTHON_VERSIONS=3.8 + pip install nox + nox + + # windows + py36_win: + executor: win/default + steps: + - checkout + - run: + name: Installing Conda + command: | + choco install miniconda3 -y + C:\tools\miniconda3\Scripts\conda.exe init powershell + choco install openssl -y + - run: + name: Preparing conda environment + command: | + conda create -n hydra python=3.6 pywin32 -qy + conda activate hydra + pip install nox dataclasses + - run: + name: Testing Hydra + no_output_timeout: 20m + command: | + $env:NOX_PYTHON_VERSIONS=3.6 + $env:PYTHONIOENCODING="utf_8" + conda activate hydra + nox + exit $LASTEXITCODE + + py37_win: + executor: win/default + steps: + - checkout + - run: + name: Installing Conda + command: | + choco install miniconda3 -y + C:\tools\miniconda3\Scripts\conda.exe init powershell + choco install openssl -y + - run: + name: Preparing conda environment + command: | + conda create -n hydra python=3.7 pywin32 -qy + conda activate hydra + pip install nox + - run: + name: Testing Hydra + no_output_timeout: 20m + command: | + $env:NOX_PYTHON_VERSIONS=3.7 + $env:PYTHONIOENCODING="utf_8" + conda activate hydra + nox + exit $LASTEXITCODE + + py38_win: + executor: win/default + steps: + - checkout + - run: + name: Installing Conda + command: | + choco install miniconda3 -y + C:\tools\miniconda3\Scripts\conda.exe init powershell + choco install openssl -y + - run: + name: Preparing conda environment + command: | + conda create -n hydra python=3.8 pywin32 -qy + conda activate hydra + pip install nox + - run: + name: Testing Hydra + no_output_timeout: 20m + command: | + $env:NOX_PYTHON_VERSIONS=3.8 + $env:PYTHONIOENCODING="utf_8" + conda activate hydra + nox + exit $LASTEXITCODE + # Misc + coverage: + docker: + - image: circleci/python:3.6 + steps: + - checkout + - run: sudo pip install nox + - run: nox -s coverage + + deploy-website: + docker: + - image: circleci/node:12 + steps: + - checkout + - deploy: + name: Deploying to GitHub Pages + command: | + SUBDIR=website + REV=$(git log -5 --pretty=oneline origin/gh-pages | grep "Deploy website" | awk 'NF>1{print $NF}' | head -1) + # This condition passes in 2 conditions: + # 1. The revision does not exist (squash/force push happened) + # 2. There are changes between last deployed revision and HEAD + if [[ ! $(git rev-parse --verify -q "$REV^{commit}") || $(git diff-index $REV -- $SUBDIR) ]]; then + echo "Changes detected in directory $SUBDIR between origin/master and this diff" + + cd $SUBDIR + yarn --no-progress + + git config --global user.email omry@users.noreply.github.com + git config --global user.name omry + echo "machine github.com login docusaurus-bot password $GITHUB_TOKEN" > ~/.netrc + yarn install && GIT_USER=docusaurus-bot yarn deploy + else + echo "No changes detected in directory $SUBDIR between origin/master and this diff" + fi + +workflows: + version: 2 + build: + jobs: + # linux + - py36_linux + - py37_linux + - py38_linux + # mac + - py36_mac + - py37_mac + - py38_mac + # windows + - py36_win + - py37_win + - py38_win + - deploy-website: + filters: + branches: + only: master + +orbs: + win: circleci/windows@1.0.0 diff --git a/testbed/facebookresearch__hydra/.coveragerc b/testbed/facebookresearch__hydra/.coveragerc new file mode 100644 index 0000000000000000000000000000000000000000..5e464687ca26c3e5aeaffff54918c208b60628af --- /dev/null +++ b/testbed/facebookresearch__hydra/.coveragerc @@ -0,0 +1,16 @@ +[run] +omit = + ${COVERAGE_HOME}/.nox/* + ${COVERAGE_HOME}/*tests* + ${COVERAGE_HOME}/plugins/* + +[report] +exclude_lines = + pragma: no cover + # Don't complain if tests don't hit defensive assertion code: + raise AssertionError + raise NotImplementedError + raise TypeError + @deprecated + assert False + diff --git a/testbed/facebookresearch__hydra/.flake8 b/testbed/facebookresearch__hydra/.flake8 new file mode 100644 index 0000000000000000000000000000000000000000..e8ee6a43ad3fb8ce9ff597b4578ddc9a096b0b45 --- /dev/null +++ b/testbed/facebookresearch__hydra/.flake8 @@ -0,0 +1,7 @@ +[flake8] +exclude = .git,.nox,build +max-line-length = 119 +copyright-check = True +select = E,F,W,C +copyright-regexp=Copyright \(c\) Facebook, Inc. and its affiliates. All Rights Reserved +ignore=W503,E203 diff --git a/testbed/facebookresearch__hydra/.gitattributes b/testbed/facebookresearch__hydra/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..588d8d6e874aec4e399d08c0ae22a7e4f2b7911b --- /dev/null +++ b/testbed/facebookresearch__hydra/.gitattributes @@ -0,0 +1,29 @@ +# Auto detect text files and perform LF normalization +* text=auto +* text eol=lf + +# Don't do anything with binaries +*.png binary +*.jpg binary +*.svg binary +*.jpeg binary +*.gif binary +*.ico binary +*.mov binary +*.mp4 binary +*.mp3 binary +*.flv binary +*.fla binary +*.swf binary +*.gz binary +*.zip binary +*.7z binary +*.ttf binary +*.eot binary +*.woff binary +*.pyc binary +*.pdf binary +*.ez binary +*.bz2 binary +*.swp binary +*.webp binary diff --git a/testbed/facebookresearch__hydra/.gitignore b/testbed/facebookresearch__hydra/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a14664d3affdb4a0fc5e60b1db94dad59c404048 --- /dev/null +++ b/testbed/facebookresearch__hydra/.gitignore @@ -0,0 +1,16 @@ +/.idea +outputs +multirun +dist +build +__pycache__ +*.pyc +*.egg-info +/.nox +/report.json +/.coverage +.mypy_cache +pip-wheel-metadata +.ipynb_checkpoints +/.dmypy.json +TODO.txt diff --git a/testbed/facebookresearch__hydra/.isort.cfg b/testbed/facebookresearch__hydra/.isort.cfg new file mode 100644 index 0000000000000000000000000000000000000000..4e4baef8c88fa37bb5d0bfe2536b4bf23d7f94bd --- /dev/null +++ b/testbed/facebookresearch__hydra/.isort.cfg @@ -0,0 +1,10 @@ +[settings] +multi_line_output=3 +include_trailing_comma=True +force_grid_wrap=0 +use_parentheses=True +line_length=88 +ensure_newline_before_comments=True +known_third_party=omegaconf,ray,pytest,typing_extensions +known_first_party=hydra +skip=plugins,.nox diff --git a/testbed/facebookresearch__hydra/.pre-commit-config.yaml b/testbed/facebookresearch__hydra/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..930284cc3c1e0d3e29e265eedd04b51feff3614b --- /dev/null +++ b/testbed/facebookresearch__hydra/.pre-commit-config.yaml @@ -0,0 +1,17 @@ +repos: + - repo: https://github.com/timothycrosley/isort + rev: 'c54b3dd' + hooks: + - id: isort + + - repo: https://github.com/psf/black + rev: stable + hooks: + - id: black + language_version: python3.6 + + - repo: https://gitlab.com/pycqa/flake8 + rev: 3.7.9 + hooks: + - id: flake8 + additional_dependencies: [-e, "git+git://github.com/pycqa/pyflakes.git@1911c20#egg=pyflakes"] diff --git a/testbed/facebookresearch__hydra/.yamllint b/testbed/facebookresearch__hydra/.yamllint new file mode 100644 index 0000000000000000000000000000000000000000..6bd8359908bf390cdf3ebdc908bea927894950de --- /dev/null +++ b/testbed/facebookresearch__hydra/.yamllint @@ -0,0 +1,34 @@ +yaml-files: + - '*.yaml' + - '*.yml' + - '.yamllint' + +rules: + braces: enable + brackets: enable + colons: enable + commas: enable + comments: + level: warning + comments-indentation: + level: warning + document-end: disable + document-start: disable + empty-lines: enable + empty-values: disable + hyphens: enable + indentation: enable + key-duplicates: enable + key-ordering: disable + line-length: disable + new-line-at-end-of-file: enable + new-lines: enable + octal-values: disable + quoted-strings: disable + trailing-spaces: enable + truthy: + level: warning + +ignore: | + **/.hydra/*.yaml + .* diff --git a/testbed/facebookresearch__hydra/CHANGELOG.md b/testbed/facebookresearch__hydra/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..6be16a4a43344ab9fcb83070b0dd3cf1e3697c37 --- /dev/null +++ b/testbed/facebookresearch__hydra/CHANGELOG.md @@ -0,0 +1 @@ +Please see NEWS.rst for an updated change log \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/CODE_OF_CONDUCT.md b/testbed/facebookresearch__hydra/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..ac27d8a51bcddc928a57cae0ee5c585d5c9dc149 --- /dev/null +++ b/testbed/facebookresearch__hydra/CODE_OF_CONDUCT.md @@ -0,0 +1,2 @@ +# Code of Conduct +Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](https://code.fb.com/codeofconduct) so that you can understand what actions will and will not be tolerated. \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/CONTRIBUTING.md b/testbed/facebookresearch__hydra/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..f9bf883509e54a093d2bddd58281d6d596fc355c --- /dev/null +++ b/testbed/facebookresearch__hydra/CONTRIBUTING.md @@ -0,0 +1,32 @@ +# Contributing to hydra +We want to make contributing to this project as easy and transparent as +possible. + +Please see the [developer guide](https://hydra.cc/docs/development/contributing/) on the website. + +## Pull Requests +We welcome your pull requests. + +1. Fork the repo and create your feature branch from `master`. +2. If you've added code add suitable tests. +3. If you've changed APIs, update the documentation. +4. Ensure the test suite and lint pass. +5. If you haven't already, complete the Contributor License Agreement ("CLA"). + +## Contributor License Agreement ("CLA") +In order to accept your pull request, we need you to submit a CLA. You only need +to do this once to work on any of Facebook's open source projects. + +Complete your CLA here: + +## Issues +We use GitHub issues to track public bugs. Please ensure your description is +clear and has sufficient instructions to be able to reproduce the issue. + +Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe +disclosure of security bugs. In those cases, please go through the process +outlined on that page and do not file a public issue. + +## License +By contributing to hydra, you agree that your contributions will be licensed +under the LICENSE file in the root directory of this source tree. diff --git a/testbed/facebookresearch__hydra/LICENSE b/testbed/facebookresearch__hydra/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b96dcb0480a0b0be0727976e5202a1e7b23edc3f --- /dev/null +++ b/testbed/facebookresearch__hydra/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Facebook, Inc. and its affiliates. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/testbed/facebookresearch__hydra/MANIFEST.in b/testbed/facebookresearch__hydra/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..2550fd35b4043e2a52493ac9868e7a30951bc2fa --- /dev/null +++ b/testbed/facebookresearch__hydra/MANIFEST.in @@ -0,0 +1,5 @@ +include hydra/py.typed +global-exclude *.pyc +global-exclude __pycache__ +recursive-include hydra/* * + diff --git a/testbed/facebookresearch__hydra/NEWS.md b/testbed/facebookresearch__hydra/NEWS.md new file mode 100644 index 0000000000000000000000000000000000000000..2023e1597698f7a869417f9cf91dfac2fe44a4a7 --- /dev/null +++ b/testbed/facebookresearch__hydra/NEWS.md @@ -0,0 +1,323 @@ +1.0.0-rc1 (2020-05-31) +====================== +Hydra 1.0 is a major release introducing many new features and breaking some compatibility. + +Features +-------- +- Upgrade to OmegaConf 2.0 ([Release notes](https://github.com/omry/omegaconf/releases/tag/2.0.0)) (#630) +- Optional config type safety via Structured Configs (#629) +- Improve command line and config composition error reporting (#349) +- Hydra config can now be accessed through interpolation using ${hydra:key}, for example ${hydra:job.name} ([#325](https://github.com/facebookresearch/hydra/issues/325)) +- Support for setting environment variable of running job ([#7](https://github.com/facebookresearch/hydra/issues/7)) +- Changes command line processing (requiring + and ~ prefixes for appending and removing items) ([#598](https://github.com/facebookresearch/hydra/issues/598)) +- Introducing `@package` header for config files ([#586](https://github.com/facebookresearch/hydra/issues/586)) +- Add command line override flags for `config_path` and `config_name` ([#386](https://github.com/facebookresearch/hydra/issues/386)) +- hydra.main() now take an optional cfg object to passthrough to the function ([#575](https://github.com/facebookresearch/hydra/issues/575)) +- Add hydra.experimental.{initialize_with_file, initialize_with_module} ([#574](https://github.com/facebookresearch/hydra/issues/574)) +- Support for disabling the creation of the `.hydra` subdirectory by overriding "hydra.output_subdir" to "null" ([#324](https://github.com/facebookresearch/hydra/issues/324)) +- Add `hydra.utils.call()` to call methods and functions as well as instantiate objects. Search module paths more generically. ([#498](https://github.com/facebookresearch/hydra/issues/498)) +- Add support for overriding package from command line and defaults list ([#235](https://github.com/facebookresearch/hydra/issues/235)) +- Config source is now abstracted, allowing additional config sources to be used ([#257](https://github.com/facebookresearch/hydra/issues/257)) +- New ConfigSource plugin API allowing configs to be provided by external plugins ([#367](https://github.com/facebookresearch/hydra/issues/367)) +- Add isort to ensure imports are always sorted ([#340](https://github.com/facebookresearch/hydra/issues/340)) +- Codebase is now passing mypy --strict type checking ([#342](https://github.com/facebookresearch/hydra/issues/342)) +- Improve performance of plugin discovery and instantiation ([#489](https://github.com/facebookresearch/hydra/issues/489)) +- Modules whose name starts with "_" are skipped during plugin discovery ([#494](https://github.com/facebookresearch/hydra/issues/494)) + +Plugins +------- +- Add [Ax](https://ax.dev) Sweeper plugin ([Shagun Sodhani](https://shagunsodhani.com/)) +- Add [Nevergrad](https://github.com/facebookresearch/nevergrad) Sweeper plugin ([Jérémy Rapin](https://github.com/jrapin)) +- Add [Joblib](https://joblib.readthedocs.io/en/latest/) Launcher plugin ([Jan-Matthis](https://github.com/jan-matthis)) +- Add [Submitit](https://github.com/facebookincubator/submitit) Launcher plugin to launch jobs to SLURM clusters +- Add [Fish](https://fishshell.com/) shell Tab Completion plugin ([Binsheng Liu](https://binshengliu.github.io/)) ([#549](https://github.com/facebookresearch/hydra/issues/549)) + +API Change (Renames, deprecations and removals) +----------------------------------------------- +- Drop support Python 2.7 and 3.5 ([#313](https://github.com/facebookresearch/hydra/issues/313)) +- hydra.main() now takes an additional optional config_name and composite-style config_path is deprecated ([#395](https://github.com/facebookresearch/hydra/issues/395)) +- Launcher API launch method now takes an additional initial_job_idx indicating the id of the first job in the batch ([#284](https://github.com/facebookresearch/hydra/issues/284)) +- Singleton metaclass is now exposed at hydra.core.Singleton ([#371](https://github.com/facebookresearch/hydra/issues/371)) +- Moved HydraConfig from hydra.plugins.common.utils to hydra.core ([#371](https://github.com/facebookresearch/hydra/issues/371)) +- Move several formerly internal APIs to hydra/core to ensure plugins does not need to use internal APIs ([#371](https://github.com/facebookresearch/hydra/issues/371)) +- Plugin import now requires explicit name (from hydra.plugins.launcher import Launcher) ([#371](https://github.com/facebookresearch/hydra/issues/371)) +- Object Config "class" field is deprecated in favor of "cls" and will be removed in a future version. ([#389](https://github.com/facebookresearch/hydra/issues/389)) +- Experimental compose API config_file changed to config_name ([#395](https://github.com/facebookresearch/hydra/issues/395)) +- User plugins should be modified to not import twice during plugin discovery. see issue for details. ([#482](https://github.com/facebookresearch/hydra/issues/482)) +- Change hydra.core.plugins.Plugins class to a Singleton. access should be changed to the pattern Plugins.instance().foo() ([#489](https://github.com/facebookresearch/hydra/issues/489)) +- Plugins should now include test fixtures (sweep_runner, task_runner) via a standardized conftest.py ([#521](https://github.com/facebookresearch/hydra/issues/521)) +- Switch Python 3 native namespace packages for plugins (See task for details) ([#534](https://github.com/facebookresearch/hydra/issues/534)) +- Packaged configuration directories now requires an `__init__.py` at their top level ([#536](https://github.com/facebookresearch/hydra/issues/536)) +- Appending config groups to the defaults list via the command line now requires a + prefix ([#598](https://github.com/facebookresearch/hydra/issues/598)) +- Removing an item from the defaults list by assigning null (db=null) is deprecated, use ~db instead ([#598](https://github.com/facebookresearch/hydra/issues/598)) +- Installed Hydra applications no longer need have an additional `entry()` function on the stack ([#92](https://github.com/facebookresearch/hydra/issues/92)) + +Bug Fixes +--------- + +- Fix a bug causing sys.exit() error code to not be propagated ([#351](https://github.com/facebookresearch/hydra/issues/351)) +- Shutdown logging subsystem aftter job finishes to ensure log files are flushed and closed ([#378](https://github.com/facebookresearch/hydra/issues/378)) +- Fix a bug with utils.instantiate() failing if params contains interpolated values. ([#388](https://github.com/facebookresearch/hydra/issues/388)) +- Allow hydra.utils.instantiate() to accept non primitive objects for passthrough by name ([#400](https://github.com/facebookresearch/hydra/issues/400)) +- Fix to work when an Hydra app is executed in Jupyter notebook using the %run command ([#481](https://github.com/facebookresearch/hydra/issues/481)) +- Plugins are no longer imported twice during plugin discovery ([#482](https://github.com/facebookresearch/hydra/issues/482)) +- to_absolute_dir(path) now converts relative path to be relative to os.cwd() when used outside of Hydra ([#496](https://github.com/facebookresearch/hydra/issues/496)) + +Improved Documentation +---------------------- + +- Working examples are provided for all Hydra plugins in [plugins/examples](https://github.com/facebookresearch/hydra/tree/master/plugins/examples) ([#253](https://github.com/facebookresearch/hydra/issues/253)) +- The basic tutorial was rewritten to reflect many changes ([#602](https://github.com/facebookresearch/hydra/issues/602)) +- Add a new tutorial covering Structured Configs ([#628](https://github.com/facebookresearch/hydra/issues/628)) + + +0.11.3 (2019-12-29) +=================== + +Bug Fixes +--------- + +- Pin Hydra 0.11 to OmegaConf 1.4 to avoid breaking compatibility when OmegaConf 2.0 is released ([#334](https://github.com/facebookresearch/hydra/issues/334)) + +Improved Documentation +---------------------- + +- Document a simple Ray example ([#317](https://github.com/facebookresearch/hydra/issues/317)) + + +0.11.2 (2019-12-04) +=================== + +Features +-------- + +- Change website from cli.dev to hydra.cc (#314) + +Bug Fixes +--------- + +- Fixes --cfg command line flag not working (#305) + + +0.11.0 (2019-11-19) +=================== + +Features +-------- + +- Add hydra.experimental API for composing configuration on demand (hydra.experimental.compose) (#219) +- Add hydra.utils.get_original_cwd() to access original working directory and hydra.utils.to_absolute_path() to convert a path to absolute path (#251) +- Change hydra logging format pattern, example: "[2019-10-22 16:13:10,769][HYDRA] Installed Hydra Plugins" (#254) +- Change --cfg to require config type (one of 'job', 'hydra' or 'all') (#270) +- Upgrade to OmegaConf 1.4.0, see full change log [here](https://github.com/omry/omegaconf/releases/tag/1.4.0) (#280) +- Experimental support for Jupyter notebooks via compose API (#281) +- Allow configuring override_dirname via hydra.job.config.override_dirname to exclude specific keys or change separator characters (#95) + +Bug Fixes +--------- + +- Fix a bug that caused out of order composition when mixing config-groups with non-config-group in the defaults block (#261) +- Allow '=' to be used in the value of an override, eg. foo=bar=10 (key foo, value bar=10). (#266) +- Allow composing config files with dot in their name (foo.bar.yaml) (#271) + +Plugins +------- + +- hydra-colorlog plugin adds colored log output. + +Improved Documentation +---------------------- + +- Document utils.get_original_cwd() and utils.to_absolute_path("foo") (#251) + + +0.10.0 (2019-10-19) +=================== + +Configuration structure changes +------------------------------- + +- Change the default sweep subdir from ${hydra.job.num}_${hydra.job.id} to ${hydra.job.num} (#150) + +Features +-------- + +- App help now contains config groups and generated config + App help can now be customized + Hydra help is now available via --hydra-help (#1) +- Simplify install and uninstall commands for tab completion (#200) +- hydra.runtime.cwd now contains the original working directory the app was launched from (#244) + +Bug Fixes +--------- + +- Fix an error with tab completion that occurred when a TAB was pressed after two spaces (#203) +- Fix a bug when sweeping over groups that are used in an interpolation in defaults (#206) +- Fix tab completion for cases where app name looks like foo.par (#213) + +Improved Documentation +---------------------- + +- Describe news fragment types in more details in development/contributing (#150) +- Examples dir now mirrors the structure of the website docs (#209) + + +0.9.0 (2019-10-01) +================== + +Deprecations and Removals +------------------------- + +- Old demos directory was removed and a new tutorial directory as added (#167) + +Features +-------- + +- Make strict mode the default when a config file is specified directly (#150) +- Replace --verbose with a standard override (hydra.verbose) (#161) +- Add IntegrationTestSuite to test_utils for testing Launcher plugins (#168) +- Add support for specifying which config to print in -c, options are job (default), hydra or all. (#176) +- Hydra is now hosted on https://cli.dev! (#75) +- Move all Hydra configuration files to a subfolder (.hydra by default) under the output folder (#77) + +Bug Fixes +--------- + +- Fix a bug in tab completion of missing mandatory values. (#145) +- Fix a bug with multirun overriding free config groups (not in defaults) when strict mode is enabled (#181) +- Fix a bug that prevented sweeping over an unspecified ('???') default group (#187) + +Improved Documentation +---------------------- + +- Updated the primary tutorial on the web site and added a brand new tutorial directory (#58) +- Documented debugging methods in website (#6) + + +0.1.5 (2019-09-22) +================== + +Deprecations and Removals +------------------------- + +- Move FAIRTask, Submititit and FAIR-cluster-defaults plugins to fairinternal/hydra-fair-plugins repository (#138) +- Remove Fairtask and Submitit example configs from demos as they are no longer needed (#146) + +Features +-------- + +- Created hydra-core pip package, Hydra can now installed with 'pip install hydra-core' (#143) +- Finalized submitit support (#18) + +Plugins +------- + +- Add default launcher config for Fairtask and Submitit launcher plugins + + +0.1.4 (2019-09-18) +================== + +Features +-------- + +- hydra.utils.instantiate() can now take an additional optional kwargs dictionary to pass to constructor of the instantiated object (#142) +- Initial support for bash completion, see documentation for details (#8) + +Bug Fixes +--------- + +- Fixed Town Crier to generate correct links to issues in generated news file. (#122) +- Fixed bug with overriding hydra defaults from user config file. (#123) +- Fixed Singletons not getting serialized to remote jobs. (#128) +- Fixed a bug that prevented using submitit in strict mode (#129) +- Fixed example submitit config to set the job name (#133) + + +0.1.3 (2019-09-02) +================== + +Configuration structure changes +------------------------------- + +- Changed Hydra core defaults to be more appropriate for open source use. To get the FAIR cluster defaults install the fair_cluster plugin (#103) +- Changed output directories default to group by day (output/DAY/TIME instead of output/DAY_TIME) (#121) + +Features +-------- + +- Added the ability to prevent a default from being merged it by assigning null to it (hydra/launcher=null) (#106) +- Implemented Plugin discovery mechanism, this can be used to find all installed plugins that implement a specific interface (#119) +- Implemented an API to for manipulating the config search path (#120) + +Bug Fixes +--------- + +- Fixed config loading to properly support the use case in demos/8_specializing_config (#104) +- Fixed error message when the user config contains defaults that is a mapping and not a list (#107) +- Fixed config loading order to allow properly overriding Hydra config groups from user config (#115) + +Plugins +------- + +- New plugin: fair_cluster + Change Hydra defaults to be appropriate for the FAIR cluster + +Improved Documentation +---------------------- + +- Initial search path and plugins documentation (#103) + + +0.1.2 (2019-08-26) +================== + +Deprecations and Removals +------------------------- + +- Hydra config groups were moved to the hydra/namespace (#101) +- Removed support for .hydra directory, Hydra can be configured directly from the job config. (#91) + +Bug Fixes +--------- + +- Config loading rewrite fixed #88 (#88) + + +0.1.1 (2019-08-22) +================== + +Deprecations and Removals +------------------------- + +- Move non-public APIs into hydra._internal: + - Moved non-API code into hydra._interanl to flag it as private. + - Moved plugin interfaces into hydra.plugins. + - Moved code meant to be used by plugins to hydra.plugins.common. (#78) + +Features +-------- + +- Integrated towncrier to bring you this news! (#45) +- Hydra is now compatible with Windows (#63) +- Hydra apps can now be packaged and installed along with their configuration files. (#87) + +Bug Fixes +--------- + +- It is now possible to use ${override_dirname} in the output directory of a local job (#31) +- Override_dirname separator changed from : to =, for example: foo/a:10,b:10 => foo/a=10,b=10 (#63) +- Fixed automatic detection of missing copyright headers (#72) +- fixed a bug that caused an empty config to be returned if specifed config file did not have a .yaml extension. (#80) +- Multi change diff: + - Logging config search path in verbose logging to assist debugging of config load issues + - Saving hydra.yaml into the job dir to assist debugging hydra issues + - Fixed a bug caused by fairtask logging change + - Improved integration-tests debuggability by switching hydra to debug logging in them + - Added selective plugin testing to nox using env, for example PLUGINS=fairtask would only test fairtask. (#87) + +Improved Documentation +---------------------- + +- Improved the contributing docs (#45) +- Documented Hydra app packaging under Deployment/Application packaging (#87) diff --git a/testbed/facebookresearch__hydra/README.md b/testbed/facebookresearch__hydra/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5e274560626e1ea708fa150c44d63e89acd51875 --- /dev/null +++ b/testbed/facebookresearch__hydra/README.md @@ -0,0 +1,49 @@ +[![PyPI](https://img.shields.io/pypi/v/hydra-core)](https://pypi.org/project/hydra-core/) +[![CircleCI](https://img.shields.io/circleci/build/github/facebookresearch/hydra?token=af199cd2deca9e70e53776f9ded96284b10687e9)](https://circleci.com/gh/facebookresearch/hydra) +![PyPI - License](https://img.shields.io/pypi/l/hydra-core) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hydra-core) +[![Downloads](https://pepy.tech/badge/hydra-core/month)](https://pepy.tech/project/hydra-core/month?versions=0.11.*&versions=1.0.*) +[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) +[![Total alerts](https://img.shields.io/lgtm/alerts/g/facebookresearch/hydra.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/facebookresearch/hydra/alerts/) +[![Language grade: Python](https://img.shields.io/lgtm/grade/python/g/facebookresearch/hydra.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/facebookresearch/hydra/context:python) +[![](https://img.shields.io/badge/zulip-join_chat-brightgreen.svg)](https://hydra-framework.zulipchat.com) + +# Hydra +A framework for elegantly configuring complex applications. + +Check the [website](https://hydra.cc/) for more information. + +### Releases +#### Stable +**Hydra 0.11** is the stable version of Hydra. +- [Documentation](https://hydra.cc/docs/intro) +- Installation : `pip install hydra-core --upgrade` + +#### Release candidate +**Hydra 1.0** is the next major version of Hydra. It is currently a release candidate. +Please report any issues. +- [Release notes](https://github.com/facebookresearch/hydra/releases/tag/hydra-1.0.0rc1) +- [Documentation](https://hydra.cc/docs/next/intro) +- Installation : `pip install hydra-core --upgrade --pre` + +### License +Hydra is licensed under [MIT License](LICENSE). + +## Community +Ask questions in the chat or StackOverflow (Use the tag #fb-hydra or #omegaconf): +* [Chat](https://hydra-framework.zulipchat.com) +* [StackOverflow](https://stackexchange.com/filters/391828/hydra-questions) +* [Twitter](https://twitter.com/Hydra_Framework) + + +### Citing Hydra +If you use Hydra in your research please use the following BibTeX entry: +```text +@Misc{, + author = {Omry Yadan}, + title = {A framework for elegantly configuring complex applications}, + howpublished = {Github}, + year = {2019}, + url = {https://github.com/facebookresearch/hydra} +} +``` diff --git a/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/MANIFEST.in b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..9ee8f87d92deea54d4f546a13929cfc73db1b32d --- /dev/null +++ b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/MANIFEST.in @@ -0,0 +1,3 @@ +include hydra_pytest_plugin/py.typed +global-exclude *.pyc +global-exclude __pycache__ \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/README.md b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..649155d1452b8806dcbfaf6dfb0586142d8813b6 --- /dev/null +++ b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/README.md @@ -0,0 +1,5 @@ +# Hydra pytest plugin + +This plugin adds common Hydra related pytest fixtures. + +NOTE: The fixtures are currently experimental are likely to change with a future version of Hydra. \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/__init__.py b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ee03b5860eb8a5953eb980765c71248f1aefa063 --- /dev/null +++ b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/__init__.py @@ -0,0 +1,88 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +# Source of truth for version +__version__ = "1.0.0rc1" +import copy +from typing import Callable, List, Optional + +import pytest + +from hydra.core.singleton import Singleton +from hydra.test_utils.test_utils import SweepTaskFunction, TaskTestFunction +from hydra.types import TaskFunction + + +@pytest.fixture(scope="function") # type: ignore +def hydra_restore_singletons() -> None: + """ + Restore singletons state after the function returns + """ + state = copy.deepcopy(Singleton.get_state()) + yield + Singleton.set_state(state) + + +@pytest.fixture(scope="function") # type: ignore +def hydra_sweep_runner() -> Callable[ + [ + Optional[str], + Optional[str], + Optional[TaskFunction], + Optional[str], + Optional[str], + Optional[List[str]], + Optional[bool], + ], + SweepTaskFunction, +]: + def _( + calling_file: Optional[str], + calling_module: Optional[str], + task_function: Optional[TaskFunction], + config_path: Optional[str], + config_name: Optional[str], + overrides: Optional[List[str]], + strict: Optional[bool] = None, + ) -> SweepTaskFunction: + sweep = SweepTaskFunction() + sweep.calling_file = calling_file + sweep.calling_module = calling_module + sweep.task_function = task_function + sweep.config_path = config_path + sweep.config_name = config_name + sweep.strict = strict + sweep.overrides = overrides or [] + return sweep + + return _ + + +@pytest.fixture(scope="function") # type: ignore +def hydra_task_runner() -> Callable[ + [ + Optional[str], + Optional[str], + Optional[str], + Optional[str], + Optional[List[str]], + Optional[bool], + ], + TaskTestFunction, +]: + def _( + calling_file: Optional[str], + calling_module: Optional[str], + config_path: Optional[str], + config_name: Optional[str], + overrides: Optional[List[str]] = None, + strict: Optional[bool] = None, + ) -> TaskTestFunction: + task = TaskTestFunction() + task.overrides = overrides or [] + task.calling_file = calling_file + task.config_name = config_name + task.calling_module = calling_module + task.config_path = config_path + task.strict = strict + return task + + return _ diff --git a/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/py.typed b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/hydra_pytest_plugin/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/setup.py b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..1759e587aec484d61c7796850a132793fe7ade0b --- /dev/null +++ b/testbed/facebookresearch__hydra/extra/hydra-pytest-plugin/setup.py @@ -0,0 +1,35 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import codecs +import os +import re + +from setuptools import find_packages, setup + + +def find_version(*file_paths): + here = os.path.abspath(os.path.dirname(__file__)) + with codecs.open(os.path.join(here, *file_paths), "r") as fp: + version_file = fp.read() + version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) + if version_match: + return version_match.group(1) + raise RuntimeError("Unable to find version string.") + + +with open("README.md", "r") as fh: + LONG_DESC = fh.read() + setup( + name="hydra-pytest-plugin", + version=find_version("hydra_pytest_plugin", "__init__.py"), + author="Omry Yadan", + author_email="omry@fb.com", + description="Hydra pytest plugin", + long_description=LONG_DESC, + long_description_content_type="text/markdown", + url="https://github.com/facebookresearch/hydra/", + packages=find_packages(include=["hydra_pytest_plugin"]), + classifiers=["License :: OSI Approved :: MIT License", "Framework :: Pytest"], + install_requires=["hydra-core~=1.0.0rc1"], + # the following makes a plugin available to pytest + entry_points={"pytest11": ["name_of_plugin = hydra_pytest_plugin"]}, + ) diff --git a/testbed/facebookresearch__hydra/lgtm.yml b/testbed/facebookresearch__hydra/lgtm.yml new file mode 100644 index 0000000000000000000000000000000000000000..e7111d0c838c9fa1f4fcb371e2894a1e124a1b16 --- /dev/null +++ b/testbed/facebookresearch__hydra/lgtm.yml @@ -0,0 +1,2 @@ +queries: + - exclude: py/import-own-module diff --git a/testbed/facebookresearch__hydra/noxfile.py b/testbed/facebookresearch__hydra/noxfile.py new file mode 100644 index 0000000000000000000000000000000000000000..d047c04e06e9bddb22988601edd14850c6251500 --- /dev/null +++ b/testbed/facebookresearch__hydra/noxfile.py @@ -0,0 +1,379 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +# type: ignore +import copy +import os +import platform +from dataclasses import dataclass +from typing import List + +import nox +from nox.logger import logger + +BASE = os.path.abspath(os.path.dirname(__file__)) + +DEFAULT_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] +DEFAULT_OS_NAMES = ["Linux", "MacOS", "Windows"] + +PYTHON_VERSIONS = os.environ.get( + "NOX_PYTHON_VERSIONS", ",".join(DEFAULT_PYTHON_VERSIONS) +).split(",") + +PLUGINS_INSTALL_COMMANDS = (["pip", "install"], ["pip", "install", "-e"]) + +# Allow limiting testing to specific plugins +# The list ['ALL'] indicates all plugins +PLUGINS = os.environ.get("PLUGINS", "ALL").split(",") + +SKIP_CORE_TESTS = "0" +SKIP_CORE_TESTS = os.environ.get("SKIP_CORE_TESTS", SKIP_CORE_TESTS) != "0" +FIX = os.environ.get("FIX", "0") == "1" +VERBOSE = os.environ.get("VERBOSE", "0") +SILENT = VERBOSE == "0" + + +@dataclass +class Plugin: + name: str + path: str + module: str + + +def get_current_os() -> str: + current_os = platform.system() + if current_os == "Darwin": + current_os = "MacOS" + return current_os + + +print(f"Operating system\t:\t{get_current_os()}") +print(f"NOX_PYTHON_VERSIONS\t:\t{PYTHON_VERSIONS}") +print(f"PLUGINS\t\t\t:\t{PLUGINS}") +print(f"SKIP_CORE_TESTS\t\t:\t{SKIP_CORE_TESTS}") +print(f"FIX\t\t\t:\t{FIX}") +print(f"VERBOSE\t\t\t:\t{VERBOSE}") + + +def _upgrade_basic(session): + session.run( + "python", + "-m", + "pip", + "install", + "--upgrade", + "setuptools", + "pip", + silent=SILENT, + ) + + +def find_python_files_for_mypy(folder): + exclude_list = [""] + + def excluded(file: str) -> bool: + for exclude in exclude_list: + if file.startswith(exclude): + return True + return False + + for root, folders, files in os.walk(folder): + for filename in folders + files: + if filename.endswith(".py"): + if excluded(filename): + yield os.path.join(root, filename) + + +def install_hydra(session, cmd): + # clean install hydra + session.chdir(BASE) + session.run(*cmd, ".", silent=SILENT) + session.run(*cmd, "extra/hydra-pytest-plugin", silent=SILENT) + if not SILENT: + session.install("pipdeptree", silent=SILENT) + session.run("pipdeptree", "-p", "hydra-core") + + +def pytest_args(session, *args): + ret = ["pytest", "-Werror"] + ret.extend(args) + if len(session.posargs) > 0: + ret.extend(session.posargs) + return ret + + +def run_pytest(session, directory=".", *args): + pytest_cmd = pytest_args(session, directory, *args) + session.run(*pytest_cmd, silent=SILENT) + + +def get_setup_python_versions(classifiers): + pythons = filter(lambda line: "Programming Language :: Python" in line, classifiers) + return [p[len("Programming Language :: Python :: ") :] for p in pythons] + + +def get_plugin_os_names(classifiers: List[str]) -> List[str]: + oses = list(filter(lambda line: "Operating System" in line, classifiers)) + if len(oses) == 0: + # No Os is specified so all oses are supported + return DEFAULT_OS_NAMES + if len(oses) == 1 and oses[0] == "Operating System :: OS Independent": + # All oses are supported + return DEFAULT_OS_NAMES + else: + return [p.split("::")[-1].strip() for p in oses] + + +def select_plugins(session) -> List[Plugin]: + """ + Select all plugins that should be tested in this session. + Considers the current Python version and operating systems against the supported ones, + as well as the user plugins selection (via the PLUGINS environment variable). + """ + + assert session.python is not None, "Session python version is not specified" + blacklist = [".isort.cfg"] + example_plugins = [ + {"dir_name": x, "path": f"examples/{x}"} + for x in sorted(os.listdir(os.path.join(BASE, "plugins/examples"))) + if x not in blacklist + ] + plugins = [ + {"dir_name": x, "path": x} + for x in sorted(os.listdir(os.path.join(BASE, "plugins"))) + if x != "examples" + if x not in blacklist + ] + available_plugins = plugins + example_plugins + + ret = [] + skipped = [] + for plugin in available_plugins: + if not (plugin["dir_name"] in PLUGINS or PLUGINS == ["ALL"]): + skipped.append(f"Deselecting {plugin['dir_name']}: User request") + continue + + setup_py = os.path.join(BASE, "plugins", plugin["path"], "setup.py") + classifiers = session.run( + "python", setup_py, "--name", "--classifiers", silent=True + ).splitlines() + plugin_name = classifiers.pop(0) + plugin_python_versions = get_setup_python_versions(classifiers) + python_supported = session.python in plugin_python_versions + + plugin_os_names = get_plugin_os_names(classifiers) + os_supported = get_current_os() in plugin_os_names + + if not python_supported: + py_str = ", ".join(plugin_python_versions) + skipped.append( + f"Deselecting {plugin['dir_name']} : Incompatible Python {session.python}. Supports [{py_str}]" + ) + continue + + # Verify this plugin supports the OS we are testing on, skip otherwise + if not os_supported: + os_str = ", ".join(plugin_os_names) + skipped.append( + f"Deselecting {plugin['dir_name']}: Incompatible OS {get_current_os()}. Supports [{os_str}]" + ) + continue + + ret.append( + Plugin( + name=plugin_name, + path=plugin["path"], + module="hydra_plugins." + plugin["dir_name"], + ) + ) + + for msg in skipped: + logger.warn(msg) + + if len(ret) == 0: + logger.warn("No plugins selected") + return ret + + +def install_lint_deps(session): + _upgrade_basic(session) + session.run("pip", "install", "-r", "requirements/dev.txt", silent=SILENT) + session.run("pip", "install", "-e", ".", silent=SILENT) + + +@nox.session(python=PYTHON_VERSIONS) +def lint(session): + install_lint_deps(session) + install_hydra(session, ["pip", "install", "-e"]) + session.run("black", "--check", ".", silent=SILENT) + session.run( + "isort", + "--check", + "--diff", + ".", + "--skip=plugins", + "--skip=.nox", + silent=SILENT, + ) + session.run("mypy", ".", "--strict", silent=SILENT) + session.run("flake8", "--config", ".flake8") + session.run("yamllint", ".") + # Mypy for examples + for pyfile in find_python_files_for_mypy("examples"): + session.run("mypy", pyfile, "--strict", silent=SILENT) + + +@nox.session(python=PYTHON_VERSIONS) +def lint_plugins(session): + + install_cmd = ["pip", "install", "-e"] + install_hydra(session, install_cmd) + plugins = select_plugins(session) + + # plugin linting requires the plugins and their dependencies to be installed + for plugin in plugins: + cmd = install_cmd + [os.path.join("plugins", plugin.path)] + session.run(*cmd, silent=SILENT) + + install_lint_deps(session) + + session.run("flake8", "--config", ".flake8", "plugins") + # Mypy for plugins + for plugin in plugins: + session.chdir(os.path.join("plugins", plugin.path)) + blackcmd = ["black", "."] + isortcmd = ["isort", "."] + if not FIX: + blackcmd += ["--check"] + isortcmd += ["--check", "--diff"] + session.run(*blackcmd, silent=SILENT) + session.run(*isortcmd, silent=SILENT) + session.chdir(BASE) + + session.run("mypy", ".", "--strict", silent=SILENT) + + +@nox.session(python=PYTHON_VERSIONS) +@nox.parametrize( + "install_cmd", + PLUGINS_INSTALL_COMMANDS, + ids=[" ".join(x) for x in PLUGINS_INSTALL_COMMANDS], +) +def test_core(session, install_cmd): + _upgrade_basic(session) + install_hydra(session, install_cmd) + session.install("pytest") + + run_pytest(session, "tests") + + # test discovery_test_plugin + run_pytest(session, "tests/test_plugins/discovery_test_plugin", "--noconftest") + + # run namespace config loader tests + run_pytest(session, "tests/test_plugins/namespace_pkg_config_source_test") + + # Install and test example app + session.chdir(f"{BASE}/examples/advanced/hydra_app_example") + session.run(*install_cmd, ".", silent=SILENT) + run_pytest(session, ".") + + +@nox.session(python=PYTHON_VERSIONS) +@nox.parametrize( + "install_cmd", + PLUGINS_INSTALL_COMMANDS, + ids=[" ".join(x) for x in PLUGINS_INSTALL_COMMANDS], +) +def test_plugins(session, install_cmd): + _upgrade_basic(session) + session.install("pytest") + install_hydra(session, install_cmd) + selected_plugin = select_plugins(session) + for plugin in selected_plugin: + cmd = list(install_cmd) + [os.path.join("plugins", plugin.path)] + session.run(*cmd, silent=SILENT) + if not SILENT: + session.run("pipdeptree", "-p", plugin.name) + + # Test that we can import Hydra + session.run("python", "-c", "from hydra import main", silent=SILENT) + + # Test that we can import all installed plugins + for plugin in selected_plugin: + session.run("python", "-c", f"import {plugin.module}") + + # Run Hydra tests to verify installed plugins did not break anything + if not SKIP_CORE_TESTS: + run_pytest(session, "tests") + else: + session.log("Skipping Hydra core tests") + + # Run tests for all installed plugins + for plugin in selected_plugin: + # install all other plugins that are compatible with the current Python version + session.chdir(os.path.join(BASE, "plugins", plugin.path)) + run_pytest(session) + + +@nox.session(python="3.8") +def coverage(session): + coverage_env = { + "COVERAGE_HOME": BASE, + "COVERAGE_FILE": f"{BASE}/.coverage", + "COVERAGE_RCFILE": f"{BASE}/.coveragerc", + } + + _upgrade_basic(session) + session.install("coverage", "pytest") + install_hydra(session, ["pip", "install", "-e"]) + session.run("coverage", "erase") + + selected_plugins = select_plugins(session) + for plugin in selected_plugins: + session.run( + "pip", "install", "-e", os.path.join("plugins", plugin.path), silent=SILENT, + ) + + session.run("coverage", "erase", env=coverage_env) + # run plugin coverage + for plugin in selected_plugins: + session.chdir(os.path.join("plugins", plugin.path)) + cov_args = ["coverage", "run", "--append", "-m"] + cov_args.extend(pytest_args(session)) + session.run(*cov_args, silent=SILENT, env=coverage_env) + session.chdir(BASE) + + # run hydra-core coverage + session.run( + "coverage", + "run", + "--append", + "-m", + silent=SILENT, + env=coverage_env, + *pytest_args(session), + ) + + # Increase the fail_under as coverage improves + session.run("coverage", "report", "--fail-under=80", env=coverage_env) + session.run("coverage", "erase", env=coverage_env) + + +@nox.session(python=PYTHON_VERSIONS) +def test_jupyter_notebooks(session): + versions = copy.copy(DEFAULT_PYTHON_VERSIONS) + if session.python not in versions: + session.skip( + f"Not testing Jupyter notebook on Python {session.python}, supports [{','.join(versions)}]" + ) + # pyzmq 19.0.1 has installation issues on Windows + session.install("jupyter", "nbval", "pyzmq==19.0.0") + install_hydra(session, ["pip", "install", "-e"]) + args = pytest_args( + session, "--nbval", "examples/notebook/hydra_notebook_example.ipynb" + ) + # Jupyter notebook test on Windows yield warnings + args = [x for x in args if x != "-Werror"] + session.run(*args, silent=SILENT) + + args = pytest_args(session, "--nbval", "examples/notebook/%run_test.ipynb") + args = [x for x in args if x != "-Werror"] + session.run(*args, silent=SILENT) diff --git a/testbed/facebookresearch__hydra/pyproject.toml b/testbed/facebookresearch__hydra/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8efa4c0c3694df634cf17e85cc0871e6807cae64 --- /dev/null +++ b/testbed/facebookresearch__hydra/pyproject.toml @@ -0,0 +1,49 @@ +[tool.towncrier] + package = "hydra" + package_dir = "" + filename = "NEWS.md" + directory = "news/" + title_format = "{version} ({project_date})" + template = "news/_template.rst" + issue_format = "[#{issue}](https://github.com/facebookresearch/hydra/issues/{issue})" + start_string = "\n" + + [[tool.towncrier.type]] + directory = "feature" + name = "Features" + showcontent = true + + [[tool.towncrier.type]] + directory = "api_change" + name = "API Change (Renames, deprecations and removals)" + showcontent = true + + [[tool.towncrier.type]] + directory = "bugfix" + name = "Bug Fixes" + showcontent = true + + [[tool.towncrier.type]] + directory = "plugin" + name = "Plugins" + showcontent = true + + [[tool.towncrier.type]] + directory = "config" + name = "Configuration structure changes" + showcontent = true + + [[tool.towncrier.type]] + directory = "docs" + name = "Improved Documentation" + showcontent = true + + [[tool.towncrier.type]] + directory = "trivial" + name = "Trivial Changes" + showcontent = false + + [[tool.towncrier.type]] + directory = "maintenance" + name = "Maintenance Changes" + showcontent = true diff --git a/testbed/facebookresearch__hydra/pytest.ini b/testbed/facebookresearch__hydra/pytest.ini new file mode 100644 index 0000000000000000000000000000000000000000..a43b6a1425523a4fda5cf9f42e12d1d9a72b827d --- /dev/null +++ b/testbed/facebookresearch__hydra/pytest.ini @@ -0,0 +1,8 @@ +[pytest] +# reasons for excludes: +# .nox: large and irrelevant +# plugins: tested separately +# examples: contains the test for the example app, tested separately (app needs to be installed first) +# website: No python code +# tests/test_plugins : tested separately +norecursedirs = .nox plugins examples website tests/test_plugins build diff --git a/testbed/facebookresearch__hydra/setup.cfg b/testbed/facebookresearch__hydra/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..e55883bf2e350430932921823cb79cef9e845d0c --- /dev/null +++ b/testbed/facebookresearch__hydra/setup.cfg @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.6 +mypy_path=.stubs \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/setup.py b/testbed/facebookresearch__hydra/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..d291a7802ee6630f52fdad6851a5c31e850fa2df --- /dev/null +++ b/testbed/facebookresearch__hydra/setup.py @@ -0,0 +1,115 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +# type: ignore +import codecs +import os +import pathlib +import re +import shutil +from distutils import cmd +from os.path import exists, isdir, join +from typing import Any, List + +import pkg_resources +from setuptools import find_packages, setup + + +def find_version(*file_paths): + here = os.path.abspath(os.path.dirname(__file__)) + with codecs.open(os.path.join(here, *file_paths), "r") as fp: + version_file = fp.read() + version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) + if version_match: + return version_match.group(1) + raise RuntimeError("Unable to find version string.") + + +with pathlib.Path("requirements/requirements.txt").open() as requirements_txt: + install_requires = [ + str(requirement) + for requirement in pkg_resources.parse_requirements(requirements_txt) + ] + + +class CleanCommand(cmd.Command): + """ + Our custom command to clean out junk files. + """ + + description = "Cleans out junk files we don't want in the repo" + user_options: List[Any] = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + @staticmethod + def find(root, includes, excludes=[]): + res = [] + for parent, dirs, files in os.walk(root): + for f in dirs + files: + add = list() + for include in includes: + if re.findall(include, f): + add.append(join(parent, f)) + res.extend(add) + final_list = [] + # Exclude things that matches an exclude pattern + for ex in excludes: + for file in res: + if not re.findall(ex, file): + final_list.append(file) + return final_list + + def run(self): + delete_patterns = [ + ".eggs", + ".egg-info", + ".pytest_cache", + "build", + "dist", + "__pycache__", + ".pyc", + ] + deletion_list = CleanCommand.find( + ".", includes=delete_patterns, excludes=["\\.nox/.*"] + ) + + for f in deletion_list: + if exists(f): + if isdir(f): + shutil.rmtree(f, ignore_errors=True) + else: + os.unlink(f) + + +with open("README.md", "r") as fh: + LONG_DESC = fh.read() + setup( + cmdclass={"clean": CleanCommand}, + name="hydra-core", + version=find_version("hydra", "__init__.py"), + author="Omry Yadan", + author_email="omry@fb.com", + description="A framework for elegantly configuring complex applications", + long_description=LONG_DESC, + long_description_content_type="text/markdown", + url="https://github.com/facebookresearch/hydra", + keywords="command-line configuration yaml tab-completion", + packages=find_packages(include=["hydra"]), + include_package_data=True, + classifiers=[ + "License :: OSI Approved :: MIT License", + "Development Status :: 4 - Beta", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Operating System :: POSIX :: Linux", + "Operating System :: MacOS", + "Operating System :: Microsoft :: Windows", + ], + install_requires=install_requires, + # Install development dependencies with + # pip install -r requirements/dev.txt -e . + ) diff --git a/testbed/facebookresearch__hydra/tests/__init__.py b/testbed/facebookresearch__hydra/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c4103889ab5b2d67c24a5c3a3991463c175e9d7a --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +from hydra.core.utils import verify_pytest_plugin_version + +verify_pytest_plugin_version() diff --git a/testbed/facebookresearch__hydra/tests/scripts/test_bash_completion.exp b/testbed/facebookresearch__hydra/tests/scripts/test_bash_completion.exp new file mode 100644 index 0000000000000000000000000000000000000000..5aff8a0b76914a59e150284a1948d196cb1cfd23 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/scripts/test_bash_completion.exp @@ -0,0 +1,46 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +log_user 0 +set timeout 4 +set env(PS1) >> + +# Under pycharm, for some unknown reason readline displays +# the suggestions in a different order, breaking the test. +# This enables debug output from Hydra which is easier to test +set env(HYDRA_COMP_DEBUG) 1 +set env(INPUTRC) /dev/null + +# Suppress bash deprecation warning on Mac +set env(BASH_SILENCE_DEPRECATION_WARNING) 1 + +# parray env + +spawn bash --norc --noprofile +expect >> + +set in_line [lindex $argv 1] +set len [expr [string length $in_line] - 1] +set line [string range $in_line 5 $len] +set num_tabs [lindex $argv 2] +puts "input line: '$line'" +puts "num_tabs: $num_tabs" + +send "eval \"\$([lindex $argv 0] -sc install=bash)\"\r" +expect >> + +set command "[lindex $argv 0] $line" +while {$num_tabs > 0} { + incr num_tabs -1 + append command "\t" +} + +puts "command: '$command'" + +send $command + +puts "\nMatching:\n" +foreach arg [lrange $argv 3 end] { + expect { + "$arg" {puts "matched '$arg' to '$expect_out(0,string)'\nbuffer: '$expect_out(buffer)'";continue} + timeout {puts "Error matching $arg"; exit 1} + } +} diff --git a/testbed/facebookresearch__hydra/tests/test_apps/app_with_cfg_groups/conf/dataset/imagenet.yaml b/testbed/facebookresearch__hydra/tests/test_apps/app_with_cfg_groups/conf/dataset/imagenet.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a93c054e766e5bb5f6ebbcaf793b216e31bf94a3 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_apps/app_with_cfg_groups/conf/dataset/imagenet.yaml @@ -0,0 +1,4 @@ +# @package _global_ +dataset: + name: imagenet + path: /datasets/imagenet diff --git a/testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/config.yaml b/testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a0b92d5c60b4947f846d9f7407cd390bd62c6647 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/config.yaml @@ -0,0 +1,3 @@ +# @package _global_ +defaults: + - group: opt1 diff --git a/testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/group/opt1.yaml b/testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/group/opt1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4deb2bc8ea81a20965ea5b7235daec1f3ab9b62a --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_apps/app_with_config_with_free_group/conf/group/opt1.yaml @@ -0,0 +1,2 @@ +# @package _global_ +group_opt1: true diff --git a/testbed/facebookresearch__hydra/tests/test_basic_launcher.py b/testbed/facebookresearch__hydra/tests/test_basic_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa5d9e006ca63fd7255411999740110ce2d2018 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_basic_launcher.py @@ -0,0 +1,45 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import pytest + +from hydra.test_utils.launcher_common_tests import ( + BatchedSweeperTestSuite, + IntegrationTestSuite, + LauncherTestSuite, +) + + +@pytest.mark.parametrize("launcher_name, overrides", [("basic", [])]) +class TestBasicLauncher(LauncherTestSuite): + pass + + +@pytest.mark.parametrize( + "task_launcher_cfg, extra_flags", + [ + pytest.param( + { + "defaults": [ + {"hydra/launcher": "basic"}, + {"hydra/hydra_logging": "hydra_debug"}, + {"hydra/job_logging": "disabled"}, + ] + }, + ["-m"], + id="basic_launcher_multirun", + ) + ], +) +class TestBasicLauncherIntegration(IntegrationTestSuite): + """ + Run this launcher through the integration test suite. + """ + + pass + + +@pytest.mark.parametrize( + "launcher_name, overrides", + [("basic", ["hydra/sweeper=basic", "hydra.sweeper.params.max_batch_size=2"])], +) +class TestBasicSweeperWithBatching(BatchedSweeperTestSuite): + ... diff --git a/testbed/facebookresearch__hydra/tests/test_completion.py b/testbed/facebookresearch__hydra/tests/test_completion.py new file mode 100644 index 0000000000000000000000000000000000000000..227d1c4f5cb1a4959c859391fab1d9d61a4fd534 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_completion.py @@ -0,0 +1,314 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import distutils.spawn +import os +import re +import subprocess +import sys +from pathlib import Path +from typing import List + +import pytest +from packaging import version + +from hydra._internal.config_loader_impl import ConfigLoaderImpl +from hydra._internal.core_plugins.bash_completion import BashCompletion +from hydra._internal.utils import create_config_search_path +from hydra.plugins.completion_plugin import DefaultCompletionPlugin +from hydra.test_utils.test_utils import chdir_hydra_root + +chdir_hydra_root() + + +def is_expect_exists() -> bool: + return distutils.spawn.find_executable("expect") is not None + + +def is_fish_supported() -> bool: + if distutils.spawn.find_executable("fish") is None: + return False + + proc = subprocess.run( + ["fish", "--version"], stdout=subprocess.PIPE, encoding="utf-8" + ) + matches = re.match(r".*version\s+(\d\.\d\.\d)(.*)", proc.stdout) + if not matches: + return False + + fish_version, git_version = matches.groups() + + # Release after 3.1.2 or git build after 3.1.2 contain space fix. + if version.parse(fish_version) > version.parse("3.1.2"): + return True + elif version.parse(fish_version) >= version.parse("3.1.2") and git_version: + return True + else: + return False + + +def create_config_loader() -> ConfigLoaderImpl: + return ConfigLoaderImpl( + config_search_path=create_config_search_path( + search_path_dir=os.path.realpath("hydra/test_utils/configs/completion_test") + ) + ) + + +base_completion_list: List[str] = [ + "dict.", + "dict_prefix=", + "group=", + "hydra.", + "hydra/", + "list.", + "list_prefix=", + "test_hydra/", +] + + +@pytest.mark.parametrize("line_prefix", ["", "dict.key1=val1 ", "-r "]) +@pytest.mark.parametrize( + "line,num_tabs,expected", + [ + ("", 2, base_completion_list), + (" ", 2, base_completion_list), + ("dict", 2, ["dict.", "dict_prefix="]), + ("dict.", 3, ["dict.key1=", "dict.key2=", "dict.key3="]), + ("dict.key", 2, ["dict.key1=", "dict.key2=", "dict.key3="]), + ("dict.key1=", 2, ["dict.key1=val1"]), + ("dict.key3=", 2, ["dict.key3="]), # no value because dict.key3 is ??? + ("list", 2, ["list.", "list_prefix="]), + ("list.", 2, ["list.0=", "list.1=", "list.2="]), + ( + "hydra/", + 3, + [ + "hydra/help=", + "hydra/hydra_help=", + "hydra/hydra_logging=", + "hydra/job_logging=", + "hydra/launcher=", + "hydra/output=", + "hydra/sweeper=", + ], + ), + ("test_hydra/lau", 2, ["test_hydra/launcher="]), + ("test_hydra/launcher=", 2, ["test_hydra/launcher=fairtask"]), + ("test_hydra/launcher=fa", 2, ["test_hydra/launcher=fairtask"]), + # loading groups + ("gro", 2, ["group="]), + ("group=di", 2, ["group=dict"]), + ( + "group=dict ", + 3, + [ + "dict.", + "dict_prefix=", + "group.", + "group=", + "hydra.", + "hydra/", + "list.", + "list_prefix=", + "test_hydra/", + "toys.", + ], + ), + ("group=", 2, ["group=dict", "group=list"]), + ("group=dict group.dict=", 2, ["group.dict=true"]), + ("group=dict group=", 2, ["group=dict", "group=list"]), + ], +) +class TestCompletion: + def test_completion_plugin( + self, line_prefix: str, num_tabs: int, line: str, expected: List[str] + ) -> None: + config_loader = create_config_loader() + bc = DefaultCompletionPlugin(config_loader) + ret = bc._query(config_name="config.yaml", line=line_prefix + line) + assert ret == expected + + @pytest.mark.skipif( # type: ignore + not is_expect_exists(), + reason="expect should be installed to run the expects tests", + ) + @pytest.mark.parametrize( # type: ignore + "prog", [["python", "hydra/test_utils/completion.py"]] + ) + @pytest.mark.parametrize("shell", ["bash", "fish"]) # type: ignore + def test_shell_integration( + self, + shell: str, + prog: List[str], + num_tabs: int, + line_prefix: str, + line: str, + expected: List[str], + ) -> None: + if shell == "fish" and not is_fish_supported(): + pytest.skip("fish is not installed or the version is too old") + + # verify expect will be running the correct Python. + # This preemptively detect a much harder to understand error from expect. + ret = subprocess.check_output(["which", "python"], env=os.environ) + assert os.path.realpath(ret.decode("utf-8").strip()) == os.path.realpath( + sys.executable.strip() + ) + + verbose = os.environ.get("VERBOSE", "0") != "0" + + line1 = "line={}".format(line_prefix + line) + cmd = ["expect"] + if verbose: + cmd.append("-d") + + cmd.extend( + [ + "tests/scripts/test_{}_completion.exp".format(shell), + f"{' '.join(prog)}", + line1, + str(num_tabs), + ] + ) + + if shell == "fish": + # Fish will add a space to an unambiguous completion. + expected = [x + " " if re.match(r".*=\w+$", x) else x for x in expected] + + # Exactly match token end. See + # https://github.com/fish-shell/fish-shell/issues/6928 + expected = [re.escape(x) + "$" for x in expected] + + cmd.extend(expected) + if verbose: + print("\nCOMMAND:\n" + " ".join([f"'{x}'" for x in cmd])) + subprocess.check_call(cmd) + + +@pytest.mark.parametrize( # type: ignore + "line,expected", + [ + ("-c job", base_completion_list), + ("-c hydra ", base_completion_list), + ("-c all ", base_completion_list), + ], +) +def test_with_flags(line: str, expected: List[str]) -> None: + config_loader = create_config_loader() + bc = DefaultCompletionPlugin(config_loader) + ret = bc._query(config_name="config.yaml", line=line) + assert ret == expected + + +@pytest.mark.parametrize("relative", [True, False]) # type: ignore +@pytest.mark.parametrize("line_prefix", ["", "dict.key1=val1 "]) # type: ignore +@pytest.mark.parametrize( # type: ignore + "key_eq, fname_prefix, files, expected", + [ + ("abc=", "", ["foo.txt"], ["foo.txt"]), + ("abc=", "fo", ["foo.txt"], ["foo.txt"]), + ("abc=", "foo.txt", ["foo.txt"], ["foo.txt"]), + ("abc=", "foo", ["foo1.txt", "foo2.txt"], ["foo1.txt", "foo2.txt"]), + ("abc=", "foo1", ["foo1.txt", "foo2.txt"], ["foo1.txt"]), + ("abc=", "foo/bar", [], []), + ], +) +def test_file_completion( + tmpdir: Path, + files: List[str], + line_prefix: str, + key_eq: str, + fname_prefix: str, + expected: List[str], + relative: bool, +) -> None: + def create_files(in_files: List[str]) -> None: + for f in in_files: + path = Path(f) + dirname = path.parent + if str(dirname) != ".": + Path.mkdir(dirname, parents=True) + Path(f).touch(exist_ok=True) + + config_loader = create_config_loader() + try: + pwd = os.getcwd() + os.chdir(str(tmpdir)) + create_files(files) + bc = DefaultCompletionPlugin(config_loader) + probe = line_prefix + key_eq + if relative: + prefix = "." + os.path.sep + probe += prefix + fname_prefix + else: + prefix = os.path.realpath(".") + probe += os.path.join(prefix, fname_prefix) + + ret = bc._query(config_name="config.yaml", line=probe) + assert len(expected) == len(ret) + for idx, file in enumerate(expected): + assert key_eq + os.path.join(prefix, file) == ret[idx] + finally: + os.chdir(pwd) + + +@pytest.mark.parametrize( # type: ignore + "prefix", ["", " ", "\t", "/foo/bar", " /foo/bar/"] +) +@pytest.mark.parametrize( # type: ignore + "app_prefix", + [ + "python foo.py", + "hydra_app", + "hydra_app ", + "hy1-_=ra_app", + "foo.par", + "f_o-o1=2.par", + "python foo.py", + "python tutorials/hydra_app/example/hydra_app/main.py", + "python foo.py", + ], +) +@pytest.mark.parametrize( # type: ignore + "args_line, args_line_index", + [ + ("", None), + ("foo=bar", None), + ("foo=bar bar=baz0", None), + ("", 0), + ("foo=bar", 3), + ("foo=bar bar=baz0", 3), + ("dict.", 0), + ("dict.", 5), + ], +) +def test_strip( + prefix: str, app_prefix: str, args_line: str, args_line_index: int +) -> None: + app_prefix = prefix + app_prefix + if args_line: + app_prefix = app_prefix + " " + line = "{}{}".format(app_prefix, args_line) + result_line = BashCompletion.strip_python_or_app_name(line) + assert result_line == args_line + + +@pytest.mark.parametrize( # type: ignore + "shell,script,comp_func", + [ + ( + "bash", + "tests/scripts/test_bash_install_uninstall.sh", + "hydra_bash_completion", + ), + ( + "fish", + "tests/scripts/test_fish_install_uninstall.fish", + "hydra_fish_completion", + ), + ], +) +def test_install_uninstall(shell: str, script: str, comp_func: str) -> None: + if shell == "fish" and not is_fish_supported(): + pytest.skip("fish is not installed or the version is too old") + cmd = [shell, script, "python hydra/test_utils/completion.py", comp_func] + subprocess.check_call(cmd) diff --git a/testbed/facebookresearch__hydra/tests/test_config_loader.py b/testbed/facebookresearch__hydra/tests/test_config_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..9a0dd53bd6eb525bc5289f2ca579c9f669cc2879 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_config_loader.py @@ -0,0 +1,1194 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import re +from dataclasses import dataclass +from typing import Any, List + +import pkg_resources +import pytest +from omegaconf import MISSING, OmegaConf, ValidationError, open_dict + +from hydra._internal.config_loader_impl import ( + ConfigLoaderImpl, + DefaultElement, + ParsedConfigOverride, + ParsedOverride, +) +from hydra._internal.utils import create_config_search_path +from hydra.core.config_loader import LoadTrace +from hydra.core.config_store import ConfigStore, ConfigStoreWithProvider +from hydra.core.utils import env_override +from hydra.errors import HydraException, MissingConfigException +from hydra.test_utils.test_utils import chdir_hydra_root + +chdir_hydra_root() + + +@dataclass +class MySQLConfig: + driver: str = MISSING + host: str = MISSING + port: int = MISSING + user: str = MISSING + password: str = MISSING + + +@dataclass +class TopLevelConfig: + normal_yaml_config: bool = MISSING + db: MySQLConfig = MySQLConfig() + + +hydra_load_list: List[LoadTrace] = [ + LoadTrace("hydra_config", "structured://", "hydra", None), + LoadTrace("hydra/hydra_logging/default", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/job_logging/default", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/launcher/basic", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/sweeper/basic", "pkg://hydra.conf", "hydra", "hydra"), + LoadTrace("hydra/output/default", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/help/default", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/hydra_help/default", "pkg://hydra.conf", "hydra", None), +] + + +@pytest.mark.parametrize( + "path", + [ + pytest.param("file://hydra/test_utils/configs", id="file"), + pytest.param("pkg://hydra.test_utils.configs", id="pkg"), + ], +) +class TestConfigLoader: + def test_load_configuration(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="config.yaml", strict=False, overrides=["abc=123"] + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == {"normal_yaml_config": True, "abc": 123} + + def test_load_with_missing_default(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + with pytest.raises(MissingConfigException): + config_loader.load_configuration( + config_name="missing-default.yaml", overrides=[], strict=False + ) + + def test_load_with_missing_optional_default(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="missing-optional-default.yaml", overrides=[], strict=False + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == {} + + def test_load_with_optional_default(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="optional-default.yaml", overrides=[], strict=False + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == {"foo": 10} + + def test_load_changing_group_in_default(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="optional-default.yaml", + overrides=["group1=file2"], + strict=False, + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == {"foo": 20} + + @pytest.mark.parametrize( # type: ignore + "overrides,expected", + [ + pytest.param( + [], + {"group1_option1": True, "pkg1": {"group2_option1": True}}, + id="no_overrides", + ), + pytest.param( + ["group1@:pkg2=option1"], + {"pkg2": {"group1_option1": True}, "pkg1": {"group2_option1": True}}, + id="override_unspecified_pkg_of_default", + ), + pytest.param( + ["group1@:pkg1=option1"], + {"pkg1": {"group1_option1": True, "group2_option1": True}}, + id="override_two_groups_to_same_package", + ), + ], + ) + def test_load_changing_group_and_package_in_default( + self, path: str, overrides: List[str], expected: Any + ) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(f"{path}/package_tests") + ) + cfg = config_loader.load_configuration( + config_name="pkg_override", overrides=overrides + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == expected + + @pytest.mark.parametrize( # type: ignore + "overrides,expected", + [ + pytest.param( + [], + {"pkg1": {"group1_option1": True}, "pkg2": {"group1_option1": True}}, + id="baseline", + ), + pytest.param( + ["+group1@pkg3=option1"], + { + "pkg1": {"group1_option1": True}, + "pkg2": {"group1_option1": True}, + "pkg3": {"group1_option1": True}, + }, + id="append", + ), + pytest.param( + ["~group1@pkg1"], + {"pkg2": {"group1_option1": True}}, + id="delete_package", + ), + pytest.param( + ["group1@pkg1:new_pkg=option1"], + {"new_pkg": {"group1_option1": True}, "pkg2": {"group1_option1": True}}, + id="change_pkg1", + ), + pytest.param( + ["group1@pkg2:new_pkg=option1"], + {"pkg1": {"group1_option1": True}, "new_pkg": {"group1_option1": True}}, + id="change_pkg2", + ), + ], + ) + def test_override_compose_two_package_one_group( + self, path: str, overrides: List[str], expected: Any + ) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(f"{path}/package_tests") + ) + cfg = config_loader.load_configuration( + config_name="two_packages_one_group", overrides=overrides + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == expected + + def test_load_adding_group_not_in_default(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="optional-default.yaml", + overrides=["+group2=file1"], + strict=False, + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == {"foo": 10, "bar": 100} + + def test_change_run_dir_with_override(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="overriding_run_dir.yaml", + overrides=["hydra.run.dir=abc"], + strict=False, + ) + assert cfg.hydra.run.dir == "abc" + + def test_change_run_dir_with_config(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="overriding_run_dir.yaml", overrides=[], strict=False + ) + assert cfg.hydra.run.dir == "cde" + + def test_load_strict(self, path: str) -> None: + """ + Ensure that in strict mode we can override only things that are already in the config + :return: + """ + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + # Test that overriding existing things works in strict mode + cfg = config_loader.load_configuration( + config_name="compose.yaml", overrides=["foo=ZZZ"], strict=True + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == {"foo": "ZZZ", "bar": 100} + + # Test that accessing a key that is not there will fail + with pytest.raises(AttributeError): + # noinspection PyStatementEffect + cfg.not_here + + # Test that bad overrides triggers the KeyError + with pytest.raises(HydraException): + config_loader.load_configuration( + config_name="compose.yaml", overrides=["f00=ZZZ"], strict=True + ) + + def test_load_history(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + config_loader.load_configuration( + config_name="missing-optional-default.yaml", overrides=[], strict=False + ) + expected = hydra_load_list.copy() + expected.append(LoadTrace("missing-optional-default.yaml", path, "main", None)) + expected.append(LoadTrace("foo/missing", None, None, None)) + + assert config_loader.get_load_history() == expected + + def test_load_history_with_basic_launcher(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + config_loader.load_configuration( + config_name="custom_default_launcher.yaml", + overrides=["hydra/launcher=basic"], + strict=False, + ) + + expected = hydra_load_list.copy() + expected.append(LoadTrace("custom_default_launcher.yaml", path, "main", None)) + assert config_loader.get_load_history() == expected + + def test_load_yml_file(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="config.yml", overrides=[], strict=False + ) + with open_dict(cfg): + del cfg["hydra"] + + assert cfg == {"yml_file_here": True} + + def test_override_with_equals(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="config.yaml", overrides=["abc='cde=12'"], strict=False + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == OmegaConf.create({"normal_yaml_config": True, "abc": "cde=12"}) + + def test_compose_file_with_dot(self, path: str) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="compose.yaml", overrides=["group1=abc.cde"], strict=False + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == {"abc=cde": None, "bar": 100} + + def test_load_config_with_schema( + self, hydra_restore_singletons: Any, path: str + ) -> None: + + ConfigStore.instance().store( + name="config", node=TopLevelConfig, provider="this_test" + ) + ConfigStore.instance().store( + group="db", name="mysql", node=MySQLConfig, provider="this_test", + ) + + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + + cfg = config_loader.load_configuration( + config_name="config", overrides=["+db=mysql"] + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == { + "normal_yaml_config": True, + "db": { + "driver": "mysql", + "host": "???", + "port": "???", + "user": "omry", + "password": "secret", + }, + } + + expected = hydra_load_list.copy() + expected.append(LoadTrace("config", path, "main", "this_test")) + expected.append(LoadTrace("db/mysql", path, "main", "this_test")) + assert config_loader.get_load_history() == expected + + # verify illegal modification is rejected at runtime + with pytest.raises(ValidationError): + cfg.db.port = "fail" + + # verify illegal override is rejected during load + with pytest.raises(HydraException): + config_loader.load_configuration( + config_name="db/mysql", overrides=["db.port=fail"] + ) + + def test_load_config_file_with_schema_validation( + self, hydra_restore_singletons: Any, path: str + ) -> None: + + with ConfigStoreWithProvider("this_test") as cs: + cs.store(name="config", node=TopLevelConfig) + cs.store(group="db", name="mysql", node=MySQLConfig, package="db") + + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="config", overrides=["+db=mysql"], strict=False + ) + + with open_dict(cfg): + del cfg["hydra"] + assert cfg == { + "normal_yaml_config": True, + "db": { + "driver": "mysql", + "host": "???", + "port": "???", + "user": "omry", + "password": "secret", + }, + } + + expected = hydra_load_list.copy() + expected.append(LoadTrace("config", path, "main", "this_test")) + expected.append(LoadTrace("db/mysql", path, "main", "this_test")) + assert config_loader.get_load_history() == expected + + def test_assign_null( + self, hydra_restore_singletons: Any, path: str, recwarn: Any + ) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path(path) + ) + cfg = config_loader.load_configuration( + config_name="config.yaml", overrides=["abc=null"] + ) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == {"normal_yaml_config": True, "abc": None} + assert len(recwarn) == 0 + + +@pytest.mark.parametrize( # type:ignore + "in_primary,in_merged,expected", + [ + ([], [], []), + ( + [DefaultElement(config_group="a", config_name="aa")], + [], + [DefaultElement(config_group="a", config_name="aa")], + ), + ( + [DefaultElement(config_group="a", config_name="aa")], + [DefaultElement(config_group="b", config_name="bb")], + [ + DefaultElement(config_group="a", config_name="aa"), + DefaultElement(config_group="b", config_name="bb"), + ], + ), + ( + [ + DefaultElement(config_group="hydra_logging", config_name="default"), + DefaultElement(config_group="job_logging", config_name="default"), + DefaultElement(config_group="launcher", config_name="basic"), + DefaultElement(config_group="sweeper", config_name="basic"), + ], + [ + DefaultElement(config_group="optimizer", config_name="nesterov"), + DefaultElement(config_group="launcher", config_name="basic"), + ], + [ + DefaultElement(config_group="hydra_logging", config_name="default"), + DefaultElement(config_group="job_logging", config_name="default"), + DefaultElement(config_group="launcher", config_name="basic"), + DefaultElement(config_group="sweeper", config_name="basic"), + DefaultElement(config_group="optimizer", config_name="nesterov"), + ], + ), + ], +) +def test_merge_default_lists( + in_primary: List[DefaultElement], + in_merged: List[DefaultElement], + expected: List[DefaultElement], +) -> None: + ConfigLoaderImpl._combine_default_lists(in_primary, in_merged) + assert in_primary == expected + + +@pytest.mark.parametrize( # type:ignore + "config_file, overrides", + [ + # remove from config + ("removing-hydra-launcher-default.yaml", []), + # remove from override + ("config.yaml", ["~hydra/launcher"]), + # remove from both + ("removing-hydra-launcher-default.yaml", ["~hydra/launcher"]), + # second overrides removes + ("config.yaml", ["hydra/launcher=submitit", "~hydra/launcher"]), + ], +) +def test_default_removal(config_file: str, overrides: List[str]) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path("hydra/test_utils/configs") + ) + config_loader.load_configuration( + config_name=config_file, overrides=overrides, strict=False + ) + + expected = list( + filter(lambda x: x.filename != "hydra/launcher/basic", hydra_load_list.copy()) + ) + expected.append( + LoadTrace(config_file, "file://hydra/test_utils/configs", "main", None) + ) + assert config_loader.get_load_history() == expected + + +def test_defaults_not_list_exception() -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path("hydra/test_utils/configs") + ) + with pytest.raises(ValueError): + config_loader.load_configuration( + config_name="defaults_not_list.yaml", overrides=[], strict=False + ) + + +@pytest.mark.parametrize( # type:ignore + "module_name, resource_name", + [ + ("hydra.test_utils", ""), + ("hydra.test_utils", "__init__.py"), + ("hydra.test_utils", "configs"), + ("hydra.test_utils", "configs/config.yaml"), + ("hydra.test_utils.configs", ""), + ("hydra.test_utils.configs", "config.yaml"), + ("hydra.test_utils.configs", "group1"), + ("hydra.test_utils.configs", "group1/file1.yaml"), + ], +) +def test_resource_exists(module_name: str, resource_name: str) -> None: + assert pkg_resources.resource_exists(module_name, resource_name) is True + + +def test_override_hydra_config_value_from_config_file() -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path("hydra/test_utils/configs") + ) + + cfg = config_loader.load_configuration( + config_name="overriding_output_dir.yaml", overrides=[], strict=False + ) + assert cfg.hydra.run.dir == "foo" + + +def test_override_hydra_config_group_from_config_file() -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path("hydra/test_utils/configs") + ) + + config_loader.load_configuration( + config_name="overriding_logging_default.yaml", overrides=[], strict=False + ) + + # This load history is too different to easily reuse the standard hydra_load_list + assert config_loader.get_load_history() == [ + LoadTrace("hydra_config", "structured://", "hydra", None), + LoadTrace("hydra/hydra_logging/hydra_debug", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/job_logging/disabled", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/sweeper/basic", "pkg://hydra.conf", "hydra", "hydra"), + LoadTrace("hydra/output/default", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/help/default", "pkg://hydra.conf", "hydra", None), + LoadTrace("hydra/hydra_help/default", "pkg://hydra.conf", "hydra", None), + LoadTrace( + "overriding_logging_default.yaml", + "file://hydra/test_utils/configs", + "main", + None, + ), + ] + + +def test_list_groups() -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path( + "hydra/test_utils/configs/cloud_infra_example" + ) + ) + groups = config_loader.list_groups("") + assert sorted(groups) == [ + "application", + "cloud_provider", + "db", + "environment", + "hydra", + ] + + assert sorted(config_loader.list_groups("hydra")) == [ + "help", + "hydra_help", + "hydra_logging", + "job_logging", + "launcher", + "output", + "sweeper", + ] + + +def test_non_config_group_default() -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path("hydra/test_utils/configs") + ) + config_loader.load_configuration( + config_name="non_config_group_default.yaml", overrides=[], strict=False + ) + + expected = hydra_load_list.copy() + expected.extend( + [ + LoadTrace( + "non_config_group_default.yaml", + "file://hydra/test_utils/configs", + "main", + None, + ), + LoadTrace("some_config", "file://hydra/test_utils/configs", "main", None), + ] + ) + assert config_loader.get_load_history() == expected + + +def test_mixed_composition_order() -> None: + """ + Tests that the order of mixed composition (defaults contains both config group and non config group + items) is correct + """ + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path("hydra/test_utils/configs") + ) + config_loader.load_configuration( + config_name="mixed_compose.yaml", overrides=[], strict=False + ) + + expected = hydra_load_list.copy() + expected.extend( + [ + LoadTrace( + "mixed_compose.yaml", "file://hydra/test_utils/configs", "main", None + ), + LoadTrace("some_config", "file://hydra/test_utils/configs", "main", None), + LoadTrace("group1/file1", "file://hydra/test_utils/configs", "main", None), + LoadTrace("config", "file://hydra/test_utils/configs", "main", None), + ] + ) + + assert config_loader.get_load_history() == expected + + +def test_load_schema_as_config(hydra_restore_singletons: Any) -> None: + """ + Load structured config as a configuration + """ + ConfigStore.instance().store( + name="config", node=TopLevelConfig, provider="this_test" + ) + + ConfigStore.instance().store( + name="db/mysql", node=MySQLConfig, provider="this_test", + ) + + config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path(None)) + cfg = config_loader.load_configuration(config_name="config", overrides=[]) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == { + "normal_yaml_config": "???", + "db": { + "driver": MISSING, + "host": MISSING, + "port": MISSING, + "user": MISSING, + "password": MISSING, + }, + } + + expected = hydra_load_list.copy() + expected.extend([LoadTrace("config", "structured://", "this_test", None)]) + assert config_loader.get_load_history() == expected + + +@dataclass +class Plugin: + name: str = MISSING + params: Any = MISSING + + +@dataclass +class ConcretePlugin(Plugin): + name: str = "foobar_plugin" + + @dataclass + class FoobarParams: + foo: int = 10 + + params: FoobarParams = FoobarParams() + + +@dataclass +# A plugin that does not extend the parent Plugin class +class InvalidPlugin: + name: str = "invalid_plugin" + + +@dataclass +class Config: + plugin: Plugin = Plugin() + + +def test_overlapping_schemas(hydra_restore_singletons: Any) -> None: + + cs = ConfigStore.instance() + cs.store(name="config", node=Config) + cs.store(group="plugin", name="concrete", node=ConcretePlugin) + + config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path(None)) + cfg = config_loader.load_configuration(config_name="config", overrides=[]) + with open_dict(cfg): + del cfg["hydra"] + + assert cfg == {"plugin": {"name": "???", "params": "???"}} + assert OmegaConf.get_type(cfg.plugin) == Plugin + + cfg = config_loader.load_configuration( + config_name="config", overrides=["+plugin=concrete"] + ) + with open_dict(cfg): + del cfg["hydra"] + + assert cfg == {"plugin": {"name": "foobar_plugin", "params": {"foo": 10}}} + assert OmegaConf.get_type(cfg.plugin) == ConcretePlugin + assert OmegaConf.get_type(cfg.plugin.params) == ConcretePlugin.FoobarParams + with pytest.raises(ValidationError): + cfg.plugin = 10 + + +def test_invalid_plugin_merge(hydra_restore_singletons: Any) -> Any: + cs = ConfigStore.instance() + cs.store(name="config", node=Config) + cs.store(group="plugin", name="invalid", node=InvalidPlugin) + + cl = ConfigLoaderImpl(config_search_path=create_config_search_path(None)) + with pytest.raises(HydraException): + cl.load_configuration(config_name="config", overrides=["plugin=invalid"]) + + +def test_job_env_copy() -> None: + config_loader = ConfigLoaderImpl(config_search_path=create_config_search_path(None)) + with env_override({"zonk": "123456"}): + cfg = config_loader.load_configuration( + config_name=None, overrides=["hydra.job.env_copy=[zonk]"] + ) + assert cfg.hydra.job.env_set == {"zonk": "123456"} + + +@pytest.mark.parametrize( # type: ignore + "overrides,expected", + [ + ( + [], + { + "optimizer": {"type": "adam", "lr": 0.1, "beta": 0.01}, + "dataset": {"name": "imagenet", "path": "/datasets/imagenet"}, + "adam_imagenet": True, + }, + ), + ( + ["optimizer=nesterov"], + { + "optimizer": {"type": "nesterov", "lr": 0.001}, + "dataset": {"name": "imagenet", "path": "/datasets/imagenet"}, + "nesterov_imagenet": True, + }, + ), + ], +) +def test_complex_defaults(overrides: Any, expected: Any) -> None: + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path( + "tests/test_apps/sweep_complex_defaults/conf" + ) + ) + + cfg = config_loader.load_configuration(config_name="config", overrides=overrides) + with open_dict(cfg): + del cfg["hydra"] + assert cfg == expected + + +@pytest.mark.parametrize( # type: ignore + "override, expected", + [ + # changing item + pytest.param( + "db=postgresql", + ParsedOverride(None, "db", None, None, "postgresql"), + id="change_option", + ), + pytest.param( + "db@dest=postgresql", + ParsedOverride(None, "db", "dest", None, "postgresql"), + id="change_option", + ), + pytest.param( + "db@src:dest=postgresql", + ParsedOverride(None, "db", "src", "dest", "postgresql"), + id="change_both", + ), + pytest.param( + "db@dest", + ParsedOverride(None, "db", "dest", None, None), + id="change_package", + ), + pytest.param( + "db@src:dest", + ParsedOverride(None, "db", "src", "dest", None), + id="change_package", + ), + # adding item + pytest.param( + "+model=resnet", + ParsedOverride("+", "model", None, None, "resnet"), + id="add_item", + ), + pytest.param( + "+db@offsite_backup=mysql", + ParsedOverride("+", "db", "offsite_backup", None, "mysql"), + id="add_item", + ), + # deleting item + pytest.param( + "~db", ParsedOverride("~", "db", None, None, None), id="delete_item", + ), + pytest.param( + "~db@src", ParsedOverride("~", "db", "src", None, None), id="delete_item", + ), + pytest.param( + "~db", ParsedOverride("~", "db", None, None, None), id="delete_item", + ), + pytest.param( + "~db@src", ParsedOverride("~", "db", "src", None, None), id="delete_item", + ), + ], +) +def test_parse_override(override: str, expected: ParsedOverride) -> None: + ret = ConfigLoaderImpl._parse_override(override) + assert ret.override == expected + + +config_parse_error_msg = ( + "Error parsing config override : '{override}'" + "\nAccepted forms:" + "\n\tOverride: key=value" + "\n\tAppend: +key=value" + "\n\tDelete: ~key=value, ~key" +) + + +@pytest.mark.parametrize( # type: ignore + "override, expected", + [ + pytest.param( + "x.y.z=abc", ParsedConfigOverride(None, "x.y.z", "abc"), id="change_option", + ), + pytest.param( + "+x.y.z=abc", ParsedConfigOverride("+", "x.y.z", "abc"), id="adding", + ), + pytest.param( + "~x.y.z=abc", ParsedConfigOverride("~", "x.y.z", "abc"), id="adding", + ), + pytest.param("~x.y.z=", ParsedConfigOverride("~", "x.y.z", ""), id="adding"), + pytest.param( + "=a", + pytest.raises( + HydraException, + match=re.escape(config_parse_error_msg.format(override="=a")), + ), + id="no_key", + ), + ], +) +def test_parse_config_override(override: str, expected: Any) -> None: + if isinstance(expected, ParsedConfigOverride): + ret = ConfigLoaderImpl._parse_config_override(override) + assert ret == expected + else: + with expected: + ConfigLoaderImpl._parse_config_override(override) + + +defaults_list = [{"db": "mysql"}, {"db@src": "mysql"}, {"hydra/launcher": "basic"}] + + +@pytest.mark.parametrize( # type: ignore + "input_defaults,overrides,expected", + [ + # change item + pytest.param( + defaults_list, + ["db=postgresql"], + [{"db": "postgresql"}, {"db@src": "mysql"}, {"hydra/launcher": "basic"}], + id="change_option", + ), + pytest.param( + defaults_list, + ["db@src=postgresql"], + [{"db": "mysql"}, {"db@src": "postgresql"}, {"hydra/launcher": "basic"}], + id="change_option", + ), + pytest.param( + defaults_list, + ["db@:dest=postgresql"], + [ + {"db@dest": "postgresql"}, + {"db@src": "mysql"}, + {"hydra/launcher": "basic"}, + ], + id="change_both", + ), + pytest.param( + defaults_list, + ["db@src:dest=postgresql"], + [{"db": "mysql"}, {"db@dest": "postgresql"}, {"hydra/launcher": "basic"}], + id="change_both", + ), + pytest.param( + defaults_list, + ["db@XXX:dest=postgresql"], + pytest.raises( + HydraException, + match=re.escape( + "Could not rename package. No match for 'db@XXX' in the defaults list." + ), + ), + id="change_both_invalid_package", + ), + pytest.param( + defaults_list, + ["db@:dest"], + [{"db@dest": "mysql"}, {"db@src": "mysql"}, {"hydra/launcher": "basic"}], + id="change_package", + ), + pytest.param( + defaults_list, + ["db@src:dest"], + [{"db": "mysql"}, {"db@dest": "mysql"}, {"hydra/launcher": "basic"}], + id="change_package", + ), + pytest.param( + defaults_list, + ["db@XXX:dest"], + pytest.raises( + HydraException, + match=re.escape( + "Could not rename package. No match for 'db@XXX' in the defaults list." + ), + ), + id="change_package_from_invalid", + ), + # adding item + pytest.param([], ["+db=mysql"], [{"db": "mysql"}], id="adding_item"), + pytest.param( + defaults_list, + ["+db@backup=mysql"], + [ + {"db": "mysql"}, + {"db@src": "mysql"}, + {"hydra/launcher": "basic"}, + {"db@backup": "mysql"}, + ], + id="adding_item_at_package", + ), + pytest.param( + defaults_list, + ["+db=mysql"], + pytest.raises( + HydraException, + match=re.escape( + "Could not add. An item matching 'db' is already in the defaults list" + ), + ), + id="adding_duplicate_item", + ), + pytest.param( + defaults_list, + ["+db@src:foo=mysql"], + pytest.raises( + HydraException, + match=re.escape( + "Add syntax does not support package rename, remove + prefix" + ), + ), + id="add_rename_error", + ), + pytest.param( + defaults_list, + ["+db@src=mysql"], + pytest.raises( + HydraException, + match=re.escape( + "Could not add. An item matching 'db@src' is already in the defaults list" + ), + ), + id="adding_duplicate_item", + ), + pytest.param( + [], + ["db=mysql"], + pytest.raises( + HydraException, + match=re.escape( + "Could not override 'db'. No match in the defaults list." + "\nTo append to your default list use +db=mysql" + ), + ), + id="adding_without_plus", + ), + # deleting item + pytest.param( + [], + ["~db=mysql"], + pytest.raises( + HydraException, + match=re.escape( + "Could not delete. No match for 'db' in the defaults list." + ), + ), + id="delete_no_match", + ), + pytest.param( + defaults_list, + ["~db"], + [{"db@src": "mysql"}, {"hydra/launcher": "basic"}], + id="delete", + ), + pytest.param( + defaults_list, + ["~db=mysql"], + [{"db@src": "mysql"}, {"hydra/launcher": "basic"}], + id="delete", + ), + pytest.param( + defaults_list, + ["~db=postgresql"], + pytest.raises( + HydraException, + match=re.escape( + "Could not delete. No match for 'db=postgresql' in the defaults list." + ), + ), + id="delete_mismatch_value", + ), + pytest.param( + defaults_list, + ["~db@src"], + [{"db": "mysql"}, {"hydra/launcher": "basic"}], + id="delete", + ), + # syntax error + pytest.param( + defaults_list, + ["db"], + pytest.raises( + HydraException, + match=re.escape("Error parsing config group override : 'db'"), + ), + id="syntax_error", + ), + ], +) +def test_apply_overrides_to_defaults( + input_defaults: List[str], overrides: List[str], expected: Any +) -> None: + defaults = ConfigLoaderImpl._parse_defaults( + OmegaConf.create({"defaults": input_defaults}) + ) + parsed_overrides = [ + ConfigLoaderImpl._parse_override(override) for override in overrides + ] + + if isinstance(expected, list): + expected_defaults = ConfigLoaderImpl._parse_defaults( + OmegaConf.create({"defaults": expected}) + ) + ConfigLoaderImpl._apply_overrides_to_defaults( + overrides=parsed_overrides, defaults=defaults + ) + assert defaults == expected_defaults + else: + with expected: + ConfigLoaderImpl._apply_overrides_to_defaults( + overrides=parsed_overrides, defaults=defaults + ) + + +def test_delete_by_assigning_null_is_deprecated() -> None: + msg = ( + "\nRemoving from the defaults list by assigning 'null' " + "is deprecated and will be removed in Hydra 1.1." + "\nUse ~db" + ) + + defaults = ConfigLoaderImpl._parse_defaults( + OmegaConf.create({"defaults": [{"db": "mysql"}]}) + ) + parsed_overrides = [ConfigLoaderImpl._parse_override("db=null")] + + with pytest.warns(expected_warning=UserWarning, match=re.escape(msg)): + assert parsed_overrides[0].override.is_delete() + ConfigLoaderImpl._apply_overrides_to_defaults( + overrides=parsed_overrides, defaults=defaults + ) + assert defaults == [] + + +@pytest.mark.parametrize( # type: ignore + "input_cfg,strict,overrides,expected", + [ + # append + pytest.param({}, False, ["x=10"], {"x": 10}, id="append"), + pytest.param( + {}, + True, + ["x=10"], + pytest.raises( + HydraException, + match=re.escape( + "Could not override 'x'. No match in config." + "\nTo append to your config use +x=10" + ), + ), + id="append", + ), + pytest.param({}, True, ["+x=10"], {"x": 10}, id="append"), + # append item with @ + pytest.param( + {}, + False, + ["user@hostname=active"], + {"user@hostname": "active"}, + id="append@", + ), + pytest.param( + {}, + True, + ["+user@hostname=active"], + {"user@hostname": "active"}, + id="append@", + ), + pytest.param( + {"x": 20}, + True, + ["+x=10"], + pytest.raises( + HydraException, + match=re.escape( + "Could not append to config. An item is already at 'x'" + ), + ), + id="append", + ), + # override + pytest.param({"x": 20}, False, ["x=10"], {"x": 10}, id="override"), + pytest.param({"x": 20}, True, ["x=10"], {"x": 10}, id="override"), + pytest.param( + {"x": 20}, False, ["x=null"], {"x": None}, id="override_with_null" + ), + # delete + pytest.param({"x": 20}, False, ["~x"], {}, id="delete"), + pytest.param({"x": 20}, False, ["~x=20"], {}, id="delete"), + pytest.param({"x": {"y": 10}}, False, ["~x"], {}, id="delete"), + pytest.param({"x": {"y": 10}}, False, ["~x.y"], {"x": {}}, id="delete"), + pytest.param({"x": {"y": 10}}, False, ["~x.y=10"], {"x": {}}, id="delete"), + pytest.param({"x": 20}, True, ["~x"], {}, id="delete_strict"), + pytest.param({"x": 20}, True, ["~x=20"], {}, id="delete_strict"), + pytest.param({"x": {"y": 10}}, True, ["~x"], {}, id="delete_strict"), + pytest.param({"x": {"y": 10}}, True, ["~x.y"], {"x": {}}, id="delete_strict"), + pytest.param( + {"x": {"y": 10}}, True, ["~x.y=10"], {"x": {}}, id="delete_strict" + ), + pytest.param( + {"x": 20}, + False, + ["~z"], + pytest.raises( + HydraException, + match=re.escape("Could not delete from config. 'z' does not exist."), + ), + id="delete_error_key", + ), + pytest.param( + {"x": 20}, + False, + ["~x=10"], + pytest.raises( + HydraException, + match=re.escape( + "Could not delete from config. The value of 'x' is 20 and not 10." + ), + ), + id="delete_error_value", + ), + ], +) +def test_apply_overrides_to_config( + input_cfg: Any, strict: bool, overrides: List[str], expected: Any +) -> None: + cfg = OmegaConf.create(input_cfg) + OmegaConf.set_struct(cfg, strict) + if isinstance(expected, dict): + ConfigLoaderImpl._apply_overrides_to_config(overrides=overrides, cfg=cfg) + assert cfg == expected + else: + with expected: + ConfigLoaderImpl._apply_overrides_to_config(overrides=overrides, cfg=cfg) diff --git a/testbed/facebookresearch__hydra/tests/test_config_repository.py b/testbed/facebookresearch__hydra/tests/test_config_repository.py new file mode 100644 index 0000000000000000000000000000000000000000..c89e6b03da86520ff76881177ab56e09009ceda1 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_config_repository.py @@ -0,0 +1,179 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import re +from typing import Any, List, Optional + +import pytest + +from hydra._internal.config_repository import ConfigRepository +from hydra._internal.config_search_path_impl import ConfigSearchPathImpl +from hydra._internal.core_plugins.file_config_source import FileConfigSource +from hydra._internal.core_plugins.package_config_source import PackageConfigSource +from hydra._internal.core_plugins.structured_config_source import StructuredConfigSource +from hydra.core.object_type import ObjectType +from hydra.core.plugins import Plugins +from hydra.plugins.config_source import ConfigSource +from hydra.test_utils.config_source_common_tests import ConfigSourceTestSuite +from hydra.test_utils.test_utils import chdir_hydra_root + +chdir_hydra_root() + + +@pytest.mark.parametrize( + "type_, path", + [ + pytest.param( + FileConfigSource, + "file://tests/test_apps/config_source_test/dir", + id="FileConfigSource", + ), + pytest.param( + PackageConfigSource, + "pkg://tests.test_apps.config_source_test.dir", + id="PackageConfigSource", + ), + pytest.param( + StructuredConfigSource, + "structured://tests.test_apps.config_source_test.structured", + id="StructuredConfigSource", + ), + ], +) +class TestCoreConfigSources(ConfigSourceTestSuite): + pass + + +def create_config_search_path(path: str) -> ConfigSearchPathImpl: + csp = ConfigSearchPathImpl() + csp.append(provider="test", path=path) + return csp + + +@pytest.mark.parametrize( + "path", + [ + "file://tests/test_apps/config_source_test/dir", + "pkg://tests.test_apps.config_source_test.dir", + ], +) +class TestConfigRepository: + def test_config_repository_load( + self, hydra_restore_singletons: Any, path: str + ) -> None: + Plugins.instance() # initializes + config_search_path = create_config_search_path(path) + repo = ConfigRepository(config_search_path=config_search_path) + ret = repo.load_config( + config_path="dataset/imagenet.yaml", is_primary_config=False + ) + assert ret is not None + assert ret.config == { + "dataset": {"name": "imagenet", "path": "/datasets/imagenet"} + } + assert ( + repo.load_config(config_path="not_found.yaml", is_primary_config=True) + is None + ) + + def test_config_repository_exists( + self, hydra_restore_singletons: Any, path: str + ) -> None: + Plugins.instance() # initializes + config_search_path = create_config_search_path(path) + repo = ConfigRepository(config_search_path=config_search_path) + assert repo.config_exists("dataset/imagenet.yaml") + assert not repo.config_exists("not_found.yaml") + + @pytest.mark.parametrize( # type: ignore + "config_path,results_filter,expected", + [ + ( + "", + None, + [ + "config_without_group", + "dataset", + "level1", + "optimizer", + "package_test", + "primary_config", + "primary_config_with_non_global_package", + ], + ), + ("", ObjectType.GROUP, ["dataset", "level1", "optimizer", "package_test"]), + ( + "", + ObjectType.CONFIG, + [ + "config_without_group", + "dataset", + "primary_config", + "primary_config_with_non_global_package", + ], + ), + ("dataset", None, ["cifar10", "imagenet"]), + ("dataset", ObjectType.GROUP, []), + ("dataset", ObjectType.CONFIG, ["cifar10", "imagenet"]), + ("level1", ObjectType.GROUP, ["level2"]), + ("level1", ObjectType.CONFIG, []), + ("level1/level2", ObjectType.CONFIG, ["nested1", "nested2"]), + ], + ) + def test_config_repository_list( + self, + hydra_restore_singletons: Any, + path: str, + config_path: str, + results_filter: Optional[ObjectType], + expected: List[str], + ) -> None: + Plugins.instance() # initializes + config_search_path = create_config_search_path(path) + repo = ConfigRepository(config_search_path=config_search_path) + ret = repo.get_group_options( + group_name=config_path, results_filter=results_filter + ) + assert ret == expected + + +@pytest.mark.parametrize("sep", [" "]) # type: ignore +@pytest.mark.parametrize( # type: ignore + "cfg_text, expected", + [ + ("# @package{sep}foo.bar", {"package": "foo.bar"}), + ("# @package{sep} foo.bar", {"package": "foo.bar"}), + ("# @package {sep}foo.bar", {"package": "foo.bar"}), + ("#@package{sep}foo.bar", {"package": "foo.bar"}), + ("#@package{sep}foo.bar ", {"package": "foo.bar"}), + ( + "#@package{sep}foo.bar bah", + pytest.raises(ValueError, match=re.escape("Too many components in"),), + ), + ( + "#@package", + pytest.raises( + ValueError, match=re.escape("Expected header format: KEY VALUE, got"), + ), + ), + ( + """# @package{sep}foo.bar +foo: bar +# comment dsa +""", + {"package": "foo.bar"}, + ), + ( + """ +# @package{sep}foo.bar +""", + {"package": "foo.bar"}, + ), + ], +) +def test_get_config_header(cfg_text: str, expected: Any, sep: str) -> None: + cfg_text = cfg_text.format(sep=sep) + if isinstance(expected, dict): + header = ConfigSource._get_header_dict(cfg_text) + assert header == expected + else: + with expected: + ConfigSource._get_header_dict(cfg_text) diff --git a/testbed/facebookresearch__hydra/tests/test_config_search_path.py b/testbed/facebookresearch__hydra/tests/test_config_search_path.py new file mode 100644 index 0000000000000000000000000000000000000000..4a88035c8d59581e47a606150322dcacce8ea30a --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_config_search_path.py @@ -0,0 +1,175 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +from os.path import realpath +from typing import List, Optional, Tuple + +import pytest + +from hydra._internal.config_search_path_impl import ConfigSearchPathImpl +from hydra._internal.utils import compute_search_path_dir +from hydra.core.config_search_path import SearchPathElement, SearchPathQuery + + +def create_search_path(base_list: List[Tuple[str, str]]) -> ConfigSearchPathImpl: + csp = ConfigSearchPathImpl() + csp.config_search_path = [SearchPathElement(x[0], x[1]) for x in base_list] + return csp + + +def to_tuples_list( + search_path: ConfigSearchPathImpl, +) -> List[Tuple[Optional[str], Optional[str]]]: + return [(x.provider, x.path) for x in search_path.config_search_path] + + +@pytest.mark.parametrize( # type: ignore + "input_list, reference, expected_idx", + [ + ([], ("", ""), -1), + ([("a", "10")], ("a", None), 0), + ([("a", "10"), ("b", "20"), ("a", "30")], ("a", None), 2), + ([("a", "10"), ("b", "20"), ("a", "30")], ("b", None), 1), + ([("a", "10"), ("b", "20"), ("a", "30")], ("a", "10"), 0), + ], +) +def test_find_last_match( + input_list: List[Tuple[str, str]], reference: str, expected_idx: int, +) -> None: + csp = create_search_path(input_list) + assert ( + csp.find_last_match(SearchPathQuery(reference[0], reference[1])) == expected_idx + ) + + +@pytest.mark.parametrize( # type: ignore + "input_list, reference, expected_idx", + [ + ([], ("", ""), -1), + ([("a", "10")], ("a", None), 0), + ([("a", "10"), ("b", "20"), ("a", "30")], ("a", None), 0), + ([("a", "10"), ("b", "20"), ("a", "30")], ("b", None), 1), + ([("a", "10"), ("b", "20"), ("a", "30")], ("a", "10"), 0), + ], +) +def test_find_first_match( + input_list: List[Tuple[str, str]], reference: str, expected_idx: int, +) -> None: + csp = create_search_path(input_list) + sp = SearchPathQuery(reference[0], reference[1]) + assert csp.find_first_match(sp) == expected_idx + + +@pytest.mark.parametrize( # type: ignore + "base_list, provider, path, anchor_provider, result_list", + [ + # appending to an empty list + ([], "foo", "/path", None, [("foo", "/path")]), + # appending to a non empty list + ([("f1", "/p1")], "f2", "/p2", None, [("f1", "/p1"), ("f2", "/p2")]), + # appending after an anchor at key 0 + ( + [("f1", "A"), ("f2", "B")], + "f3", + "B", + SearchPathQuery(None, "A"), + [("f1", "A"), ("f3", "B"), ("f2", "B")], + ), + # appending after an anchor at the end of the list + ( + [("f1", "A"), ("f2", "B")], + "f3", + "B", + SearchPathQuery(None, "B"), + [("f1", "A"), ("f2", "B"), ("f3", "B")], + ), + # appending after a non existent anchor + ( + [], + "new_provider", + "/path", + "unregister_provider", + [("new_provider", "/path")], + ), + ], +) +def test_append( + base_list: List[Tuple[str, str]], + provider: str, + path: str, + anchor_provider: SearchPathQuery, + result_list: List[Tuple[str, str]], +) -> None: + csp = create_search_path(base_list) + csp.append(provider=provider, path=path, anchor=anchor_provider) + assert to_tuples_list(csp) == result_list + + +@pytest.mark.parametrize( # type: ignore + "base_list, provider, path, anchor_provider, result_list", + [ + # prepending to an empty list + ([], "foo", "/path", None, [("foo", "/path")]), + # prepending to a full list + ( + [("foo", "/path")], + "foo2", + "/path2", + None, + [("foo2", "/path2"), ("foo", "/path")], + ), + # prepending in front of an anchor at key 0 + ( + [("foo", "/path")], + "foo2", + "/path2", + SearchPathQuery("foo", "/path"), + [("foo2", "/path2"), ("foo", "/path")], + ), + # prepending in front of an anchor at key 1 + ( + [("foo", "/path"), ("foo2", "/path2")], + "foo3", + "/path3", + SearchPathQuery("foo2", "/path2"), + [("foo", "/path"), ("foo3", "/path3"), ("foo2", "/path2")], + ), + # prepending in front of a none existing anchor results in prepending to the head of the list + ([], "foo2", "/path2", "does not exist", [("foo2", "/path2")]), + ], +) +def test_prepend( + base_list: List[Tuple[str, str]], + provider: str, + path: str, + anchor_provider: SearchPathQuery, + result_list: List[Tuple[str, str]], +) -> None: + csp = create_search_path(base_list) + csp.prepend(provider=provider, path=path, anchor=anchor_provider) + assert to_tuples_list(csp) == result_list + + +@pytest.mark.parametrize( # type:ignore + "calling_file, calling_module, config_path, expected", + [ + ("foo.py", None, None, realpath("")), + ("foo/bar.py", None, None, realpath("foo")), + ("foo/bar.py", None, "conf", realpath("foo/conf")), + ("foo/bar.py", None, "../conf", realpath("conf")), + ("c:/foo/bar.py", None, "conf", realpath("c:/foo/conf")), + ("c:/foo/bar.py", None, "../conf", realpath("c:/conf")), + # short module name, keep it to avoid empty module error + (None, "module", None, "pkg://module"), + (None, "package.module", None, "pkg://package"), + (None, "package.module", "conf", "pkg://package/conf"), + # This is an unusual one. this behavior is intentional. + (None, "package.module", "../conf", "pkg://conf"), + (None, "package1.package2.module", "../conf", "pkg://package1/conf"), + # prefer package + ("foo", "package1.package2.module", "../conf", "pkg://package1/conf"), + ], +) +def test_compute_search_path_dir( + calling_file: str, calling_module: str, config_path: str, expected: str +) -> None: + res = compute_search_path_dir(calling_file, calling_module, config_path) + assert res == expected diff --git a/testbed/facebookresearch__hydra/tests/test_core_utils.py b/testbed/facebookresearch__hydra/tests/test_core_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4baca6d6548960d56040fc10dd70ce893499142c --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_core_utils.py @@ -0,0 +1,25 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +from typing import Any + +from omegaconf import open_dict + +from hydra._internal.config_loader_impl import ConfigLoaderImpl +from hydra._internal.utils import create_config_search_path +from hydra.core import utils +from hydra.core.hydra_config import HydraConfig + + +def test_accessing_hydra_config(hydra_restore_singletons: Any) -> Any: + utils.setup_globals() + + config_loader = ConfigLoaderImpl( + config_search_path=create_config_search_path("pkg://hydra.test_utils.configs") + ) + cfg = config_loader.load_configuration( + config_name="accessing_hydra_config", overrides=[] + ) + HydraConfig.instance().set_config(cfg) + with open_dict(cfg): + del cfg["hydra"] + assert cfg.job_name == "UNKNOWN_NAME" + assert cfg.config_name == "accessing_hydra_config" diff --git a/testbed/facebookresearch__hydra/tests/test_hydra.py b/testbed/facebookresearch__hydra/tests/test_hydra.py new file mode 100644 index 0000000000000000000000000000000000000000..071deef108d87a5fae72224090f6424837fe0cbd --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_hydra.py @@ -0,0 +1,814 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import os +import re +import subprocess +import sys +from pathlib import Path +from typing import Any, List, Set + +import pytest +from omegaconf import DictConfig, OmegaConf + +from hydra import MissingConfigException +from hydra.test_utils.test_utils import ( + TSweepRunner, + TTaskRunner, + chdir_hydra_root, + integration_test, + verify_dir_outputs, +) + +chdir_hydra_root() + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", [(".", None), (None, ".")] +) +def test_missing_conf_dir( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with pytest.raises(MissingConfigException): + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="dir_not_found", + config_name=None, + ): + pass + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_without_config/my_app.py", None), + (None, "tests.test_apps.app_without_config.my_app"), + ], +) +def test_missing_conf_file( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with pytest.raises(MissingConfigException): + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, + config_name="not_found.yaml", + ): + pass + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_without_config/my_app.py", None), + (None, "tests.test_apps.app_without_config.my_app"), + ], +) +def test_app_without_config___no_overrides( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, + config_name=None, + ) as task: + assert task.job_ret is not None + assert task.job_ret.cfg == {} + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/hydra_main_rerun/my_app.py", None), + (None, "tests.test_apps.hydra_main_rerun.my_app"), + ], +) +def test_hydra_main_rerun( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, + config_name=None, + ) as task: + assert task.job_ret is not None + assert task.job_ret.cfg == {} + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_without_config/my_app.py", None), + (None, "tests.test_apps.app_without_config.my_app"), + ], +) +def test_app_without_config__with_append( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="", + config_name=None, + overrides=["+abc=123", "+a.b=1", "+a.a=2"], + ) as task: + assert task.job_ret is not None and task.job_ret.cfg == dict( + abc=123, a=dict(b=1, a=2) + ) + verify_dir_outputs(task.job_ret, task.overrides) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_cfg/my_app.py", None), + (None, "tests.test_apps.app_with_cfg.my_app"), + ], +) +def test_app_with_config_file__no_overrides( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + + task = hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, # Testing legacy mode, both path and named are in config_path + config_name="config.yaml", + ) + with task: + assert task.job_ret is not None and task.job_ret.cfg == { + "dataset": {"name": "imagenet", "path": "/datasets/imagenet"} + } + + verify_dir_outputs(task.job_ret) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_cfg_groups_no_header/my_app.py", None,), + (None, "tests.test_apps.app_with_cfg_groups_no_header.my_app",), + ], +) +def test_config_without_package_header_warnings( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, + recwarn: Any, +) -> None: + task = hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="conf", + config_name="config.yaml", + ) + with task: + assert task.job_ret is not None and task.job_ret.cfg == { + "optimizer": {"type": "nesterov", "lr": 0.001} + } + + assert len(recwarn) == 1 + msg = recwarn.pop().message.args[0] + assert "Missing @package directive optimizer/nesterov.yaml in " in msg + assert ( + "See https://hydra.cc/docs/next/upgrades/0.11_to_1.0/adding_a_package_directive" + in msg + ) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_cfg_groups/my_app.py", None), + (None, "tests.test_apps.app_with_cfg_groups.my_app"), + ], +) +def test_app_with_config_path_backward_compatibility( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + msg = ( + "\nUsing config_path to specify the config name is deprecated, specify the config name via config_name" + "\nSee https://hydra.cc/next/upgrades/0.11_to_1.0/config_path_changes" + ) + + with pytest.warns(expected_warning=UserWarning, match=re.escape(msg)): + task = hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="conf/config.yaml", # Testing legacy mode, both path and named are in config_path + config_name=None, + ) + with task: + assert task.job_ret is not None and task.job_ret.cfg == { + "optimizer": {"type": "nesterov", "lr": 0.001} + } + + verify_dir_outputs(task.job_ret) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_cfg/my_app.py", None), + (None, "tests.test_apps.app_with_cfg.my_app"), + ], +) +def test_app_with_config_file__with_overide( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, + config_name="config.yaml", + overrides=["dataset.path=/datasets/imagenet2"], + ) as task: + assert task.job_ret is not None and task.job_ret.cfg == dict( + dataset=dict(name="imagenet", path="/datasets/imagenet2") + ) + verify_dir_outputs(task.job_ret, task.overrides) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_split_cfg/my_app.py", None), + (None, "tests.test_apps.app_with_split_cfg.my_app"), + ], +) +def test_app_with_split_config( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, + config_name="config.yaml", + ) as task: + assert task.job_ret is not None and task.job_ret.cfg == dict( + dataset=dict(name="imagenet", path="/datasets/imagenet"), + optimizer=dict(lr=0.001, type="nesterov"), + ) + verify_dir_outputs(task.job_ret) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_cfg_groups/my_app.py", None), + (None, "tests.test_apps.app_with_cfg_groups.my_app"), + ], +) +def test_app_with_config_groups__override_dataset__wrong( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with pytest.raises(MissingConfigException) as ex: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="conf", + config_name=None, + overrides=["+optimizer=wrong_name"], + ): + pass + assert sorted(ex.value.options) == sorted(["adam", "nesterov"]) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_cfg_groups/my_app.py", None), + (None, "tests.test_apps.app_with_cfg_groups.my_app"), + ], +) +def test_app_with_config_groups__override_all_configs( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="conf", + config_name=None, + overrides=["+optimizer=adam", "optimizer.lr=10"], + ) as task: + assert task.job_ret is not None and task.job_ret.cfg == dict( + optimizer=dict(type="adam", lr=10, beta=0.01) + ) + verify_dir_outputs(task.job_ret, overrides=task.overrides) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_custom_launcher/my_app.py", None), + (None, "tests.test_apps.app_with_custom_launcher.my_app"), + ], +) +def test_app_with_sweep_cfg__override_to_basic_launcher( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, + config_name="config.yaml", + overrides=["hydra/launcher=basic"], + ) as task: + assert task.job_ret is not None + assert task.job_ret.hydra_cfg is not None + hydra_cfg = task.job_ret.hydra_cfg + assert ( + hydra_cfg.hydra.launcher.cls + == "hydra._internal.core_plugins.basic_launcher.BasicLauncher" + ) + assert len(task.job_ret.hydra_cfg.hydra.launcher.params) == 0 + + +def test_short_module_name(tmpdir: Path) -> None: + cmd = [ + sys.executable, + "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py", + "hydra.run.dir=" + str(tmpdir), + ] + result = subprocess.check_output(cmd) + assert OmegaConf.create(str(result.decode("utf-8"))) == { + "db": {"driver": "mysql", "password": "secret", "user": "omry"} + } + + +def test_hydra_main_module_override_name(tmpdir: Path) -> None: + cfg = OmegaConf.create() + integration_test( + tmpdir=tmpdir, + task_config=cfg, + overrides=[], + prints="HydraConfig.get().job.name", + expected_outputs="Foo", + env_override={"HYDRA_MAIN_MODULE": "hydra.test_utils.configs.Foo"}, + ) + + +def test_short_hydra_main_module_override_name(tmpdir: Path) -> None: + cfg = OmegaConf.create() + integration_test( + tmpdir=tmpdir, + task_config=cfg, + overrides=[], + prints="HydraConfig.get().job.name", + expected_outputs="Foo", + env_override={"HYDRA_MAIN_MODULE": "Foo"}, + ) + + +@pytest.mark.parametrize( # type: ignore + "env_name", ["HYDRA_MAIN_MODULE", "FB_PAR_MAIN_MODULE", "FB_XAR_MAIN_MODULE"] +) +def test_module_env_override(tmpdir: Path, env_name: str) -> None: + """ + Tests that module name overrides are working. + """ + cmd = [ + sys.executable, + "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py", + "hydra.run.dir=" + str(tmpdir), + ] + modified_env = os.environ.copy() + modified_env[env_name] = "hydra.test_utils.configs.Foo" + result = subprocess.check_output(cmd, env=modified_env) + assert OmegaConf.create(str(result.decode("utf-8"))) == {"normal_yaml_config": True} + + +@pytest.mark.parametrize( # type: ignore + "flag,expected_keys", + [("--cfg=all", ["db", "hydra"]), ("--cfg=hydra", ["hydra"]), ("--cfg=job", ["db"])], +) +def test_cfg(tmpdir: Path, flag: str, expected_keys: List[str]) -> None: + cmd = [ + sys.executable, + "examples/tutorials/basic/your_first_hydra_app/5_defaults/my_app.py", + "hydra.run.dir=" + str(tmpdir), + flag, + ] + result = subprocess.check_output(cmd) + conf = OmegaConf.create(str(result.decode("utf-8"))) + for key in expected_keys: + assert key in conf + + +@pytest.mark.parametrize( # type: ignore + "flags,expected", + [ + ( + ["--cfg=job", "--package=_global_"], + """# @package _global_ +db: + driver: mysql + user: omry + pass: secret +""", + ), + ( + ["--cfg=job", "--package=db"], + """# @package db +driver: mysql +user: omry +pass: secret +""", + ), + (["--cfg=job", "--package=db.driver"], "mysql\n"), + ], +) +def test_cfg_with_package(tmpdir: Path, flags: List[str], expected: str) -> None: + cmd = [ + sys.executable, + "examples/tutorials/basic/your_first_hydra_app/5_defaults/my_app.py", + "hydra.run.dir=" + str(tmpdir), + ] + flags + + def norm(s: str) -> str: + return s.replace("\r\n", "\n").replace("\r", "\n") + + result = subprocess.check_output(cmd).decode("utf-8") + assert norm(result) == norm(expected) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_config_with_free_group/my_app.py", None), + (None, "tests.test_apps.app_with_config_with_free_group.my_app"), + ], +) +@pytest.mark.parametrize("overrides", [["+free_group=opt1,opt2"]]) # type: ignore +def test_multirun_with_free_override( + hydra_restore_singletons: Any, + hydra_sweep_runner: TSweepRunner, + calling_file: str, + calling_module: str, + overrides: List[str], +) -> None: + sweep = hydra_sweep_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="conf/", + config_name="config.yaml", + task_function=None, + overrides=overrides, + ) + with sweep: + assert sweep.returns is not None and len(sweep.returns[0]) == 2 + assert sweep.returns[0][0].overrides == ["+free_group=opt1"] + assert sweep.returns[0][0].cfg == {"group_opt1": True, "free_group_opt1": True} + assert sweep.returns[0][1].overrides == ["+free_group=opt2"] + assert sweep.returns[0][1].cfg == {"group_opt1": True, "free_group_opt2": True} + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + pytest.param( + "tests/test_apps/sweep_complex_defaults/my_app.py", None, id="file_path" + ), + pytest.param( + None, "tests.test_apps.sweep_complex_defaults.my_app", id="pkg_path" + ), + ], +) +def test_sweep_complex_defaults( + hydra_restore_singletons: Any, + hydra_sweep_runner: TSweepRunner, + calling_file: str, + calling_module: str, +) -> None: + with hydra_sweep_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="conf", + config_name="config.yaml", + task_function=None, + overrides=["optimizer=adam,nesterov"], + ) as sweep: + assert sweep.returns is not None and len(sweep.returns[0]) == 2 + assert sweep.returns[0][0].overrides == ["optimizer=adam"] + assert sweep.returns[0][1].overrides == ["optimizer=nesterov"] + + +@pytest.mark.parametrize( # type: ignore + "script, flag, overrides,expected", + [ + pytest.param( + "examples/tutorials/basic/your_first_hydra_app/1_simple_cli/my_app.py", + "--help", + ["hydra.help.template=foo"], + "foo\n", + id="simple_cli_app", + ), + pytest.param( + "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py", + "--help", + ["hydra.help.template=foo"], + "foo\n", + id="overriding_help_template", + ), + pytest.param( + "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py", + "--help", + ["hydra.help.template=$CONFIG", "db.user=root"], + """db: + driver: mysql + user: root + password: secret + +""", + id="overriding_help_template:$CONFIG", + ), + pytest.param( + "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py", + "--help", + ["hydra.help.template=$FLAGS_HELP"], + """--help,-h : Application's help +--hydra-help : Hydra's help +--version : show program's version number and exit +--cfg,-c : Show config instead of running [job|hydra|all] +--package,-p : Config package to show +--run,-r : Run a job +--multirun,-m : Run multiple jobs with the configured launcher +--shell-completion,-sc : Install or Uninstall shell completion: + Bash - Install: + eval "$(python {script} -sc install=bash)" + Bash - Uninstall: + eval "$(python {script} -sc uninstall=bash)" + + Fish - Install: + python {script} -sc install=fish | source + Fish - Uninstall: + python {script} -sc uninstall=fish | source + +--config-path,-cp : Overrides the config_path specified in hydra.main(). + The config_path is relative to the Python file declaring @hydra.main() +--config-name,-cn : Overrides the config_name specified in hydra.main() +--info,-i : Print Hydra information +Overrides : Any key=value arguments to override config values (use dots for.nested=overrides) +""", + id="overriding_help_template:$FLAGS_HELP", + ), + pytest.param( + "examples/tutorials/basic/your_first_hydra_app/4_config_groups/my_app.py", + "--help", + ["hydra.help.template=$APP_CONFIG_GROUPS"], + """db: mysql, postgresql + +""", + id="overriding_help_template:$APP_CONFIG_GROUPS", + ), + pytest.param( + "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py", + "--hydra-help", + ["hydra.hydra_help.template=foo"], + "foo\n", + id="overriding_hydra_help_template", + ), + pytest.param( + "examples/tutorials/basic/your_first_hydra_app/2_config_file/my_app.py", + "--hydra-help", + ["hydra.hydra_help.template=$FLAGS_HELP"], + """--help,-h : Application's help +--hydra-help : Hydra's help +--version : show program's version number and exit +--cfg,-c : Show config instead of running [job|hydra|all] +--package,-p : Config package to show +--run,-r : Run a job +--multirun,-m : Run multiple jobs with the configured launcher +--shell-completion,-sc : Install or Uninstall shell completion: + Bash - Install: + eval "$(python {script} -sc install=bash)" + Bash - Uninstall: + eval "$(python {script} -sc uninstall=bash)" + + Fish - Install: + python {script} -sc install=fish | source + Fish - Uninstall: + python {script} -sc uninstall=fish | source + +--config-path,-cp : Overrides the config_path specified in hydra.main(). + The config_path is relative to the Python file declaring @hydra.main() +--config-name,-cn : Overrides the config_name specified in hydra.main() +--info,-i : Print Hydra information +Overrides : Any key=value arguments to override config values (use dots for.nested=overrides) +""", + id="overriding_hydra_help_template:$FLAGS_HELP", + ), + ], +) +def test_help( + tmpdir: Path, script: str, flag: str, overrides: List[str], expected: Any, +) -> None: + cmd = [sys.executable, script, "hydra.run.dir=" + str(tmpdir)] + cmd.extend(overrides) + cmd.append(flag) + print(" ".join(cmd)) + result = str(subprocess.check_output(cmd).decode("utf-8")) + # normalize newlines on Windows to make testing easier + result = result.replace("\r\n", "\n") + assert result == expected.format(script=script) + + +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/interpolating_dir_hydra_to_app/my_app.py", None), + (None, "tests.test_apps.interpolating_dir_hydra_to_app.my_app"), + ], +) +def test_interpolating_dir_hydra_to_app( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, +) -> None: + basedir = "foo" + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, + config_name="config.yaml", + overrides=["experiment.base_dir=" + basedir], + ) as task: + assert task.temp_dir is not None + path = Path(task.temp_dir) / basedir + assert path.exists() + + +def test_sys_exit(tmpdir: Path) -> None: + cmd = [ + sys.executable, + "tests/test_apps/sys_exit/my_app.py", + "hydra.run.dir=" + str(tmpdir), + ] + assert subprocess.run(cmd).returncode == 42 + + +@pytest.mark.parametrize( # type: ignore + "task_config, overrides, expected_dir", + [ + ({"hydra": {"run": {"dir": "foo"}}}, [], "foo"), + ({}, ["hydra.run.dir=bar"], "bar"), + ({"hydra": {"run": {"dir": "foo"}}}, ["hydra.run.dir=boom"], "boom"), + ( + { + "hydra": {"run": {"dir": "foo-${hydra.job.override_dirname}"}}, + "app": {"a": 1, "b": 2}, + }, + ["app.a=20"], + "foo-app.a=20", + ), + ], +) +def test_local_run_workdir( + tmpdir: Path, task_config: DictConfig, overrides: List[str], expected_dir: str +) -> None: + cfg = OmegaConf.create(task_config) + assert isinstance(cfg, DictConfig) + expected_dir1 = tmpdir / expected_dir + integration_test( + tmpdir=tmpdir, + task_config=cfg, + overrides=overrides, + prints="os.getcwd()", + expected_outputs=str(expected_dir1), + ) + + +def test_hydra_env_set(tmpdir: Path) -> None: + cfg = OmegaConf.create({"hydra": {"job": {"env_set": {"foo": "bar"}}}}) + integration_test( + tmpdir=tmpdir, + task_config=cfg, + overrides=[], + prints="os.environ['foo']", + expected_outputs="bar", + ) + + +@pytest.mark.parametrize( # type: ignore + "override", [pytest.param("xyz", id="db=xyz"), pytest.param("", id="db=")] +) +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + pytest.param("hydra/test_utils/example_app.py", None, id="file"), + pytest.param(None, "hydra.test_utils.example_app", id="module"), + ], +) +def test_override_with_invalid_group_choice( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, + override: str, +) -> None: + msg = f"""Could not load db/{override}, available options:\ndb:\n\tmysql\n\tpostgresql""" + + with pytest.raises(MissingConfigException, match=re.escape(msg)): + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path="configs", + config_name="db_conf", + overrides=[f"db={override}"], + ): + ... + + +@pytest.mark.parametrize("config_path", ["dir1", "dir2"]) # type: ignore +@pytest.mark.parametrize("config_name", ["cfg1", "cfg2"]) # type: ignore +def test_config_name_and_path_overrides( + tmpdir: Path, config_path: str, config_name: str +) -> None: + cmd = [ + sys.executable, + "tests/test_apps/app_with_multiple_config_dirs/my_app.py", + "hydra.run.dir=" + str(tmpdir), + f"--config-name={config_name}", + f"--config-path={config_path}", + ] + print(" ".join(cmd)) + result = str(subprocess.check_output(cmd).decode("utf-8")).strip() + # normalize newlines on Windows to make testing easier + result = result.replace("\r\n", "\n") + assert result == f"{config_path}_{config_name}: true" + + +@pytest.mark.parametrize( # type: ignore + "overrides, expected_files", + [ + ([], {"my_app.log", ".hydra"}), + (["hydra.output_subdir=foo"], {"my_app.log", "foo"}), + (["hydra.output_subdir=null"], {"my_app.log"}), + ], +) +@pytest.mark.parametrize( # type: ignore + "calling_file, calling_module", + [ + ("tests/test_apps/app_with_cfg/my_app.py", None), + (None, "tests.test_apps.app_with_cfg.my_app"), + ], +) +def test_hydra_output_dir( + hydra_restore_singletons: Any, + hydra_task_runner: TTaskRunner, + calling_file: str, + calling_module: str, + overrides: List[str], + expected_files: Set[str], +) -> None: + with hydra_task_runner( + calling_file=calling_file, + calling_module=calling_module, + config_path=None, + config_name=None, + overrides=overrides, + ) as task: + assert task.temp_dir is not None + path = Path(task.temp_dir) + files = set([str(x)[len(task.temp_dir) + 1 :] for x in path.iterdir()]) + assert files == expected_files diff --git a/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/setup.py b/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c10ba5ad2b94abd7310433dd750c6dc2a8e6e3 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/setup.py @@ -0,0 +1,12 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +from setuptools import find_namespace_packages, setup + +setup( + name="hydra-namespace-test-plugin", + version="0.1.0", + author="Omry Yadan", + author_email="omry@fb.com", + url="https://github.com/facebookresearch/hydra/", + packages=find_namespace_packages(include=["some_namespace.*"]), + install_requires=["hydra-core==1.0.*"], +) diff --git a/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/level1/level2/nested1.yaml b/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/level1/level2/nested1.yaml new file mode 100644 index 0000000000000000000000000000000000000000..639036e290432ab345ea9122dd9d47df29d95b64 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/level1/level2/nested1.yaml @@ -0,0 +1,2 @@ +# @package _global_ +l1_l2_n1: true diff --git a/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/explicit.yaml b/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/explicit.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a2f16c7ee87399b132ff70eee607912bda98e3e4 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/explicit.yaml @@ -0,0 +1,2 @@ +# @package a.b +foo: bar diff --git a/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/group_name.yaml b/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/group_name.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9be1c15f9ad42fcc8a0effb0800db5facc8387b2 --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_plugins/namespace_pkg_config_source_test/some_namespace/namespace_test/dir/package_test/group_name.yaml @@ -0,0 +1,2 @@ +# @package foo._group_._name_ +foo: bar diff --git a/testbed/facebookresearch__hydra/tests/test_utils.py b/testbed/facebookresearch__hydra/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d43c6ebfa2570eb4476ab8317fda0eaf6f52348b --- /dev/null +++ b/testbed/facebookresearch__hydra/tests/test_utils.py @@ -0,0 +1,322 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +import copy +import os +from pathlib import Path +from typing import Any, Dict, Optional + +import pytest +from omegaconf import DictConfig, OmegaConf + +import hydra._internal.utils as internal_utils +from hydra import utils +from hydra.conf import HydraConf, RuntimeConf +from hydra.core.hydra_config import HydraConfig +from hydra.types import ObjectConf + + +def some_method() -> int: + return 42 + + +class Bar: + def __init__(self, a: Any, b: Any, c: Any, d: Any = "default_value") -> None: + self.a = a + self.b = b + self.c = c + self.d = d + + def __repr__(self) -> str: + return f"a={self.a}, b={self.b}, c={self.c}, d={self.d}" + + @staticmethod + def static_method() -> int: + return 43 + + def __eq__(self, other: Any) -> Any: + """Overrides the default implementation""" + if isinstance(other, Bar): + + return ( + self.a == other.a + and self.b == other.b + and self.c == other.c + and self.d == other.d + ) + return NotImplemented + + def __ne__(self, other: Any) -> Any: + """Overrides the default implementation (unnecessary in Python 3)""" + x = self.__eq__(other) + if x is not NotImplemented: + return not x + return NotImplemented + + +class Foo: + def __init__(self, x: int) -> None: + self.x = x + + def __eq__(self, other: Any) -> Any: + if isinstance(other, Foo): + return self.x == other.x + return False + + +class Baz(Foo): + @classmethod + def class_method(self, y: int) -> Any: + return self(y + 1) + + @staticmethod + def static_method(z: int) -> int: + return z + + +class Fii: + def __init__(self, a: Baz = Baz(10)): + self.a = a + + def __repr__(self) -> str: + return f"a={self.a}" + + def __eq__(self, other: Any) -> Any: + """Overrides the default implementation""" + if isinstance(other, Fii): + + return self.a == other.a + return NotImplemented + + def __ne__(self, other: Any) -> Any: + """Overrides the default implementation (unnecessary in Python 3)""" + x = self.__eq__(other) + if x is not NotImplemented: + return not x + return NotImplemented + + +fii = Fii() + + +def fum(k: int) -> int: + return k + 1 + + +@pytest.mark.parametrize( # type: ignore + "path,expected_type", [("tests.test_utils.Bar", Bar)] +) +def test_get_class(path: str, expected_type: type) -> None: + assert utils.get_class(path) == expected_type + + +@pytest.mark.parametrize( # type: ignore + "path,return_value", [("tests.test_utils.some_method", 42)] +) +def test_get_method(path: str, return_value: Any) -> None: + assert utils.get_method(path)() == return_value + + +@pytest.mark.parametrize( # type: ignore + "path,return_value", [("tests.test_utils.Bar.static_method", 43)] +) +def test_get_static_method(path: str, return_value: Any) -> None: + assert utils.get_static_method(path)() == return_value + + +@pytest.mark.parametrize( # type: ignore + "input_conf, key_to_get_config, kwargs_to_pass, expected", + [ + ( + { + "cls": "tests.test_utils.Bar", + "params": {"a": 10, "b": 20, "c": 30, "d": 40}, + }, + None, + {}, + Bar(10, 20, 30, 40), + ), + ( + { + "all_params": { + "main": { + "cls": "tests.test_utils.Bar", + "params": {"a": 10, "b": 20, "c": "${all_params.aux.c}"}, + }, + "aux": {"c": 30}, + } + }, + "all_params.main", + {"d": 40}, + Bar(10, 20, 30, 40), + ), + ( + {"cls": "tests.test_utils.Bar", "params": {"b": 20, "c": 30}}, + None, + {"a": 10, "d": 40}, + Bar(10, 20, 30, 40), + ), + ( + {"cls": "tests.test_utils.Bar", "params": {"b": 200, "c": "${params.b}"}}, + None, + {"a": 10, "d": 40}, + Bar(10, 200, 200, 40), + ), + # Check class and static methods + ( + {"cls": "tests.test_utils.Baz.class_method", "params": {"y": 10}}, + None, + {}, + Baz(11), + ), + ( + {"cls": "tests.test_utils.Baz.static_method", "params": {"z": 43}}, + None, + {}, + 43, + ), + # Check nested types and static methods + ({"cls": "tests.test_utils.Fii", "params": {}}, None, {}, Fii(Baz(10)),), + ( + {"cls": "tests.test_utils.fii.a.class_method", "params": {"y": 10}}, + None, + {}, + Baz(11), + ), + ( + {"cls": "tests.test_utils.fii.a.static_method", "params": {"z": 43}}, + None, + {}, + 43, + ), + # Check that default value is respected + ( + {"cls": "tests.test_utils.Bar", "params": {"b": 200, "c": "${params.b}"}}, + None, + {"a": 10}, + Bar(10, 200, 200, "default_value"), + ), + ( + {"cls": "tests.test_utils.Bar", "params": {}}, + None, + {"a": 10, "b": 20, "c": 30}, + Bar(10, 20, 30, "default_value"), + ), + # call a function from a module + ({"cls": "tests.test_utils.fum", "params": {"k": 43}}, None, {}, 44,), + # Check builtins + ({"cls": "builtins.str", "params": {"object": 43}}, None, {}, "43",), + ], +) +def test_class_instantiate( + input_conf: Dict[str, Any], + key_to_get_config: Optional[str], + kwargs_to_pass: Dict[str, Any], + expected: Any, +) -> Any: + conf = OmegaConf.create(input_conf) + assert isinstance(conf, DictConfig) + if key_to_get_config is None: + config_to_pass = conf + else: + config_to_pass = OmegaConf.select(conf, key_to_get_config) + config_to_pass_copy = copy.deepcopy(config_to_pass) + obj = utils.instantiate(config_to_pass, **kwargs_to_pass) + assert obj == expected + # make sure config is not modified by instantiate + assert config_to_pass == config_to_pass_copy + + +def test_class_instantiate_pass_omegaconf_node() -> Any: + pc = ObjectConf() + # This is a bit clunky because it exposes a problem with the backport of dataclass on Python 3.6 + # see: https://github.com/ericvsmith/dataclasses/issues/155 + pc.cls = "tests.test_utils.Bar" + pc.params = {"b": 200, "c": {"x": 10, "y": "${params.b}"}} + conf = OmegaConf.structured(pc) + obj = utils.instantiate(conf, **{"a": 10, "d": Foo(99)}) + assert obj == Bar(10, 200, {"x": 10, "y": 200}, Foo(99)) + assert OmegaConf.is_config(obj.c) + + +def test_class_warning() -> None: + expected = Bar(10, 20, 30, 40) + with pytest.warns(UserWarning): + config = OmegaConf.structured( + { + "class": "tests.test_utils.Bar", + "params": {"a": 10, "b": 20, "c": 30, "d": 40}, + } + ) + assert utils.instantiate(config) == expected + + config = OmegaConf.structured( + {"cls": "tests.test_utils.Bar", "params": {"a": 10, "b": 20, "c": 30, "d": 40}} + ) + assert utils.instantiate(config) == expected + + +def test_get_original_cwd(hydra_restore_singletons: Any) -> None: + orig = "/foo/bar" + cfg = OmegaConf.create({"hydra": HydraConf(runtime=RuntimeConf(cwd=orig))}) + assert isinstance(cfg, DictConfig) + HydraConfig.instance().set_config(cfg) + assert utils.get_original_cwd() == orig + + +def test_get_original_cwd_without_hydra(hydra_restore_singletons: Any) -> None: + with pytest.raises(ValueError): + utils.get_original_cwd() + + +@pytest.mark.parametrize( # type: ignore + "orig_cwd, path, expected", + [ + ("/home/omry/hydra", "foo/bar", "/home/omry/hydra/foo/bar"), + ("/home/omry/hydra/", "foo/bar", "/home/omry/hydra/foo/bar"), + ("/home/omry/hydra/", "/foo/bar", "/foo/bar"), + ], +) +def test_to_absolute_path( + hydra_restore_singletons: Any, orig_cwd: str, path: str, expected: str +) -> None: + # normalize paths to current OS + orig_cwd = str(Path(orig_cwd)) + path = str(Path(path)) + expected = str(Path(expected)) + cfg = OmegaConf.create({"hydra": HydraConf(runtime=RuntimeConf(cwd=orig_cwd))}) + assert isinstance(cfg, DictConfig) + HydraConfig().set_config(cfg) + assert utils.to_absolute_path(path) == expected + + +@pytest.mark.parametrize( # type: ignore + "path, expected", + [ + ("foo/bar", f"{os.getcwd()}/foo/bar"), + ("foo/bar", f"{os.getcwd()}/foo/bar"), + ("/foo/bar", os.path.abspath("/foo/bar")), + ], +) +def test_to_absolute_path_without_hydra( + hydra_restore_singletons: Any, path: str, expected: str +) -> None: + # normalize paths to current OS + path = str(Path(path)) + expected = str(Path(expected).absolute()) + assert utils.to_absolute_path(path) == expected + + +@pytest.mark.parametrize( # type: ignore + "matrix,expected", + [ + ([["a"]], [1]), + ([["a", "bb"]], [1, 2]), + ([["a", "bb"], ["aa", "b"]], [2, 2]), + ([["a"], ["aa", "b"]], [2, 1]), + ([["a", "aa"], ["bb"]], [2, 2]), + ([["a"]], [1]), + ([["a"]], [1]), + ([["a"]], [1]), + ], +) +def test_get_column_widths(matrix: Any, expected: Any) -> None: + assert internal_utils.get_column_widths(matrix) == expected diff --git a/testbed/facebookresearch__hydra/website/.gitignore b/testbed/facebookresearch__hydra/website/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1d7ee021e89875c26ad73cee97406667d1ac93ae --- /dev/null +++ b/testbed/facebookresearch__hydra/website/.gitignore @@ -0,0 +1,20 @@ +# dependencies +/node_modules + +# production +/build + +# generated files +.docusaurus +.cache-loader + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/testbed/facebookresearch__hydra/website/.yarnclean b/testbed/facebookresearch__hydra/website/.yarnclean new file mode 100644 index 0000000000000000000000000000000000000000..b591611ea7ac935fc14ec90f4ffeffd1bf7058d8 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/.yarnclean @@ -0,0 +1,45 @@ +# test directories +__tests__ +test +tests +powered-test + +# asset directories +docs +doc +website +images +assets + +# examples +example +examples + +# code coverage directories +coverage +.nyc_output + +# build scripts +Makefile +Gulpfile.js +Gruntfile.js + +# configs +appveyor.yml +circle.yml +codeship-services.yml +codeship-steps.yml +wercker.yml +.tern-project +.gitattributes +.editorconfig +.*ignore +.eslintrc +.jshintrc +.flowconfig +.documentup.json +.yarn-metadata.json +.travis.yml + +# misc +*.md diff --git a/testbed/facebookresearch__hydra/website/README.md b/testbed/facebookresearch__hydra/website/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aff350dcc03cd415821eaa2422fa9fc979b0c7bd --- /dev/null +++ b/testbed/facebookresearch__hydra/website/README.md @@ -0,0 +1,34 @@ +# Website + +This website is built using Docusaurus 2, a modern static website generator. + +### Installation + +``` +$ yarn +``` + +### Local Development + +``` +$ yarn start +``` + +This command starts a local development server and open up a browser window. Most changes are reflected live without having to restart the server. + +### Build + +``` +$ yarn build +``` + +This command generates static content into the `build` directory and can be served using any static contents hosting service. + +### Deployment + +Done automatically once a website change is landed to master. + + +### Adding pages + +New pages, e.g., for a new plugin, should be added to `docs/`. They can be accessed on a local server via `http://localhost:3000/docs/next/page_name`. diff --git a/testbed/facebookresearch__hydra/website/blog/2020-05-04-New-blog.md b/testbed/facebookresearch__hydra/website/blog/2020-05-04-New-blog.md new file mode 100644 index 0000000000000000000000000000000000000000..5857d2ecde8eee051ee6b6b57d33c1bbdf642e92 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/blog/2020-05-04-New-blog.md @@ -0,0 +1,20 @@ +--- +title: New Hydra blog +author: Omry Yadan +author_title: Creator of Hydra +author_url: https://github.com/omry +author_image_url: http://graph.facebook.com/733244046/picture/?height=200&width=200 +tags: [Hydra] +--- +Welcome to the Hydra blog. + +Catching up on some previous content: + +##### Apr/8/2020 +[FLOSS Weekly interview](https://twit.tv/shows/floss-weekly/episodes/573) + +##### Feb/3/2020 +[PyTorch Medium channel blog post](http://bit.ly/2Sdq2B3) + +##### Oct/3/2019 +[Facebook engineering blog release post](https://engineering.fb.com/open-source/hydra/) diff --git a/testbed/facebookresearch__hydra/website/docs/advanced/command_line_overrides.md b/testbed/facebookresearch__hydra/website/docs/advanced/command_line_overrides.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac8a7ce3eb9d13b5a260d3ad0fb995cf970332b --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/advanced/command_line_overrides.md @@ -0,0 +1,56 @@ +--- +id: command_line_overrides +title: Command line overrides +--- +You can manipulate your configuration via the command line. This includes: +- Manipulation of the defaults list +- Manipulation of the resulting config object + +Both of those looks similar in the command line. +Command line overrides matching a Config group are manipulating the Defaults List; The rest are manipulating the resulting config object. + +```text title="Defaults List overrides" +PACKAGE : PATH[.PATH]* +PATH : [A-Za-z0-9_-]+ +OPTION : .* + +# Changing an existing item +GROUP[@SRC_PKG[:DEST_PKG]][=OPTION] + +# Appending a new item ++GROUP@[SRC_PKG]=OPTION + +# Deleting an existing item +~GROUP[@PACKAGE][=OPTION] +``` + +```text title="Config overrides" +KEY=VALUE +KEY : .+ +VALUE : .+ + +# Changing an existing item +KEY=VALUE + +# Appending a new item ++KEY=VALUE + +# Deleting an existing item +~KEY[=VALUE] +``` + +# Examples +## Config values +- Overriding a config value : `foo.bar=value` +- Appending a config value : `+foo.bar=value` +- Removing a config value : `~foo.bar`, `~foo.bar=value` + +## Defaults list +- Overriding selected Option: `db=mysql` +- Overriding selected Option and renaming package: `db@src_pkg:dst_pkg=mysql` +- Renaming package: `db@src_pkg:dst_pkg` +- Appending to defaults: `+experiment=exp1` +- Deleting from defaults: `~db`, `~db=mysql` + +When renaming a package, if the current item in the defaults list does not have a package, +use the empty string for the source package, e.g: `db@:dst_package`. \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/advanced/overriding_packages.md b/testbed/facebookresearch__hydra/website/docs/advanced/overriding_packages.md new file mode 100644 index 0000000000000000000000000000000000000000..2b740fda7a4b3a4dd44f2ac4dd6e74ccc7de24c3 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/advanced/overriding_packages.md @@ -0,0 +1,135 @@ +--- +id: overriding_packages +title: Overriding packages +--- + +The contents of a config file can be relocated, or replicated, within the config, via package overrides. + +### Package specification + +``` text title="Definition of a package" +PACKAGE : _global_ | COMPONENT[.COMPONENT]* +COMPONENT : _group_ | _name_ | \w+ + +_global_ : the top level package (equivalent to the empty string). +_group_ : the config group in dot notation: foo/bar/zoo.yaml -> foo.bar +_name_ : the config file name: foo/bar/zoo.yaml -> zoo +``` + +### Overriding the package in a file via a package directive + +A `@package directive` specifies a common [package](/terminology.md#package) for all nodes in the config file. +It must be placed at the top of each `config group file`. + +```text title="Package directive examples" +# @package foo.bar +# @package _global_ +# @package _group_ +# @package _group_._name_ +# @package foo._group_._name_ +``` +#### Examples +##### A package directive with a literal +
+
+ +```yaml title="mysql.yaml" {1-2} +# @package foo.bar + +db: + host: localhost + port: 3306 +``` + +
+ +
+ +```yaml title="Interpretation" {1-2} +foo: + bar: + db: + host: localhost + port: 3306 +``` + +
+
+ + +##### A package directive with `_group_` and `_name_` + +
+
+ +```yaml title="db/mysql.yaml" {1-2} +# @package _group_._name_ + +host: localhost +port: 3306 +``` +
+ +```yaml title="Interpretation" {1-2} +db: + mysql: + host: localhost + port: 3306 +``` +
+ +### Overriding the package via the defaults list +The following example adds the `mysql` config in under the packages `src` and `dst`. + + +
+
+ +```yaml title="config.yaml" +defaults: + - db@db.src: mysql + - db@db.dst: mysql + + + + +``` +
+ +```yaml title="Interpretation" +db: + src: + host: localhost + port: 3306 + dst: + host: localhost + port: 3306 +``` +
+ +### Overriding the package via the command line +Overriding the package for `db` specified in the defaults list from `db.dst` to `backup`: +```bash +$ python my_app.py db@db.dst:backup +$ python my_app.py db@db.dst:backup=postgresql # And change the config group option +``` + +Overriding the package of a config group option not in the defaults list: +```text +python my_app.py +webserver@prod=apache +``` + +For more details, see the [Command line overrides](advanced/command_line_overrides.md) page. + +### History and future of the package directive +The primary config, named in `@hydra.main()` should not have a package directive. + +For config files in config groups the default depends on the version: + - In **Hydra 0.11**, there was an implicit default of `_global_` + - **Hydra 1.0** the default is `_global_` + A warning is issued for each **config group file** without a `@package` directive. + - In **Hydra 1.1** the default for **config group files** will become `_group_` + +By adding an explicit `@package` to your configs files, you guarantee that they +will not break when you upgrade to Hydra 1.1. + diff --git a/testbed/facebookresearch__hydra/website/docs/advanced/packaging.md b/testbed/facebookresearch__hydra/website/docs/advanced/packaging.md new file mode 100644 index 0000000000000000000000000000000000000000..47195996d39884f1248dbb86ebd15c1d44e00e69 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/advanced/packaging.md @@ -0,0 +1,34 @@ +--- +id: app_packaging +title: Application packaging +sidebar_label: Application packaging +--- + +You can package your Hydra application along with its configuration. +There is a working example [here](https://github.com/facebookresearch/hydra/tree/master/examples/advanced/hydra_app_example). + +You can run it with: + +```yaml +$ python examples/advanced/hydra_app_example/hydra_app/main.py +dataset: + name: imagenet + path: /datasets/imagenet +``` + +To install it, use: +```text +$ pip install examples/advanced/hydra_app_example +... +Successfully installed hydra-app-0.1 +``` + +Run the installed app with: +```yaml +$ hydra_app +dataset: + name: imagenet + path: /datasets/imagenet +``` + +The installed app will use the packaged configuration files. diff --git a/testbed/facebookresearch__hydra/website/docs/advanced/search_path.md b/testbed/facebookresearch__hydra/website/docs/advanced/search_path.md new file mode 100644 index 0000000000000000000000000000000000000000..15847bb259cf27a995bad23d9d5dd54c9d1b3461 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/advanced/search_path.md @@ -0,0 +1,17 @@ +--- +id: search_path +title: Config Search Path +--- + +The Config Search Path is a list of paths that are searched in order to find configs. It is similar to +the Python PYTHONPATH. + + - When a config is requested, The first matching config in the search path is used. + - Each search path element has a schema prefix such as file:// or pkg:// that is corresponding to a ConfigSourcePlugin. + - `SearchPathPlugin` can manipulate the search path. + +You can inspect the search path and the configurations loaded by Hydra by turning on verbose logging for the `hydra` logger: + +```text +$ python my_app.py hydra.verbose=hydra +``` \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/configure_hydra/Intro.md b/testbed/facebookresearch__hydra/website/docs/configure_hydra/Intro.md new file mode 100644 index 0000000000000000000000000000000000000000..1246619476ca2225f57edd262a494e7dd9984a4e --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/configure_hydra/Intro.md @@ -0,0 +1,70 @@ +--- +id: intro +title: Overview +sidebar_label: Introduction +--- + +Many things in Hydra can be customized. This includes: +* Launcher configurations +* Sweeper configuration +* Logging configuration +* Run and Multirun output directory patterns +* Application help (--help and --hydra-help) + +Hydra can be customized using the same methods you are already familiar with from the tutorial. +You can include some Hydra config snippet in your own config to override it directly, or compose in different +configurations provided by plugins or by your own code. You can also override everything in Hydra from the command +line just like with your own configuration. + +The Hydra configuration actually lives in the same config object as your configuration, but is removed prior to running +your function to reduce confusion. +You can view the configuration with `--cfg hydra|job|all` + +The Hydra configuration itself is composed from multiple config files. here is a partial list: +```yaml +defaults: + - hydra/job_logging : default # Job's logging config + - hydra/launcher: basic # Launcher config + - hydra/sweeper: basic # Sweeper config + - hydra/output: default # Output directory +``` +You can view the Hydra config structure [here](https://github.com/facebookresearch/hydra/tree/master/hydra/conf). + +This is a subset of the composed Hydra configuration node: + +```yaml +hydra: + run: + # Output directory for normal runs + dir: ./outputs/${now:%Y-%m-%d_%H-%M-%S} + sweep: + # Output directory for sweep runs + dir: /checkpoint/${env:USER}/outputs/${now:%Y-%m-%d_%H-%M-%S} + # Output sub directory for sweep runs. + subdir: ${hydra.job.num}_${hydra.job.id} +``` + +## Runtime variables +The `hydra` package is deleted from your config when the function runs to reduce the amount of noise +in the config passed to the function. +You can still access all config nodes in Hydra through the custom resolver `hydra`. + +For example: +```yaml +config_name: ${hydra:job.config_name} +``` +Pay close attention to the syntax: The resolver name is `hydra`, and the `key` is passed after the colon. + +The following variables are some of the variables populated at runtime. +You can see the full Hydra config using `--cfg hydra`: + +`hydra.job`: +- *hydra.job.name* : Job name, defaults to python file name without suffix. can be overridden. +- *hydra.job.override_dirname* : Pathname derived from the overrides for this job +- *hydra.job.num* : job serial number in sweep +- *hydra.job.id* : Job ID in the underlying jobs system (SLURM etc) + +`hydra.runtime`: +- *hydra.runtime.version*: Hydra's version +- *hydra.runtime.cwd*: Original working directory the app was executed from + diff --git a/testbed/facebookresearch__hydra/website/docs/configure_hydra/job.md b/testbed/facebookresearch__hydra/website/docs/configure_hydra/job.md new file mode 100644 index 0000000000000000000000000000000000000000..e7097d9ed5771f585718d15f149f544cc03d1168 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/configure_hydra/job.md @@ -0,0 +1,138 @@ +--- +id: job +title: Job configuration +--- + +The job configuration resides in `hydra.job`. +The structure definition is below, you can fine the latest definition [in the code](https://github.com/facebookresearch/hydra/blob/master/hydra/conf/__init__.py). +## Definition +```python +# job runtime information will be populated here +@dataclass +class JobConf: + # Job name, populated automatically unless specified by the user (in config or cli) + name: str = MISSING + + # Concatenation of job overrides that can be used as a part + # of the directory name. + # This can be configured in hydra.job.config.override_dirname + override_dirname: str = MISSING + + # Job ID in underlying scheduling system + id: str = MISSING + + # Job number if job is a part of a sweep + num: int = MISSING + + # The config name used by the job + config_name: Optional[str] = MISSING + + # Environment variables to set remotely + env_set: Dict[str, str] = field(default_factory=dict) + # Environment variables to copy from the launching machine + env_copy: List[str] = field(default_factory=list) + + # Job config + @dataclass + class JobConfig: + @dataclass + # configuration for the ${hydra.job.override_dirname} runtime variable + class OverrideDirname: + kv_sep: str = "=" + item_sep: str = "," + exclude_keys: List[str] = field(default_factory=list) + + override_dirname: OverrideDirname = OverrideDirname() + + config: JobConfig = JobConfig() +``` + +## Documentation +### hydra.job.name +The job name is used by different things in Hydra, such as the log file name (`${hydra.job.name}.log`). +It is automatically set with Python file name (file: `train.py` -> name: `train`), but you can override +it you specify it via the command line or your config file. + +### hydra.job.override_dirname +This field is populated automatically using your command line arguments and is typically being used as a part of your +output directory pattern. +For example, the command line arguments: +```bash +$ python foo.py a=10 b=20 +``` +Would result in `hydra.job.override_dirname` getting the value a=10,b=20. +When used with the output directory override, it can automatically generate directories that represent the +command line arguments used in your run. +```yaml +hydra: + run: + dir: output/${hydra.job.override_dirname} +``` + +The generation of override_dirname can be controlled by `hydra.job.config.override_dirname`. +In particular, the separator char `=` and the item separator char `,` can be modified, and in addition some command line +override keys can be automatically excluded from the generated `override_dirname`. +An example of a case where the exclude is useful is a random seed. + +```yaml +hydra: + run: + dir: output/${hydra.job.override_dirname}/seed=${seed} + job: + config: + override_dirname: + exclude_keys: + - seed +``` +With this configuration, running +```bash +$ python foo.py a=10 b=20 seed=999 +``` + +Would result in a directory like: +``` +output/a=10,b=20/seed=999 +``` +Allowing you to more easily group identical runs with different random seeds together. + +### hydra.job.id +The job ID is populated by active Hydra launcher. For the basic launcher, the job ID is just a serial job number, but +for other systems this could be the SLURM job ID or the AWS Instance ID. + +### hydra.job.num +Serial job number within this current sweep run. (0 to n-1) + +### hydra.job.config_name +The config name used by the job, this is populated automatically to match the config name in @hydra.main() + +### hydra.job.env_set +A Dict[str, str] that is used to set the environment variables of the running job. +Some common use cases are to set environment variables that are effecting underlying libraries, for example +```yaml +hydra: + job: + env_set: + OMP_NUM_THREADS: 1 +``` +Disables multithreading in Intel IPP and MKL. + +Another example, is to use interpolation to automatically set the rank +for [Torch Distributed](https://pytorch.org/tutorials/intermediate/dist_tuto.html) run to match the job number +in the sweep. + +```yaml +hydra: + job: + env_set: + RANK: ${hydra.job.num} +``` + +### hydra.job.env_copy +In some cases you want to automatically copy local environment variables to the running job environment variables. +This is particularly useful for remote runs. +```yaml +hydra: + job: + env_copy: + - AWS_KEY +``` diff --git a/testbed/facebookresearch__hydra/website/docs/configure_hydra/logging.md b/testbed/facebookresearch__hydra/website/docs/configure_hydra/logging.md new file mode 100644 index 0000000000000000000000000000000000000000..c23c35ea8350b977e62b34209b3bb164deb0d9f5 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/configure_hydra/logging.md @@ -0,0 +1,36 @@ +--- +id: logging +title: Customizing logging +sidebar_label: Customizing logging +--- +Hydra is configuring Python standard logging library with the dictConfig method. You can learn more about it [here](https://docs.python.org/3/howto/logging.html). +There are two logging configurations, one for Hydra itself and one for the executed jobs. + +This example demonstrates how to customize the logging behavior of your Hydra app, by making the following changes +to the default logging behavior: + + * Outputs only to stdout (no log file) + * Output a simpler log line pattern + +`config.yaml`: +```yaml +hydra: + job_logging: + formatters: + simple: + format: '[%(levelname)s] - %(message)s' + root: + handlers: [console] +``` + +This is what the the default logging looks like: +```text +$ python main.py +[2019-09-26 18:58:05,477][__main__][INFO] - Info level message +``` + +And this simplified logging looks like: +```bash +$ python main.py +[INFO] - Info level message +``` diff --git a/testbed/facebookresearch__hydra/website/docs/configure_hydra/workdir.md b/testbed/facebookresearch__hydra/website/docs/configure_hydra/workdir.md new file mode 100644 index 0000000000000000000000000000000000000000..8459ff212aded252c71d997ded0a2fcc8a977245 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/configure_hydra/workdir.md @@ -0,0 +1,46 @@ +--- +id: workdir +title: Customizing working directory pattern +sidebar_label: Customizing working directory pattern +--- +Below are a few examples of customizing output directory patterns. + +Run output directory grouped by day: +```yaml +hydra: + run: + dir: ./outputs/${now:%Y-%m-%d}/${now:%H-%M-%S} +``` + +Sweep sub directory contains the the job number and the override parameters for the job instance: +```yaml +hydra: + sweep: + subdir: ${hydra.job.num}_${hydra.job.num}_${hydra.job.override_dirname} +``` + +Run output directory grouped by job name: +```yaml +hydra: + run: + dir: outputs/${hydra.job.name}/${now:%Y-%m-%d_%H-%M-%S} +``` + +Run output directory can contain user configuration variables: +```yaml +hydra: + run: + dir: outputs/${now:%Y-%m-%d_%H-%M-%S}/opt:${optimizer.type} + +``` + +Run output directory can contain override parameters for the job: + +See [Override dirname](./job#hydrajoboverride_dirname) in the Job configuration page for details on how to customize +`hydra.job.override_dirname`. + +```yaml +hydra: + run: + dir: output/${hydra.job.override_dirname} +``` diff --git a/testbed/facebookresearch__hydra/website/docs/development/contributing.md b/testbed/facebookresearch__hydra/website/docs/development/contributing.md new file mode 100644 index 0000000000000000000000000000000000000000..bb4ba1fe0c941dd42fbd4e393f6805cb15b67f60 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/development/contributing.md @@ -0,0 +1,116 @@ +--- +id: contributing +title: Contributing +sidebar_label: Contributing +--- + +This guide assumes you have forked and checked-out the repository. +It is recommended that you install Hydra in a virtual environment like conda or virtualenv. + +### Environment setup +Install [Miniconda](https://docs.conda.io/en/latest/miniconda.html) and create an empty Conda environment with: +``` +conda create -n hydra38 python=3.8 -y +``` + + +
+ +Activate the environment: +``` +conda activate hydra38 +``` +From the source tree, install Hydra in development mode with the following command: +``` +pip install -r requirements/dev.txt -e . +``` +## Nox +Hydra is using a test automation tool called [nox](https://github.com/theacodes/nox) to manage tests, linting, code coverage etc. +`nox` will run all the configured sessions. You can see the full list of nox sessions with `nox -l` and run specific sessions +with `nox -s NAME` (you may need to quote the session name in some cases) + +## Code style guide +The code need to pass verification by the following tools: + - `black .` : Automatic code formatting for Python + - `flake8` : PEP8 compliance checker for Python, this includes copyright header verification + - `isort .` : Ensure imports are sorted properly + - `mypy --strict .` : Ensures code passes strict type checking + - `yamllint .` : Ensures that yaml files are syntactically correct and properly indented. + +The easiest way to run the required verifications is: + - `nox -s lint` : for the Hydra core + - `nox -s lint_plugins` : for the included plugins + +isort is a bit tricky to run for plugins. the best way to get it to sort the plugins imports is with the FIX environment +variable: +``` +$ FIX=1 nox -s lint_plugins +``` + +It is also recommended that you install pre-commit hooks (use `pre-commit install`). +pre-commit will execute some of the above tets when you commit your code locally. +You can disable it by appending `-n` to your commit command: `git commit -am wip -n` + +Pull requests that does not lint will fail the automated testing. + +## Testing +### With pytest +Use `pytest` at the repository root to run all the Hydra core tests. +To run the tests of individual plugins, use `pytest plugins/NAME`. + + +### With nox +See `nox -l`. a few examples: +* `nox -s test_core` will test Hydra core on all supported Python versions +* `nox -s "test_core-3.6(pip install)"` : Test on Python 3.6 with `pip install` as installation method +* `nox -s "test_plugins-3.8(pip install -e)"` : Test plugins on Python 3.8 with `pip install -e` as installation method + +## NEWS Entries +The `NEWS.rst` file is managed using `towncrier` and all non trivial changes +must be accompanied by a news entry. + +To add an entry to the news file, first you need to have created an issue +describing the change you want to make. A Pull Request itself *may* function as +such, but it is preferred to have a dedicated issue (for example, in case the +PR ends up rejected due to code quality reasons). + +Once you have an issue or pull request, you take the number and you create a +file inside of the ``news/`` directory named after that issue number with one of the following extensions: +* `api_change` : API Change (Renames, deprecations and removals) +* `feature` : Addition of a new feature +* `bugfix` : Fixing of a bug +* `docs` : Addition or updates to documentation +* `plugin` : Addition of changes to a plugin +* `config` : Changes or addition to the configuration structure +* `maintenance` : Changes that improve maintainability of the code + +If your issue or PR number is ``1234`` and this change is fixing a bug, then you would +create a file ``news/1234.bugfix``. PRs can span multiple categories by creating +multiple files (for instance, if you added a feature and deprecated/removed the +old feature at the same time, you would create ``news/NNNN.feature`` and +``news/NNNN.api_change``). Likewise if a PR touches multiple issues/PRs you may +create a file for each of them with the exact same contents and Towncrier will +deduplicate them. + + +### Contents of a NEWS entry +The contents of this file is markdown formatted text that will be used +as the content of the news file entry. You do not need to reference the issue +or PR numbers here as towncrier will automatically add a reference to all of +the affected issues when rendering the news file. + +In order to maintain a consistent style in the `NEWS.md` file, it is +preferred to keep the news entry to the point, in sentence case, shorter than +80 characters and in an imperative tone -- an entry should complete the sentence +"This change will ...". In rare cases, where one line is not enough, use a +summary line in an imperative tone followed by a blank line separating it +from a description of the feature/change in one or more paragraphs, each wrapped +at 80 characters. Remember that a news entry is meant for end users and should +only contain details relevant to an end user. diff --git a/testbed/facebookresearch__hydra/website/docs/development/release.md b/testbed/facebookresearch__hydra/website/docs/development/release.md new file mode 100644 index 0000000000000000000000000000000000000000..81e2cdd0ded8aab7b8de9f8760f1a37b754312c4 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/development/release.md @@ -0,0 +1,14 @@ +--- +id: release +title: Release process +sidebar_label: Release process +--- + +The release process may be automated in the future. + +- Checkout master +- Update the Hydra version in `hydra/__init__.py` +- Update NEWS.md with towncrier +- Create a pip package for hydra-core: `python setup.py sdist bdist_wheel` +- Upload pip package: `python -m twine upload dist/*` + diff --git a/testbed/facebookresearch__hydra/website/docs/experimental/hydra_compose.md b/testbed/facebookresearch__hydra/website/docs/experimental/hydra_compose.md new file mode 100644 index 0000000000000000000000000000000000000000..f03e5fa6610153135db77b84edfe164ef4390d9d --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/experimental/hydra_compose.md @@ -0,0 +1,73 @@ +--- +id: compose_api +title: Compose API +sidebar_label: Compose API +--- + +The compose API can compose a configuration similar to `@hydra.main()` anywhere in the code. +Prior to calling compose(), you have to initialize Hydra: This can be done by using the standard `@hydra.main()` +or by calling one of the initialization methods listed below. + +Compose is useful when `@hydra.main()` is not applicable. +### Examples + - [Jupyter notebook with compose](https://github.com/facebookresearch/hydra/tree/master/examples/notebook) (hydra_notebook_example.ipynb) + - [Unit testing with compose](https://github.com/facebookresearch/hydra/tree/master/examples/advanced/hydra_app_example/tests/test_hydra_app.py). + +### Code example +```python +from hydra.experimental import compose, initialize + + +if __name__ == "__main__": + initialize(config_path="conf") + + cfg = compose(config_name="config", overrides=["db=mysql", "db.user=me"]) + print(cfg.pretty()) +``` +### API Documentation +```python +def compose(config_file=None, overrides=[]): + """ + :param config_file: optional config file to load + :param overrides: list of overrides for config file + :return: the composed config + """ + ... + +def initialize( + config_path: Optional[str] = None, + strict: Optional[bool] = None, + caller_stack_depth: int = 1, +) -> None: + """ + Initialize automatically detect the calling file or module. + config_path is relative to the detected calling for or module. + + :param config_path: A directory relative to the declaring python file or module + :param strict: (Deprecated), will be removed in the next major version + :param caller_stack_depth: stack depth of module the config_path is relative to + """ + +def initialize_with_file( + file: Optional[str], config_path: Optional[str] = None +) -> None: + """ + Initialize Hydra and add the config_path to the search path. + The config path is relative to the calling_file. + :param file : The file to make the config_path relative to + :param config_path : The config path + """ + ... + +def initialize_with_module( + module: Optional[str], config_path: Optional[str] = None +) -> None: + """ + Initialize Hydra and add the config_path to the search path. + The config path is relative to the calling_module. + :param module : The module to make the config_path relative to + :param config_path : The config path + """ + ... +``` + diff --git a/testbed/facebookresearch__hydra/website/docs/experimental/intro.md b/testbed/facebookresearch__hydra/website/docs/experimental/intro.md new file mode 100644 index 0000000000000000000000000000000000000000..1f04a33cdd24a192708e2f06d5ad174c69d52e29 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/experimental/intro.md @@ -0,0 +1,11 @@ +--- +id: intro +title: Introduction +sidebar_label: Introduction +--- +## Introduction +Experimental features are new features in Hydra that are considered experimental because their API may have not yet +stabilized. + +Those features should all work, but code relying on them may break in future versions as they evolve. +Experiemntal features are expected be promoted out of experimental once they deemed stable and complete enough. diff --git a/testbed/facebookresearch__hydra/website/docs/experimental/ray_example.md b/testbed/facebookresearch__hydra/website/docs/experimental/ray_example.md new file mode 100644 index 0000000000000000000000000000000000000000..1bab6f944cb11560a1a1b98289b54c60a3c1b322 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/experimental/ray_example.md @@ -0,0 +1,81 @@ +--- +id: ray_example +title: Ray example +sidebar_label: Ray example +--- + +[Ray](https://github.com/ray-project/ray) is a framework for building and running distributed applications. +Hydra can be used with Ray to configure Ray itself as well as complex remote calls through the compose API. +A future plugin will enable launching to Ray clusters directly from the command line. + +```python +import hydra +from hydra.experimental import compose +import ray +import time + + +@ray.remote +def train(overrides, cfg): + print(cfg.pretty()) + time.sleep(5) + return overrides, 0.9 + + +@hydra.main(config_path="conf", config_name="config") +def main(cfg): + ray.init(**cfg.ray.init) + + results = [] + for model in ["alexnet", "resnet"]: + for dataset in ["cifar10", "imagenet"]: + overrides = [f"dataset={dataset}", f"model={model}"] + run_cfg = compose(overrides=overrides) + ret = train.remote(overrides, run_cfg) + results.append(ret) + + for overrides, score in ray.get(results): + print(f"Result from {overrides} : {score}") + + +if __name__ == "__main__": + main() +``` + +Output: +```yaml +(pid=11571) dataset: +(pid=11571) name: cifar10 +(pid=11571) path: /datasets/cifar10 +(pid=11571) model: +(pid=11571) num_layers: 7 +(pid=11571) type: alexnet +(pid=11571) +(pid=11572) dataset: +(pid=11572) name: imagenet +(pid=11572) path: /datasets/imagenet +(pid=11572) model: +(pid=11572) num_layers: 7 +(pid=11572) type: alexnet +(pid=11572) +(pid=11573) dataset: +(pid=11573) name: cifar10 +(pid=11573) path: /datasets/cifar10 +(pid=11573) model: +(pid=11573) num_layers: 50 +(pid=11573) type: resnet +(pid=11573) width: 10 +(pid=11573) +(pid=11574) dataset: +(pid=11574) name: imagenet +(pid=11574) path: /datasets/imagenet +(pid=11574) model: +(pid=11574) num_layers: 50 +(pid=11574) type: resnet +(pid=11574) width: 10 +(pid=11574) +Result from ['dataset=cifar10', 'model=alexnet'] : 0.9 +Result from ['dataset=imagenet', 'model=alexnet'] : 0.9 +Result from ['dataset=cifar10', 'model=resnet'] : 0.9 +Result from ['dataset=imagenet', 'model=resnet'] : 0.9 +``` \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/fb/ai-cluster.md b/testbed/facebookresearch__hydra/website/docs/fb/ai-cluster.md new file mode 100644 index 0000000000000000000000000000000000000000..a471d949d5b2c8cea6fdf4bff07fb6b1908a62af --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/fb/ai-cluster.md @@ -0,0 +1,23 @@ +--- +id: internal-fb-cluster +title: Hydra on the internet FB Cluster +--- + +Support for launching jobs to the AI cluster is currently still experimental and is expected to evolve over +the coming months. + +## flow-cli + +flow-cli integration is hacky at the moment. +See the the sample f6.sample_projects.classy_hydra_project.workflow.main for details. + +```bash title="Example run" +$ CFG='{"config": {"overrides": ["trainer=multi_gpu","trainer.max_epochs=90","+lr_scheduler=multi_step"]}}' +$ ENTITLEMENT=cv_images_gpu_prod +$ TEAM=team_computer_vision +$ WORKFLOW=f6.sample_projects.classy_hydra_project.workflow.main +$ flow-cli canary $WORKFLOW --run-as-secure-group $TEAM --parameters-json=$CFG --entitlement $ENTITLEMENT +``` + +## fry +TODO diff --git a/testbed/facebookresearch__hydra/website/docs/fb/fair-cluster.md b/testbed/facebookresearch__hydra/website/docs/fb/fair-cluster.md new file mode 100644 index 0000000000000000000000000000000000000000..a330761f23da770dd4aad17e6d9131836d27e048 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/fb/fair-cluster.md @@ -0,0 +1,6 @@ +--- +id: fair-cluster +title: Hydra on the FAIR cluster +--- + +Hydra 1.0 is not yet ported to the FAIR cluster diff --git a/testbed/facebookresearch__hydra/website/docs/fb/fbcode.md b/testbed/facebookresearch__hydra/website/docs/fb/fbcode.md new file mode 100644 index 0000000000000000000000000000000000000000..54aa84e715576abc6ea906605c65de5f722e2e45 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/fb/fbcode.md @@ -0,0 +1,29 @@ +--- +id: fbcode +title: Hydra at fbcode +--- + +## Differences in fbcode + +### Open source plugins +#### Supported: + - hydra_ax_sweeper + - hydra_colorlog + - hydra_nevergrad_sweeper + +#### Unsupported: + - joblib launcher: Joblib's Loki backend does not work correctly when executed from a par file. + +### Facebook specified plugins + - fbcode_defaults : Changes configuration defaults to be appropriate for fbcode (e.g: Output directories are in `fbcode/outputs` and `fbcode/multirun`) + +#### TARGETS +Hydra includes buck TARGETS you can use in fbcode. In general, if there is TARGET there are two options: +1. You can depend on the TARGETS to use Hydra or a plugin. +2. The TARGETS contains a runnable example. + +targets are under `github/facebookresearch/hydra_1.0`: +- `:hydra` : Primary target to use in most cases. Includes `hydra_oss` and the `fbcode_defaults`. +- `:hydra_oss` : Vanilla Hydra without any Facebook specific targets. +- `plugins/...`: Plugins that has TARGETS file are runnable in fbcode. +- `examples/...`: Examples that has a TARGETS file are runnable in `fbcode`. diff --git a/testbed/facebookresearch__hydra/website/docs/fb/intro.md b/testbed/facebookresearch__hydra/website/docs/fb/intro.md new file mode 100644 index 0000000000000000000000000000000000000000..e72afde153f9842565f56ac933b5cff5ee7a1757 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/fb/intro.md @@ -0,0 +1,28 @@ +--- +id: intro +title: Hydra at Facebook +--- + +### Intro +Facebook has multiple different environments, such as the **Internal FB Cluster**, the **FAIR Cluster** etc. + +The FB specific docs are describing the differences. + +### Release strategy +Hydra's source of truth is the [GitHub repo](https://github.com/facebookresearch/hydra). + +Hydra is developed using release branches. Once a new major is released, it is maintained in patch only mode. +Primary development is happening on the `master` branch. + +When a new major version of Hydra is released, a new release branch is created in Hydra repo. A corresponding Hydra version will be created inside `github/facebookresearch/hydra_VERSION` to track +the release branch. + +Hydra is trying hard to remain backward compatible between two subsequent versions and in most cases the upgrade will be smooth. +There could be some new deprecations warnings that should be fixed before the next major version. + +### Maintaining this documentation +This documentation lives in in the Hydra repo which is publicly accessible. The pages will only normally render on the internal +copy of the docs, but keep in mind that everyone can read those docs in the repo if they want to. + +1. Do not put anything sensitive here, no root passwords or launch codes. +2. If you are in need to have sensitive Hydra related documentation please reach out to the maintainers of Hydra for help. diff --git a/testbed/facebookresearch__hydra/website/docs/index.html b/testbed/facebookresearch__hydra/website/docs/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a0ed6ecad0cf84960381652505820596bf9f07a6 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/index.html @@ -0,0 +1,14 @@ + + + + + + + Hydra - Docs + + + If you are not redirected automatically, follow this link. + + diff --git a/testbed/facebookresearch__hydra/website/docs/intro.md b/testbed/facebookresearch__hydra/website/docs/intro.md new file mode 100644 index 0000000000000000000000000000000000000000..7e50381e15a86f037ce530e9dd4e4d544a49b70d --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/intro.md @@ -0,0 +1,159 @@ +--- +id: intro +title: Getting started +sidebar_label: Getting started +--- +## Introduction +Hydra is an open-source Python framework that simplifies the development of research and other 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 name Hydra comes from its ability to run multiple similar jobs - much like a Hydra with multiple heads. + +### Key features: + +* Hierarchical configuration composable from multiple sources +* Configuration can be specified or overridden from the command line +* Dynamic command line tab completion +* Run your application locally or launch it to run remotely +* Run multiple jobs with different arguments with a single command + +## Versions +Hydra supports Linux, Mac and Windows. + +| | Version | Docs | Release notes | Python Version | +| -------|---------------------------|------------------------------- | ------------------------------------------------------------------------------------- | ---------------- | +| | 0.11 (Stable) | [0.11 Docs](../intro) | [Release notes](https://github.com/facebookresearch/hydra/releases/tag/0.11.0) | 2.7, 3.5+ | +| ►| 1.0 (Release candidate) | 1.0 docs | [Release notes](https://github.com/facebookresearch/hydra/releases/tag/hydra-1.0.0rc1) | **3.6+** | + + +## Quick start guide +This guide will show you some of the most important features of Hydra. +Read the [tutorial](tutorials/basic/your_first_app/1_simple_cli.md) to gain a deeper understanding. + +### Installation +Install Hydra 1.0 with `pip install hydra-core --pre --upgrade`. +This version may contain nuts and bugs and might be incompatible with existing plugins. + +### Basic example +Config: +```yaml title="config.yaml" +db: + driver: mysql + user: omry + pass: secret +``` +Application: +```python {4-6} title="my_app.py" +import hydra +from omegaconf import DictConfig + +@hydra.main(config_name="config") +def my_app(cfg : DictConfig) -> None: + print(cfg.pretty()) + +if __name__ == "__main__": + my_app() +``` +You can learn more about OmegaConf [here](https://omegaconf.readthedocs.io/en/latest/usage.html#access-and-manipulation) later. + +`config.yaml` is loaded automatically when you run your application +```yaml +$ python my_app.py +db: + driver: mysql + pass: secret + user: omry +``` + +You can override values in the loaded config from the command line: +```yaml {4-5} +$ python my_app.py db.user=root db.pass=1234 +db: + driver: mysql + user: root + pass: 1234 +``` + +### Composition example +You may want to alternate between two different databases. to support this create a `config group` named db, +and place one config file for each alternative inside: +The directory structure of our application now looks like: +```text +├── db +│ ├── mysql.yaml +│ └── postgresql.yaml +├── config.yaml +└── my_app.py +``` + +Here is the new config: +```yaml title="config.yaml" +defaults: + - db: mysql +``` + +`defaults` is a special directive telling Hydra to use db/mysql.yaml when composing the configuration object. +The resulting cfg object is a composition of configs from defaults with configs specified in your `config.yaml`. + +You can now choose which database configuration to use from the and override values from the command line: +```yaml +$ python my_app.py db=postgresql db.timeout=20 +db: + driver: postgresql + pass: drowssap + timeout: 20 + user: postgre_user +website: + domain: example.com +``` +You can have as many config groups as you need. + +### Multirun +You can run your function multiple times with different configuration easily with the `--multirun|-m` flag. + + +``` +$ python my_app.py --multirun db=mysql,postgresql +[HYDRA] Sweep output dir : multirun/2020-01-09/01-16-29 +[HYDRA] Launching 2 jobs locally +[HYDRA] #0 : db=mysql +db: + driver: mysql + pass: secret + user: omry +website: + domain: example.com + +[HYDRA] #1 : db=postgresql +db: + driver: postgresql + pass: drowssap + timeout: 10 + user: postgre_user +website: + domain: example.com +``` + +There is a whole lot more to Hydra. Read the [tutorial](tutorials/basic/your_first_app/1_simple_cli.md) to learn more. + +## Other stuff +### Community +Ask questions in the chat or StackOverflow (Use the tag #fb-hydra): +* [Zulip Chat](https://hydra-framework.zulipchat.com) +* [StackOverflow](https://stackoverflow.com/questions/tagged/fb-hydra) + +Follow Hydra on Twitter and Facebook: +* [Facebook page](https://www.facebook.com/Hydra-Framework-109364473802509/) +* [Twitter](https://twitter.com/Hydra_Framework) + + +### Citing Hydra +If you use Hydra in your research please use the following BibTeX entry: +```text +@Misc{, + author = {Omry Yadan}, + title = {A framework for elegantly configuring complex applications}, + howpublished = {Github}, + year = {2019}, + url = {https://github.com/facebookresearch/hydra} +} +``` diff --git a/testbed/facebookresearch__hydra/website/docs/patterns/objects.md b/testbed/facebookresearch__hydra/website/docs/patterns/objects.md new file mode 100644 index 0000000000000000000000000000000000000000..cbb0441ecf8405a95a66f77310ce01149dded9a5 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/patterns/objects.md @@ -0,0 +1,187 @@ +--- +id: objects +title: Creating objects and calling functions +sidebar_label: Creating objects and calling functions +--- +### Instantiating objects and calling methods and functions +Use `hydra.utils.call()` (or its alias `hydra.utils.instantiate()`) to instantiate objects, call functions and call class methods. While `instantiate` is an alias for `call`, you may prefer to use `call` for invoking functions and class methods, and `instantiate` for creating objects. + +```python +def call(config: Union[ObjectConf, DictConfig], *args: Any, **kwargs: Any) -> Any: + """ + :param config: An ObjectConf or DictConfig describing what to call and what params to use + :param args: optional positional parameters pass-through + :param kwargs: optional named parameters pass-through + :return: the return value from the specified class or method + """ +``` + +### ObjectConf definition +ObjectConf is defined in `hydra.types.ObjectConf`: +```python +@dataclass +class ObjectConf(Dict[str, Any]): + # class, class method or function name + cls: str = MISSING + # parameters to pass to cls when calling it + params: Any = field(default_factory=dict) +``` + +### Example config node +```yaml +# target class name, function name or class method fully qualified name +cls: foo.Bar +# optional parameters dictionary to pass when calling the target +params: + x: 10 +``` + + +#### Example usage + +models.py +```python +class Foo: + def __init__(x: int, y: int) -> None: + self.x = x + self.y = y + + @classmethod + def class_method(self, z: int) -> Any: + return self(z, 10) + + @staticmethod + def static_method(z: int) -> int: + return z + 1 + +def bar(z: int) -> int: + return z + 2 +``` +config.yaml +```yaml +myobject: + cls: models.Foo + params: + x: 10 + y: 20 + +myclassmethod: + cls: models.Foo.class_method + params: + z: 5 + +mystaticmethod: + cls: models.Foo.static_method + params: + z: 15 + +myfunction: + cls: models.bar + params: + z: 15 +``` + +Now to test these instantiate / call them as follows: +```python +import hydra + +@hydra.main(config_path="config.yaml") +def app(cfg): + foo1: Foo = hydra.utils.call(cfg.myobject) # Foo(10, 20) + foo2: Foo = hydra.utils.call(cfg.myclassmethod) # Foo(5, 10) + ret1: int = hydra.utils.call(cfg.mystaticmethod) # 16 + ret2: int = hydra.utils.call(cfg.myfunction) # 17 +``` +### Real World Example +One of the best ways to drive different behavior in the application is to instantiate different implementations of an interface. +The code using the instantiated object only knows the interface which remains constant, but the behavior +is determined by the actual object instance. + +A Database connection interface may have a `connect()` method, implemented by different database drivers. + +```python +class DBConnection: + def connect(self): + pass + +class MySQLConnection(DBConnection): + def __init__(self, host, user, password): + self.host = host + self.user = user + self.password = password + + def connect(self): + print( + "MySQL connecting to {} with user={} and password={}".format( + self.host, self.user, self.password + ) + ) + +class PostgreSQLConnection(DBConnection): + def __init__(self, host, user, password, database): + self.host = host + self.user = user + self.password = password + self.database = database + + def connect(self): + print( + "PostgreSQL connecting to {} " + "with user={} and password={} and database={}".format( + self.host, self.user, self.password, self.database + ) + ) +``` + +To support this, we can have a parallel config structure: +```text +conf/ +├── config.yaml +└── db + ├── mysql.yaml + └── postgresql.yaml +``` + +Config file: `config.yaml` +```yaml +defaults: + - db: mysql +``` +Config file: `db/mysql.yaml` +```yaml +db: + cls: tutorial.objects_example.objects.MySQLConnection + params: + host: localhost + user: root + password: 1234 +``` +db/postgresql.yaml: +```yaml +db: + cls: tutorial.objects_example.objects.PostgreSQLConnection + params: + host: localhost + user: root + password: 1234 + database: tutorial +``` + +With this, you can instantiate the object from the configuration with a single line of code: +```python +@hydra.main(config_path="conf", config_name="config") +def my_app(cfg): + connection = hydra.utils.instantiate(cfg.db) + connection.connect() +``` + +MySQL is the default per the `config.yaml` file: +```text +$ python my_app.py +MySQL connecting to localhost with user=root and password=1234 +``` +Change the instantiated object class and override values from the command line: +```text +$ python my_app.py db=postgresql db.params.password=abcde +PostgreSQL connecting to localhost with user=root and password=abcde and database=tutorial +``` diff --git a/testbed/facebookresearch__hydra/website/docs/patterns/specializing_config.md b/testbed/facebookresearch__hydra/website/docs/patterns/specializing_config.md new file mode 100644 index 0000000000000000000000000000000000000000..9705358a4c81c2110bfc7f19719df995ecc06651 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/patterns/specializing_config.md @@ -0,0 +1,75 @@ +--- +id: specializing_config +title: Specializing configuration +sidebar_label: Specializing configuration +--- +In some cases the desired configuration should depend on other configuration choices. +For example, You may want to use only 5 layers in your Alexnet model if the dataset of choice is cifar10, and the dafault 7 otherwise. + +We can start with a config that looks like this: +### initial config.yaml +```yaml +defaults: + - dataset: imagenet + - model: alexnet +``` + +We want to specialize the config based on the choice of the selected dataset and model: +Furthermore, we only want to do it for cifar10 and alexnet and not for 3 other combinations. + +OmegaConf supports value interpolation, we can construct a value that would - at runtime - be a function of other values. +The idea is that we can add another element to the defaults list that would load a file name that depends on those two values: +### modified config.yaml +```yaml +defaults: + - dataset: imagenet + - model: alexnet + - dataset_model: ${defaults.0.dataset}_${defaults.1.model} + optional: true +``` + +Let's break this down: +#### dataset_model +The key `dataset_model` is an arbitrary directory, it can be anything unique that makes sense, including nested directory like `dataset/model`. + +#### ${defaults.0.dataset}_${defaults.1.model} +the value `${defaults.0.dataset}_${defaults.1.model}` is using OmegaConf's [variable interpolation](https://omegaconf.readthedocs.io/en/latest/usage.html#variable-interpolation). +At runtime, that value would resolve to *imagenet_alexnet*, or *cifar_resnet* - depending on the values of defaults.dataset and defaults.model. +This a bit clunky because defaults contains a list (I hope to improve this in the future) + +#### optional: true +By default, Hydra would fail with an error if a config specified in the defaults does not exist. +In this case we only want to specialize cifar10 + alexnet, not all 4 combinations. +indication optional: true here tells Hydra to just continue if it can't find this file. + +When specializing config, you usually want to only specify what's different, and not the whole thing. +We want the model for alexnet, when trained on cifar - to have 5 layers. + +### dataset_model/cifar10_alexnet.yaml +```yaml +model: + num_layers: 5 +``` + +Let's check. Running with the default uses imagenet, so we don't get the specialized version of: + +```yaml +$ python example.py +dataset: + name: imagenet + path: /datasets/imagenet +model: + num_layers: 7 + type: alexnet +``` + +Running with cifar10 dataset, we do get 5 for num_layers: +```yaml +$ python example.py dataset=cifar10 +dataset: + name: cifar10 + path: /datasets/cifar10 +model: + num_layers: 5 + type: alexnet +``` diff --git a/testbed/facebookresearch__hydra/website/docs/plugins/ax_sweeper.md b/testbed/facebookresearch__hydra/website/docs/plugins/ax_sweeper.md new file mode 100644 index 0000000000000000000000000000000000000000..433f83376234aa76c4f1fce7d664819b52eebb16 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/plugins/ax_sweeper.md @@ -0,0 +1,99 @@ +--- +id: ax_sweeper +title: Ax Sweeper plugin +sidebar_label: Ax Sweeper plugin +--- +[![PyPI](https://img.shields.io/pypi/v/hydra-ax-sweeper)](https://img.shields.io/pypi/v/hydra-ax-sweeper) +![PyPI - License](https://img.shields.io/pypi/l/hydra-ax-sweeper) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hydra-ax-sweeper) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/hydra-ax-sweeper.svg)](https://pypistats.org/packages/hydra-ax-sweeper) +[![Example application](https://img.shields.io/badge/-Example%20application-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_ax_sweeper/example) +[![Plugin source](https://img.shields.io/badge/-Plugin%20source-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_ax_sweeper) + +This plugin provides a mechanism for Hydra applications to use the [Adaptive Experimentation Platform, aka Ax](https://ax.dev/). Ax can optimize any experiment - machine learning experiments, A/B tests, and simulations. + +### Installation +This plugin requires Hydra 1.0 (Release candidate) +```commandline +$ pip install hydra-ax-sweeper --pre +``` + +### Usage +Once installed, add `hydra/sweeper=ax` to your command line. Alternatively, override `hydra/sweeper` in your config: + +```yaml +defaults: + - hydra/sweeper: ax +``` + +We include an example of how to use this plugin. The file [`example/banana.py`](plugins/hydra_ax/example/banana.py) implements the [Rosenbrock function (aka Banana function)](https://en.wikipedia.org/wiki/Rosenbrock_function). The return value of the function should be the value that we want to optimize. + +To compute the best parameters for the Banana function, clone the code and run the following command in the `plugins/hydra_ax_sweeper` directory: + +``` +python example/banana.py -m banana.x=-5:5 banana.y=-5:10.1 +``` + +The output of a run looks like: + +``` +[HYDRA] AxSweeper is optimizing the following parameters: +banana.x: range=[-5, 5], type = int +banana.y: range=[-5.0, 10.1], type = float +ax.modelbridge.dispatch_utils: Using Bayesian Optimization generation strategy: GenerationStrategy(name='Sobol+GPEI', steps=[Sobol for 5 arms, GPEI for subsequent arms], generated 0 arm(s) so far). Iterations after 5 will take longer to generate due to model-fitting. +AxSweeper is launching 5 jobs +[HYDRA] Launching 5 jobs locally +[HYDRA] #0 : banana.x=4 banana.y=-1.484 +[__main__][INFO] - Banana_Function(x=4, y=-1.484)=30581.473 +[HYDRA] #1 : banana.x=3 banana.y=-3.653 +[__main__][INFO] - Banana_Function(x=3, y=-3.653)=16014.261 +[HYDRA] #2 : banana.x=0 banana.y=9.409 +[__main__][INFO] - Banana_Function(x=0, y=9.409)=8855.340 +[HYDRA] #3 : banana.x=-4 banana.y=2.059 +[__main__][INFO] - Banana_Function(x=-4, y=2.059)=19459.063 +[HYDRA] #4 : banana.x=-3 banana.y=-1.338 +[__main__][INFO] - Banana_Function(x=-3, y=-1.338)=10704.497 +[HYDRA] New best value: 8855.340, best parameters: {'banana.x': 0, 'banana.y': 9.409} +``` + +In this example, we set the range of `x` parameter as an integer in `[-5, 5]` and the range of `y` parameter as a float in `[-5, 10.1]`. Note that in the case of `x`, both the upper and the lower range values are integers, and hence only integers are sampled. In the case of `y`, the lower range value is an int while the upper range value is a float. The lower range value is promoted to float as well, and floating-point numbers are sampled from the range. Other supported formats are fixed parameters (eg `banana.x=5.0`) and choice parameters (eg `banana.x=1,2,3`). + +The values of the `x` and `y` parameters can also be set using the config file `plugins/hydra_ax_sweeper/example/conf/config.yaml`. For instance, the configuration corresponding to the parameter `x` is as follows: + +``` +banana.x: + type: range + bounds: [-5, 5] + +banana.y: + type: range + bounds: [-5, 10.1] +``` + +The `x` parameter takes on a "range" of integer values, between `-5` to `5`. The `y` parameter takes on a range of floating-point values between `-5` to `10.1`. In general, the plugin supports all the [Parameters](https://ax.dev/api/core.html?highlight=range#module-ax.core.parameter) that Ax supports. According to the [Ax documentation](https://ax.dev/api/service.html#ax.service.ax_client.AxClient.create_experiment), the required elements in the config are: + +* `name` - Name of the parameter. It is of type string. +* `type` - Type of the parameter. It can take the following values: `range`, `fixed`, or `choice`. +* `bounds` - Required only for the `range` parameters. It should be a list of two values, with the lower bound first. +* `values` - Required only for the `choice` parameters. It should be a list of values. +* `value` - Required only for the `fixed` parameters. It should be a single value. + +Note that when using the config file, the parameter type (int, float, string, etc.) is set via the [`parameter_type` attribute](https://ax.dev/api/core.html?highlight=range#module-ax.core.parameter). One important thing to note is how mixed types (float + int) are handled. For `y` parameter, the range bounds were set to be `-5` to `10.1`. Both the values were upcasted to a float (irrespective of whether the range was set via the command line or the config file). In case the user provides the `parameter_type` attribute in the config, the attribute is not changed when type casting is done. If the user wants to sample integers in range `-5` to `5`, they need to specify the range as `-5:5` or `[-5, 5]` (in config). If they want to sample floats in range `-5` to `5`, they need to specify the range as `-5.0:5.0` or `[-5.0, 5.0]` (in config). The type casted values, and unchanged attributes are passed to the Ax Client. + +The parameters for the optimization process can also be set in the config file. Specifying the Ax config is optional. The most important parameters are listed below: + +``` +ax_config: + experiment: + # Defaults to minimize, set to false to maximize + minimize: true + + early_stop: + # Number of epochs without a significant improvement from + # the currently known best parameters + # An Epoch is defined as a batch of trials executed in parallel + max_epochs_without_improvement: 100 + + # An improvement larger than epsilon is considered significant + epsilon: 0.00001 +``` diff --git a/testbed/facebookresearch__hydra/website/docs/plugins/colorlog.md b/testbed/facebookresearch__hydra/website/docs/plugins/colorlog.md new file mode 100644 index 0000000000000000000000000000000000000000..d4c7827de3b4a2c01181ba3f6fce48764d3ca478 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/plugins/colorlog.md @@ -0,0 +1,38 @@ +--- +id: colorlog +title: Colorlog plugin +sidebar_label: Colorlog plugin +--- +[![PyPI](https://img.shields.io/pypi/v/hydra-colorlog)](https://pypi.org/project/hydra-colorlog/) +![PyPI - License](https://img.shields.io/pypi/l/hydra-colorlog) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hydra-colorlog) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/hydra-colorlog.svg)](https://pypistats.org/packages/hydra-colorlog) +[![Example application](https://img.shields.io/badge/-Example%20application-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_colorlog/example) +[![Plugin source](https://img.shields.io/badge/-Plugin%20source-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_colorlog) + +Adds colorlog colored logs for `hydra/job_logging` and `hydra/hydra_logging`. + + +### Installation +#### Hydra 0.11 - stable +``` +pip install hydra-colorlog --upgrade +``` + +#### Hydra 1.0 - Release candidate +``` +pip install hydra_colorlog --upgrade --pre +``` + +### Usage +Override `hydra/job_logging` and `hydra/hydra_logging` your config: + +```yaml +defaults: + - hydra/job_logging: colorlog + - hydra/hydra_logging: colorlog +``` + +See included [example](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_colorlog/example). + +![Colored log output](/plugins/colorlog/colorlog.png) diff --git a/testbed/facebookresearch__hydra/website/docs/plugins/joblib_launcher.md b/testbed/facebookresearch__hydra/website/docs/plugins/joblib_launcher.md new file mode 100644 index 0000000000000000000000000000000000000000..c6644208ebe9633f34b77f1f66b34f0a14e87c32 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/plugins/joblib_launcher.md @@ -0,0 +1,99 @@ +--- +id: joblib_launcher +title: Joblib Launcher plugin +sidebar_label: Joblib Launcher plugin +--- +[![PyPI](https://img.shields.io/pypi/v/hydra-joblib-launcher)](https://pypi.org/project/hydra-joblib-launcher/) +![PyPI - License](https://img.shields.io/pypi/l/hydra-joblib-launcher) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hydra-joblib-launcher) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/hydra-joblib-launcher.svg)](https://pypistats.org/packages/hydra-joblib-launcher) +[![Example application](https://img.shields.io/badge/-Example%20application-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_joblib_launcher/example) +[![Plugin source](https://img.shields.io/badge/-Plugin%20source-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_joblib_launcher) + +The Joblib Launcher plugin provides a launcher for parallel tasks based on [`Joblib.Parallel`](https://joblib.readthedocs.io/en/latest/parallel.html). + +### Installation +This plugin requires Hydra 1.0 (Release candidate) +```commandline +$ pip install hydra-joblib-launcher --pre +``` + +### Usage +Once installed, add `hydra/launcher=joblib` to your command line. Alternatively, override `hydra/launcher` in your config: + +```yaml +defaults: + - hydra/launcher: joblib +``` + +By default, process-based parallelism using all available CPU cores is used. By overriding the default configuration, it is e.g. possible limit the number of parallel executions. + +The default configuration packaged with the plugin is: +```python +@dataclass +class JobLibLauncherConf(PluginConf): + cls: str = "hydra_plugins.hydra_joblib_launcher.JoblibLauncher" + params: JobLibConf = JobLibConf() +``` + +The JobLibConf class is defined [here](https://github.com/facebookresearch/hydra/blob/master/plugins/hydra_joblib_launcher/hydra_plugins/hydra_joblib_launcher/config.py): + +It looks like this: + +```python +@dataclass +class JobLibConf: + # maximum number of concurrently running jobs. if -1, all CPUs are used + n_jobs: int = -1 + + # allows to hard-code backend, otherwise inferred based on prefer and require + backend: Optional[str] = None + + # processes or threads, soft hint to choose backend + prefer: str = "processes" + + # null or sharedmem, sharedmem will select thread-based backend + require: Optional[str] = None + + # if greater than zero, prints progress messages + verbose: int = 0 + + # timeout limit for each task + timeout: Optional[int] = None + + # number of batches to be pre-dispatched + pre_dispatch: str = "2*n_jobs" + + # number of atomic tasks to dispatch at once to each worker + batch_size: str = "auto" + + # folder used for memmapping large arrays for sharing memory with workers + temp_folder: Optional[str] = None + + # thresholds size of arrays that triggers automated memmapping + max_nbytes: Optional[str] = None + + # memmapping mode for numpy arrays passed to workers + mmap_mode: str = "r" +``` + +See [`Joblib.Parallel` documentation](https://joblib.readthedocs.io/en/latest/parallel.html) for full details about the parameters above. + +
+ +An [example application](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_joblib_launcher/example) using this launcher is provided in the plugin repository. + +Starting the app with `python my_app.py --multirun task=1,2,3,4,5` will launch five parallel executions: + +```text +$ python my_app.py --multirun task=1,2,3,4,5 +[HYDRA] Joblib.Parallel(n_jobs=-1,verbose=0,timeout=None,pre_dispatch=2*n_jobs,batch_size=auto,temp_folder=None,max_nbytes=None,mmap_mode=r,backend=loky) is launching 5 jobs +[HYDRA] Launching jobs, sweep output dir : multirun/2020-02-18/10-00-00 +[__main__][INFO] - Process ID 14336 executing task 2 ... +[__main__][INFO] - Process ID 14333 executing task 1 ... +[__main__][INFO] - Process ID 14334 executing task 3 ... +[__main__][INFO] - Process ID 14335 executing task 4 ... +[__main__][INFO] - Process ID 14337 executing task 5 ... +``` diff --git a/testbed/facebookresearch__hydra/website/docs/plugins/nevergrad_sweeper.md b/testbed/facebookresearch__hydra/website/docs/plugins/nevergrad_sweeper.md new file mode 100644 index 0000000000000000000000000000000000000000..1a6eb042a036aae08436043a4345e382eee8c633 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/plugins/nevergrad_sweeper.md @@ -0,0 +1,188 @@ +--- +id: nevergrad_sweeper +title: Nevergrad Sweeper plugin +sidebar_label: Nevergrad Sweeper plugin +--- + +[![PyPI](https://img.shields.io/pypi/v/hydra-nevergrad-sweeper)](https://pypi.org/project/hydra-nevergrad-sweeper/) +![PyPI - License](https://img.shields.io/pypi/l/hydra-nevergrad-sweeper) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hydra-nevergrad-sweeper) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/hydra-nevergrad-sweeper.svg)](https://pypistats.org/packages/hydra-nevergrad-sweeper) +[![Example application](https://img.shields.io/badge/-Example%20application-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_nevergrad_sweeper/example) +[![Plugin source](https://img.shields.io/badge/-Plugin%20source-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_nevergrad_sweeper) + + +[Nevergrad](https://facebookresearch.github.io/nevergrad/) is a derivative-free optimization platform proposing a library of state-of-the art algorithms for hyperparameter search. This plugin provides a mechanism for Hydra applications to use [Nevergrad](https://facebookresearch.github.io/nevergrad/) algorithms for the optimization of experiments/applications parameters. + +### Installation +This plugin requires Hydra 1.0 (Release candidate) +```commandline +$ pip install hydra-nevergrad-sweeper --pre +``` + +### Usage +Once installed, add `hydra/sweeper=nevergrad` to your command command. Alternatively, override `hydra/sweeper` in your config: + +```yaml +defaults: + - hydra/sweeper: nevergrad +``` + + +The default configuration is [here](https://github.com/facebookresearch/hydra/blob/master/plugins/hydra_nevergrad_sweeper/hydra_plugins/hydra_nevergrad_sweeper/config.py). + +## Example of training using Nevergrad hyperparameter search + +We include an example of how to use this plugin. The file [`example/dummy_training.py`](plugins/hydra_nevergrad_sweeper/example/dummy_training.py) implements an example of how to perform minimization of a (dummy) function including a mixture of continuous and discrete parameters. + + +This application has the following configuration: +```yaml +defaults: + - hydra/sweeper: nevergrad + +hydra: + sweeper: + params: + + # configuration of the optimizer + optim: + # name of the Nevergrad optimizer to use. Here is a sample: + # - "OnePlusOne" extremely simple and robust, especially at low budget, but + # tends to converge early. + # - "CMA" very good algorithm, but may require a significant budget (> 120) + # - "TwoPointsDE": an algorithm good in a wide range of settings, for significant + # budgets (> 120). + # - "Shiwa" an algorithm aiming at identifying the best optimizer given your input + # definition (work in progress, it may still be ill-suited for low budget) + # find out more within nevergrad's documentation: + # https://github.com/facebookresearch/nevergrad/ + optimizer: OnePlusOne + # total number of function evaluations to perform + budget: 100 + # number of parallel workers for performing function evaluations + num_workers: 10 + # maximize: true # comment out for maximization + + # default parametrization of the search space + parametrization: + # either one or the other + db: + - mnist + - cifar + # a log-distributed positive scalar, evolving by factors of 2 on average + lr: + init: 0.02 + step: 2.0 + log: true + # a linearly-distributed scalar between 0 and 1 + dropout: + lower: 0.0 + upper: 1.0 + # an integer scalar going from 4 to 16 + # init and step parameters could also be provided, + # by default init is set to the middle of the range + # and step is set to a sixth of the range + batch_size: + lower: 4 + upper: 16 + integer: true + +db: cifar +lr: 0.01 +batch_size: 8 +dropout: 0.6 +``` + +The function decorated with `@hydra.main()` returns a float which we want to minimize, the minimum is 0 and reached for: +```yaml +db: mnist +lr: 0.12 +dropout: 0.33 +batch_size=4 +``` + +To run hyperparameter search and look for the best parameters for this function, clone the code and run the following command in the `plugins/hydra_nevergrad_sweeper` directory: +```bash +python example/dummy_training.py -m +``` + +You can also override the search space parametrization: +```bash +python example/dummy_training.py -m db=mnist,cifar batch_size=4,8,16 lr=log:0.001:1 dropout=0:1 +``` + +The initialization of the sweep and the first 5 evaluations (out of 100) look like this: + +```text +[HYDRA] NevergradSweeper(optimizer=OnePlusOne, budget=100, num_workers=10) minimization +[HYDRA] with parametrization Dict(batch_size=TransitionChoice(choices=Tuple(4,8,16),position=Scalar[sigma=Log{exp=1.2}],transitions=[1. 1.]),db=Choice(choices=Tuple(mnist,cifar),weights=Array{(2,)}),dropout=Scalar{Cl(0,1)}[sigma=Log{exp=1.2}],lr=Log{exp=3.162277660168379,Cl(0.001,1)}):{'db': 'cifar', 'batch_size': 8, 'lr': 0.03162277660168379, 'dropout': 0.5} +[HYDRA] Sweep output dir: multirun/2020-03-04/17-53-29 +[HYDRA] Launching 10 jobs locally +[HYDRA] #0 : db=mnist batch_size=8 lr=0.032 dropout=0.5 +[__main__][INFO] - dummy_training(dropout=0.500, lr=0.032, db=mnist, batch_size=8) = 5.258 +[HYDRA] #1 : db=mnist batch_size=16 lr=0.035 dropout=0.714 +[__main__][INFO] - dummy_training(dropout=0.714, lr=0.035, db=mnist, batch_size=16) = 13.469 +[HYDRA] #2 : db=cifar batch_size=8 lr=0.053 dropout=0.408 +[__main__][INFO] - dummy_training(dropout=0.408, lr=0.053, db=cifar, batch_size=8) = 4.145 +[HYDRA] #3 : db=cifar batch_size=8 lr=0.012 dropout=0.305 +[__main__][INFO] - dummy_training(dropout=0.305, lr=0.012, db=cifar, batch_size=8) = 4.133 +[HYDRA] #4 : db=mnist batch_size=4 lr=0.030 dropout=0.204 +[__main__][INFO] - dummy_training(dropout=0.204, lr=0.030, db=mnist, batch_size=4) = 1.216 +``` + + +and the final 2 evaluations look like this: +```text +[HYDRA] #8 : db=mnist batch_size=4 lr=0.094 dropout=0.381 +[__main__][INFO] - dummy_training(dropout=0.381, lr=0.094, db=mnist, batch_size=4) = 1.077 +[HYDRA] #9 : db=mnist batch_size=4 lr=0.094 dropout=0.381 +[__main__][INFO] - dummy_training(dropout=0.381, lr=0.094, db=mnist, batch_size=4) = 1.077 +[HYDRA] Best parameters: db=mnist batch_size=4 lr=0.094 dropout=0.381 +``` + + +The run also creates an `optimization_results.yaml` file in your sweep folder with the parameters recommended by the optimizer: +```yaml +best_evaluated_result: 0.381 + +best_evaluated_params: + batch_size: 4 + db: mnist + dropout: 0.381 + lr: 0.094 + +name: nevergrad: +``` + +## Defining the parameters + +The plugin can use 2 types of parameters: + +### Choices + +Choices are defined with **comma-separated values** in the command-line (`db=mnist,cifar` or `batch_size=4,8,12,16`) or with a list in a config file. +By default, values are processed as floats if all can be converted to it, but you can modify this behavior by adding colon-separated specifications `int` or `str` before the the list. (eg.: `batch_size=int:4,8,12,16`) + +**Note:** sequences of increasing scalars are treated as a special case, easier to solve. Make sure to specify it this way when possible. + +### Scalars +Scalars can be defined: + +- through a commandline override with **`:`-separated values** defining a range (eg: `dropout=0:1`). +You can add specifications for log distributed values (eg.: `lr=log:0.001:1`) or integer values (eg.: `batch_size=int:4:8`) +or a combination of both (eg.: `batch_size=log:int:4:1024`) + +- through a config files, with fields: + - `init`: optional initial value + - `lower` : optional lower bound + - `upper`: optional upper bound + - `log`: set to `true` for log distributed values + - `step`: optional step size for looking for better parameters. In linear mode this is an additive step, in logarithmic mode it + is multiplicative.  + - `integer`: set to `true` for integers (favor floats over integers whenever possible) + + Providing only `lower` and `upper` bound will set the initial value to the middle of the range, and the step to a sixth of the range. + +**Note**: unbounded scalars (scalars with no upper and/or lower bounds) can only be defined through a config file. + diff --git a/testbed/facebookresearch__hydra/website/docs/plugins/submitit_launcher.md b/testbed/facebookresearch__hydra/website/docs/plugins/submitit_launcher.md new file mode 100644 index 0000000000000000000000000000000000000000..e9c55f6d06d69e38c2badc545b23849f4215181a --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/plugins/submitit_launcher.md @@ -0,0 +1,169 @@ +--- +id: submitit_launcher +title: Submitit Launcher plugin +sidebar_label: Submitit Launcher plugin +--- +[![PyPI](https://img.shields.io/pypi/v/hydra-submitit-launcher)](https://pypi.org/project/hydra-submitit-launcher/) +![PyPI - License](https://img.shields.io/pypi/l/hydra-submitit-launcher) +![PyPI - Python Version](https://img.shields.io/pypi/pyversions/hydra-submitit-launcher) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/hydra-submitit-launcher.svg)](https://pypistats.org/packages/hydra-submitit-launcher) +[![Example application](https://img.shields.io/badge/-Example%20application-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_submitit_launcher/example) +[![Plugin source](https://img.shields.io/badge/-Plugin%20source-informational)](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_submitit_launcher) + +The Submitit Launcher plugin provides a [SLURM ](https://slurm.schedmd.com/documentation.html) Launcher based on [Submitit](https://github.com/facebookincubator/submitit). + +### Installation +This plugin requires Hydra 1.0 (Release candidate) +```commandline +$ pip install hydra-submitit-launcher --pre +``` + +### Usage +Once installed, add `hydra/launcher=submitit` to your command line. Alternatively, override `hydra/launcher` in your config: + +```yaml +defaults: + - hydra/launcher: submitit +``` + +Note that this plugin expects a valid environment in the target host. usually this means a shared file system between +the launching host and the target host. + +Submitit supports 3 types of queues: auto, local and slurm. Its config looks like this +```python +class QueueType(Enum): + auto = "auto" + local = "local" + slurm = "slurm" + + +@dataclass +class SlurmQueueConf: + # Params are used to configure sbatch, for more info check: + # https://github.com/facebookincubator/submitit/blob/master/submitit/slurm/slurm.py + + # maximum time for the job in minutes + time: int = 60 + # number of cpus to use for each task + cpus_per_task: int = 10 + # number of gpus to use on each node + gpus_per_node: int = 1 + # number of tasks to spawn on each node + ntasks_per_node: int = 1 + # number of nodes to use for the job + nodes: int = 1 + # memory to reserve for the job on each node, in GB + mem: str = "${hydra.launcher.mem_limit}GB" + # slurm partition to use on the cluster + partition: Optional[str] = None + # USR1 signal delay before timeout + signal_delay_s: int = 120 + # name of the job + job_name: str = "${hydra.job.name}" + # Maximum number of retries on job timeout. + # Change this only after you confirmed your code can handle re-submission + # by properly resuming from the latest stored checkpoint. + # check the following for more info on slurm_max_num_timeout + # https://github.com/facebookincubator/submitit/blob/master/docs/checkpointing.md + max_num_timeout: int = 0 + + +@dataclass +class LocalQueueConf: + # local executor mocks the behavior of slurm locally + + # maximum time for the job in minutes + timeout_min: int = 60 + # number of gpus to use on each node + gpus_per_node: int = 1 + # number of tasks to spawn on each node (only one node available in local executor) + tasks_per_node: int = 1 + + +@dataclass +class AutoQueueConf: + # auto executor automatically identifies and uses available cluster + # Currently this is only slurm, but local executor can be manually forced + # instead. + # Most parameters are shared between clusters, some can be cluster specific + + # cluster to use (currently either "slurm" or "local" are supported, + # None defaults to an available cluster) + cluster: Optional[str] = None + + # maximum time for the job in minutes + timeout_min: int = 60 + # number of cpus to use for each task + cpus_per_task: int = 1 + # number of gpus to use on each node + gpus_per_node: int = 0 + # number of tasks to spawn on each node + tasks_per_node: int = 1 + # memory to reserve for the job on each node (in GB) + mem_gb: int = 4 + # number of nodes to use for the job + nodes: int = 1 + # name of the job + name: str = "${hydra.job.name}" + + # following parameters are SLURM specific + + # Maximum number of retries on job timeout. + # Change this only after you confirmed your code can handle re-submission + # by properly resuming from the latest stored checkpoint. + # check the following for more info on slurm_max_num_timeout + # https://github.com/facebookincubator/submitit/blob/master/docs/checkpointing.md + slurm_max_num_timeout: int = 0 + # USR1 signal delay before timeout for the slurm queue + slurm_signal_delay_s: int = 30 + # slurm partition to use on the cluster + slurm_partition: Optional[str] = None + + +@dataclass +class QueueParams: + slurm: SlurmQueueConf = SlurmQueueConf() + local: LocalQueueConf = LocalQueueConf() + auto: AutoQueueConf = AutoQueueConf() + + +@dataclass +class SubmititConf: + queue: QueueType = QueueType.local + + folder: str = "${hydra.sweep.dir}/.${hydra.launcher.params.queue}" + + queue_parameters: QueueParams = QueueParams() +``` + +See [Submitit documentation](https://github.com/facebookincubator/submitit) for full details about the parameters above. + +An [example application](https://github.com/facebookresearch/hydra/tree/master/plugins/hydra_submitit_launcher/example) using this launcher is provided in the plugin repository. + +Starting the app with `python my_app.py task=1,2,3 -m` will launch 3 executions: + +```text +$ python my_app.py task=1,2,3 -m +[HYDRA] Sweep output dir : multirun/2020-05-28/15-05-22 +[HYDRA] #0 : task=1 +[HYDRA] #1 : task=2 +[HYDRA] #2 : task=3 +``` +You will be able to see the output of the app in the output dir: +```commandline +$ tree +. +├── 0 +│   └── my_app.log +├── 1 +│   └── my_app.log +├── 2 +│   └── my_app.log +└── multirun.yaml + + +$ cat 0/my_app.log +[2020-05-28 15:05:23,511][__main__][INFO] - Process ID 15887 executing task 1 ... +[2020-05-28 15:05:24,514][submitit][INFO] - Job completed successfully +``` + diff --git a/testbed/facebookresearch__hydra/website/docs/terminology.md b/testbed/facebookresearch__hydra/website/docs/terminology.md new file mode 100644 index 0000000000000000000000000000000000000000..e232c5f0b89f7577756c935127d2a398d055b4f1 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/terminology.md @@ -0,0 +1,90 @@ +--- +id: terminology +title: Terminology +--- +## Overview +This page describes some of the common concepts in Hydra. +Most of the concepts are described in much more details throughout the documentation. + +## Input Configs +Input configs are used to construct the config object used by the application. +Supported input configs are: +- Config Files ([YAML](https://yaml.org/) files) +- Command line arguments +- [Structured Configs](#structured-config) (Python [@dataclasses](https://docs.python.org/3/library/dataclasses.html)) + +### Primary Config +The input config named in [`@hydra.main()`](tutorials/basic/your_first_app/1_simple_cli.md) or in +the [`Compose API`](experimental/hydra_compose.md). +The Primary Config is the only config that is allowed to have a [Defaults List](#defaults-list) + + +### Structured Config +A @dataclass or an instance of a @dataclass that is used to construct a config. These enable both runtime and static type checking. + +There are two primary patterns for using Structured configs: +- As an [Input Config](#input-configs). +- As a schema validating Config Files and command line arguments. + +```python title="Example:" +@dataclass +class User: + name: str = MISSING + age: int = MISSING +``` + + +### Defaults List +A list in the [Primary Config](#primary-config) that determines how to build the final [Config Object](#output-config-object). +The list is typically composed of [Config Group Options](#config-group-option). +```yaml title="Example: config.yaml" +defaults: + - db: mysql + - schema: school +``` + +### Config Group + +A Config Group is a mutually exclusive set of [Config Group Options](#config-group-option). +Config Groups can be hierarchical and in that case the path elements are separated by a forward slash ('/') +regardless of the operating system. + +### Config Group Option +One of the configs in a Config Group. + +### Config Node +A Config Node is either a `Value Node` (a primitive type), or a `Container Node`. A `Container Node` is a list or dictionary of `Value Nodes`. + +### Package +A Package is the path of the [Config Node](#config-node) in the [Config Object](#output-config-object). + +### Package directive +The [Package Directive](advanced/overriding_packages.md) specifies the root [Package](#package) of an [Config File](#input-configs) + +### Example +```yaml title="Input config: mi6/agent/james_bond.yaml" +# @package _group_ +codename: '007' +``` +```yaml title="Resulting config" +mi6: + agent: + codename: '007' +``` +- [Config Group](#config-group): mi6/agent +- [Config Group Option](#config-group-option): james_bond +- [Container Nodes](#config-node): `{codename: '007'}`,  . . .  ,`{mi6: {agent: {codename: '007'}}}` +- [Value Node](#config-node): '007' +- [Packages](#package) ``, `mi6`, `mi6.agent`, `mi6.agent.codename` +- [Package directive](#package-directive) : `@package _group_`, which expands to `mi6.agent` + +## Output Config Object +The config for the application. It is a dictionary of [Config Nodes](#config-node) generated from the [Input Configs](#input-configs). + +## Misc +### Config Search Path +The [Config Search Path](advanced/search_path.md) is a list of paths that are searched in order to find configs. It is similar to +the Python PYTHONPATH. + +### Plugins +[Plugins](advanced/plugins.md) extend Hydra's capabilities. Some examples are Launcher and Sweeper. \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/2_multirun.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/2_multirun.md new file mode 100644 index 0000000000000000000000000000000000000000..93749a374ac93d09df4faedd422c6ed9538d4513 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/2_multirun.md @@ -0,0 +1,44 @@ +--- +id: multi-run +title: Multi-run +sidebar_label: Multi-run +--- + +Sometimes you want to run a parameter sweep. +A parameter sweep is a method of evaluating a function (or a program) with a pre-determined set of parameters. +The examples below will clarify what this means. + +To run a parameter sweep, use the `--multirun` (`-m`) flag and pass a comma separated list for each +dimension you want to sweep. + +To run your program with the 3 different schemas in schema config group: +``` +$ python my_app.py -m schema=warehouse,support,school +``` + +Here is sweep over the db types (mysql,postgresql) and the schemas (warehouse,support,school). +Output does not contain the configuration prints. + +```text + $ python my_app.py schema=warehouse,support,school db=mysql,postgresql -m +[2019-10-01 14:44:16,254] - Launching 6 jobs locally +[2019-10-01 14:44:16,254] - Sweep output dir : multirun/2019-10-01/14-44-16 +[2019-10-01 14:44:16,254] - #0 : schema=warehouse db=mysql +[2019-10-01 14:44:16,321] - #1 : schema=warehouse db=postgresql +[2019-10-01 14:44:16,390] - #2 : schema=support db=mysql +[2019-10-01 14:44:16,458] - #3 : schema=support db=postgresql +[2019-10-01 14:44:16,527] - #4 : schema=school db=mysql +[2019-10-01 14:44:16,602] - #5 : schema=school db=postgresql +``` + +### Sweeper +The sweeping logic is implemented by a simple sweeper that is built into Hydra. +Additional sweepers are available as plugins. +For example, the [Ax Sweeper](/plugins/ax_sweeper.md) can automatically find the best parameter combination! + +### Launcher +A Launcher is what runs your job, Hydra comes with a simple launcher that runs the jobs locally and serially. +However, other launchers are available as plugins. For example - The [JobLib Launcher](/plugins/joblib_launcher.md) +can execute the different parameter combinations in parallel on your local machine using multi-processing. + +There are plans to add additional Launchers, such as a Launcher that launches your application code on AWS. diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/3_working_directory.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/3_working_directory.md new file mode 100644 index 0000000000000000000000000000000000000000..7532de2c6489a193ac7d7653a389f5570d27e15b --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/3_working_directory.md @@ -0,0 +1,85 @@ +--- +id: working_directory +title: Output/Working directory +sidebar_label: Output/Working directory +--- + +Hydra solves the problem of your needing to specify a new output directory for each run, by +creating a directory for each run and executing your code within that working directory. + +The working directory is used to: +* Store the output for the application (For example, a database dump file) +* Store the Hydra output for the run (Configuration, Logs etc) + +Every time you run the app, a new working directory is created: + +Python file: `my_app.py` +```python +import os +from omegaconf import DictConfig + +@hydra.main() +def my_app(cfg: DictConfig) -> None: + print("Working directory : {}".format(os.getcwd())) + +$ python my_app.py +Working directory : /home/omry/dev/hydra/outputs/2019-09-25/15-16-17 + +$ python my_app.py +Working directory : /home/omry/dev/hydra/outputs/2019-09-25/15-16-19 +``` + +Let's take a look at one of the working directories: +```text +$ tree outputs/2019-09-25/15-16-17 +outputs/2019-09-25/15-16-17 +├── .hydra +│ ├── config.yaml +│ ├── hydra.yaml +│ └── overrides.yaml +└── my_app.log +``` + +We have the Hydra output directory (`.hydra` by default) and the application log file. +Inside the configuration output directory we have: +* `config.yaml`: A dump of the user specified configuration +* `hydra.yaml`: A dump of the Hydra configuration +* `overrides.yaml`: The command line overrides used + +And in the main output directory: +* `my_app.log`: A log file created for this run + +### Disabling output subdir +You can change the `.hydra` subdirectory name by overriding `hydra.output_subdir`. +You can disable its creation by overriding `hydra.output_subdir` to `null`. + + +### Original working directory + +You can still access the original working directory if you need to: + +```python +import os +from omegaconf import DictConfig +import hydra + +@hydra.main() +def my_app(_cfg: DictConfig) -> None: + print(f"Current working directory : {os.getcwd()}") + print(f"Orig working directory : {hydra.utils.get_original_cwd()}") + print(f"to_absolute_path('foo') : {hydra.utils.to_absolute_path('foo')}") + print(f"to_absolute_path('/foo') : {hydra.utils.to_absolute_path('/foo')}") + +if __name__ == "__main__": + my_app() + + +$ python examples/tutorial/8_working_directory/original_cwd.py +Current working directory : /Users/omry/dev/hydra/outputs/2019-10-23/10-53-03 +Original working directory : /Users/omry/dev/hydra +to_absolute_path('foo') : /Users/omry/dev/hydra/foo +to_absolute_path('/foo') : /foo +``` + + +Working directory can be [customized](/configure_hydra/workdir.md). diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/4_logging.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/4_logging.md new file mode 100644 index 0000000000000000000000000000000000000000..ff997ab696497f8579224d224fdcdeec9a8dbce7 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/4_logging.md @@ -0,0 +1,61 @@ +--- +id: logging +title: Logging +sidebar_label: Logging +--- + +People often do not use Python logging due to the setup cost. +Hydra solves that by configuring the Python logging for you. + + +By default Hydra logs at the INFO level to both the console and a log file in the automatic working directory. + +Example of logging with Hydra: + +```python +import logging +from omegaconf import DictConfig +import hydra + +# A logger for this file +log = logging.getLogger(__name__) + +@hydra.main() +def my_app(_cfg: DictConfig) -> None: + log.info("Info level message") + log.debug("Debug level message") + +if __name__ == "__main__": + my_app() + +$ python my_app.py +[2019-06-27 00:52:46,653][__main__][INFO] - Info level message + +``` +You can enable DEBUG level logging from the command line by overriding `hydra.verbose`. + +`hydra.verbose` can be a Boolean, a String or a List: + +Examples: +* `hydra.verbose=true` : Sets the log level of **all** loggers to `DEBUG` +* `hydra.verbose=NAME` : Sets the log level of the logger `NAME` to `DEBUG` +* `hydra.verbose=[NAME1,NAME2]`: Sets the log level of the loggers `NAME1` and `NAME2` to `DEBUG` + +Example output: +``` text +$ python my_app.py hydra.verbose=[__main__,hydra] +[2019-09-29 13:06:00,880] - Installed Hydra Plugins +[2019-09-29 13:06:00,880] - *********************** +... +[2019-09-29 13:06:00,896][__main__][INFO] - Info level message +[2019-09-29 13:06:00,896][__main__][DEBUG] - Debug level message +``` + +You can disable the logging output using by setting `hydra/job_logging` to `disabled' +```commandline +$ python my_app.py hydra/job_logging=disabled + +``` + +Logging can be [customized](/configure_hydra/logging.md). + diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/5_debugging.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/5_debugging.md new file mode 100644 index 0000000000000000000000000000000000000000..12c153f12d343dc86e019b0268e842104428ce05 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/5_debugging.md @@ -0,0 +1,65 @@ +--- +id: debugging +title: Debugging +sidebar_label: Debugging +--- +Hydra provides a few options to improve debuggability. + +### Printing the configuration +Print the config for your app without running your function by adding `--cfg` or `-c` to the command line. + +The `--cfg` option takes one argument indicating which part of the config to print: +* `job` : Your config +* `hydra` : Hydra's config +* `all` : The full config, which is a union of `job` and `hydra`. + +```yaml +# A normal run: +$ python my_app.py +MySQL connecting to localhost with user=root and password=1234 + +# just show the config without running your function: +$ python my_app.py --cfg job +db: + host: localhost + user: root + password: 1234 +``` +The printed config includes any modifications done via the command line: +```yaml {3} +$ python my_app.py db.host=10.0.0.1 --cfg job +db: + host: 10.0.0.1 + user: root + password: 1234 +``` + +You can use `--package` or `-p` to select a a specific config package: +```yaml +python my_app.py --cfg hydra --package hydra.job +# @package hydra.job +name: my_app +config_name: config +... +``` + +### Info +Hydra can print information about your plugins, config search path, composition trace and more using the +`--info` flag. +```text +$ python my_app.py --info +``` + +Subset of output (Complete [example](http://paste.ubuntu.com/p/JWh2cKgGtD/)) +```commandline +Config search path +... +Profiling information +... +Composition trace +... +Config +... +``` + + diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/6_tab_completion.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/6_tab_completion.md new file mode 100644 index 0000000000000000000000000000000000000000..226b8865c92c0c528ef29243b7c950c258bcdec1 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/running_your_app/6_tab_completion.md @@ -0,0 +1,22 @@ +--- +id: tab_completion +title: Tab completion +sidebar_label: Tab completion +--- + +Tab completion can complete config groups, config nodes and values. +To complete paths, start them with `/` or `./`. + +See this short video demonstration of tab completion: + +import Script from '../../../../src/components/Script.jsx'; + + + + +### Install tab completion +Get the exact command to install the completion from `--hydra-help`. +Currently, Bash and Fish are supported. We are relying on the community to implement completion plugins for additional shells. + +Fish support requires version >= 3.1.2. +Previous versions will work but add an extra space after `.`. \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/1_simple_cli.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/1_simple_cli.md new file mode 100644 index 0000000000000000000000000000000000000000..7c32718ab039052bbd5734eae2f6d3cabb82cfc9 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/1_simple_cli.md @@ -0,0 +1,34 @@ +--- +id: simple_cli +title: A simple command-line application +--- + +This is a simple Hydra application that prints your configuration. +The `my_app` function is a place holder for your code. +We will slowly evolve this example to showcase more Hydra features. + +The examples in this tutorial are available [here](https://github.com/facebookresearch/hydra/tree/master/examples/tutorials/basic). + +```python title="my_app.py" +from omegaconf import DictConfig +import hydra + +@hydra.main() +def my_app(cfg: DictConfig) -> None: + print(cfg.pretty()) + +if __name__ == "__main__": + my_app() +``` +In this example, Hydra creates an empty `cfg` object and pass it to the function annotated with `@hydra.main`. + +You can add config values via the command line. The `+` indicates that the field is new. + +```yaml +$ python my_app.py +db.driver=mysql +db.user=omry +db.password=secret +db: + driver: mysql + user: omry + password: secret +``` + diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/2_config_file.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/2_config_file.md new file mode 100644 index 0000000000000000000000000000000000000000..28ee46cc2dd42339f06897e5ab50ac53e924efd3 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/2_config_file.md @@ -0,0 +1,43 @@ +--- +id: config_file +title: Specifying a config file +--- + +It can get tedious to type all those command line arguments. +One solution is to create a configuration file in YAML format and place it next to `my_app.py`. + +```yaml title="config.yaml" +db: + driver: mysql + user: omry + password: secret +``` + +Specify the config name by passing a `config_name` parameter to the `@hydra.main()` decorator. +Note that you should omit the `.yaml` extension. +```python title="my_app.py" {1} +@hydra.main(config_name='config') +def my_app(cfg): + print(cfg.pretty()) +``` + +`config.yaml` is loaded automatically when you run your application. +```yaml +$ python my_app.py +db: + driver: mysql + user: omry + password: secret +``` + +You can override values in the loaded config from the command line. +Note the lack of the `+` prefix. +```yaml {4-5} +$ python my_app.py db.user=root db.password=1234 +db: + driver: mysql + user: root + password: 1234 +``` + +You can enable [tab completion](/tutorials/basic/7_tab_completion.md) for your Hydra applications. \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/3_using_config.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/3_using_config.md new file mode 100644 index 0000000000000000000000000000000000000000..2614b1d739ad7f435a331f273ff8db1c3d4e03c4 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/3_using_config.md @@ -0,0 +1,37 @@ +--- +id: using_config +title: Using the config object +--- + +You configuration object is an instance of OmegaConf's DictConfig. +Here are some of the basic features: + +```yaml title="config.yaml" +node: # Config is hierarchical + loompa: 10 # Simple value + zippity: ${node.loompa} # Value interpolation + do: "oompa ${node.loompa}" # String interpolation + waldo: ??? # Missing value, must be populated prior to access +``` + +```python title="main.py" +@hydra.main(config_name="config") +def my_app(cfg: DictConfig): + assert cfg.node.loompa == 10 # attribute style access + assert cfg["node"]["loompa"] == 10 # dictionary style access + + assert cfg.node.zippity == 10 # Value interpolation + assert type(cfg.node.zippity) == int # Value interpolation type + assert cfg.node.do == "oompa 10" # string interpolation + + cfg.node.waldo # raises an exception + ``` +Outputs: +``` +$ python my_app.py +Missing mandatory value: waldo + full_key: waldo + reference_type=Optional[Dict[Any, Any]] + object_type=dict +``` +You can learn more about OmegaConf here. \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/4_config_groups.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/4_config_groups.md new file mode 100644 index 0000000000000000000000000000000000000000..66145937ce07c79f2c4b3be4061c305808e0bcaf --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/4_config_groups.md @@ -0,0 +1,96 @@ +--- +id: config_groups +title: Grouping config files +--- +Suppose you want to benchmark your application on each of PostgreSQL and MySQL. To do this, use config groups. + +A _**Config Group**_ is a named group with a set of valid options. + +* The config options are mutually exclusive. Only one can be selected. +* Selecting a non-existent config option generates an error message with the valid options. + +To create a config group, create a directory. e.g. `db` to hold a file for each database configuration option. +Since we are expecting to have multiple config groups, we will proactively move all the configuration files +into a `conf` directory. + + +``` text title="Directory layout" +├── conf +│   └── db +│   ├── mysql.yaml +│   └── postgresql.yaml +└── my_app.py +``` + +```yaml title="db/mysql.yaml" +# @package _group_ +driver: mysql +user: omry +password: secret +``` +The config group determines the `package` of the config content inside the final config object. +```yaml title="Interpretation of db/mysql.yaml" {1} +db: + driver: mysql + user: omry + password: secret +``` +In Hydra 1.1 `_group_` will become the default package. +For now, add `# @package _group_` at the top of your config group files. +Learn more about packages directive [here](/advanced/overriding_packages.md). + +### Using config groups +Since we moved all the configs into the `conf` directory, we need to tell Hydra where to find them using the `config_path` parameter. +**`config_path` is a directory relative to `my_app.py`**. +```python title="my_app.py" {1} +@hydra.main(config_path="conf") +def my_app(cfg: DictConfig) -> None: + print(cfg.pretty()) +``` + +Running `my_app.py` without requesting a configuration will print an empty config. +```yaml +$ python my_app.py +{} +``` + +You can append an item a config group to the `Defaults List`. +The `Defaults List` is described on the next page. +```yaml +$ python my_app.py +db=postgresql +db: + driver: postgresql + pass: drowssap + timeout: 10 + user: postgre_user +``` + +Like before, you can still override individual values in the resulting config: +```yaml +$ python my_app.py +db=postgresql db.timeout=20 +db: + driver: postgresql + pass: drowssap + timeout: 20 + user: postgre_user +``` + +### More advanced usages of config groups +Config groups can be nested. For example the config group `db/mysql/storage_engine` can contain `innodb.yaml` and `myisam.yaml`. +When selecting an option from a nested config group, use `/`: +``` +$ python my_app.py +db=mysql +db/mysql/storage_engine=innodb +db: + driver: mysql + user: omry + password: secret + mysql: + storage_engine: + innodb_data_file_path: /var/lib/mysql/ibdata1 + max_file_size: 1G +``` + +This simple example also demonstrated a very powerful feature of Hydra: +You can compose your configuration object from multiple configuration groups. + + diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/5_defaults.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/5_defaults.md new file mode 100644 index 0000000000000000000000000000000000000000..69e49462476c7f138215cc62da23675fa09f5502 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/5_defaults.md @@ -0,0 +1,72 @@ +--- +id: defaults +title: Selecting defaults for config groups +--- + +After office politics, you decide that you want to use MySQL by default. +You no longer want to type `+db=mysql` every time you run your application. + +You can add a `defaults` list into your config file. + +## Config group defaults + +```yaml title="config.yaml" +defaults: + - db: mysql +``` + +Remember to specify the `config_name`: +```python +@hydra.main(config_path="conf", config_name="config") +def my_app(cfg: DictConfig) -> None: + print(cfg.pretty()) +``` + +When you run the updated application, MySQL is loaded by default. +```yaml +$ python my_app.py +db: + driver: mysql + pass: secret + user: omry +``` + +You can have multiple items in the defaults list, e.g +```yaml +defaults: + - db: mysql + - db/mysql/storage_engine: innodb +``` + +The defaults are ordered: + * If multiple configs define the same value, the last one wins. + * If multiple configs contribute to the same dictionary, the result is the combined dictionary. + + +### Overriding a config group default + +You can still load PostgreSQL, and override individual values. +```yaml +$ python my_app.py db=postgresql db.timeout=20 +db: + driver: postgresql + pass: drowssap + timeout: 20 + user: postgre_user +``` + +You can remove a default entry from the defaults list by prefixing it with ~: +```yaml +$ python my_app.py ~db +{} +``` + +## Non-config group defaults +Sometimes a config file does not belong in any config group. +You can still load it by default. Here is an example for `some_file.yaml`. +```yaml +defaults: + - some_file +``` +Config files that are not part of a config group will always be loaded. They cannot be overridden. +Prefer using a config group. diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/6_composition.md b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/6_composition.md new file mode 100644 index 0000000000000000000000000000000000000000..5d61a44080a01ba46a9ec285325e955063440cdd --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/basic/your_first_app/6_composition.md @@ -0,0 +1,69 @@ +--- +id: composition +title: Putting it all together +--- + +The product manager had an idea: +She wants my_app to support 3 schemas on 2 different databases and 2 kinds of UI for start. More will come later. + +This is easy using config groups. Each new schema, database, or UI will add a single config file to the corresponding +config group. +Compare this to the common alternative of creating a separate config file for each combination. +The number of config files would then grow combinatorially. +Not only that, but if you wanted to make a change such as renaming `db.user` to `db.username` you would have to do it + 12 times instead of once! + +``` text title="Directory layout" +├── conf +│   ├── config.yaml +│   ├── db +│   │   ├── mysql.yaml +│   │   └── postgresql.yaml +│   ├── schema +│   │   ├── school.yaml +│   │   ├── support.yaml +│   │   └── warehouse.yaml +│   └── ui +│   ├── full.yaml +│   └── view.yaml +└── my_app.py +``` + +```yaml title="config.yaml" +defaults: + - db: mysql + - ui: full + - schema: school +``` + +The resulting configuration would be a composition of `mysql`, `full` ui and the `school` database schema (which we are seeing for the first time here): +```yaml +$ python my_app.py +db: + driver: mysql + pass: secret + user: omry +schema: + database: school + tables: + - fields: + - name: string + - class: int + name: students + - fields: + - profession: string + - time: data + - class: int + name: exams +ui: + windows: + create_db: true + view: true +``` + +### Summary + - The addition of each new db, schema, or ui only requires a single file + - Each config group can have a default specified in the `defaults` list + - Any combination can be composed by selecting the desired option from each config group in the `defaults` list or the command line. + +Stay tuned to see how to run all of the combinations automatically ([Multi-run](/tutorials/basic/6_multirun.md)). diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/intro.md b/testbed/facebookresearch__hydra/website/docs/tutorials/intro.md new file mode 100644 index 0000000000000000000000000000000000000000..df9f76eaadb7f7cd4d55a5c3a9f7f43fb8677754 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/intro.md @@ -0,0 +1,11 @@ +--- +id: intro +title: Tutorials intro +--- + +### Basic Tutorial +The [Basic Tutorial](/tutorials/basic/your_first_app/1_simple_cli.md) covers basic Hydra concepts. + +### Structured configs +The [Structured Configs Tutorial](/tutorials/structured_config/0_intro.md) shows how to create strongly typed configurations. + diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/0_intro.md b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/0_intro.md new file mode 100644 index 0000000000000000000000000000000000000000..85b6a48594779f16c877bf15673b574fd8cd172d --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/0_intro.md @@ -0,0 +1,43 @@ +--- +id: intro +title: Introduction to Structured Configs +sidebar_label: Introduction to Structured Configs +--- +This is an advanced tutorial that assumes that you are comfortable with the concepts introduced in the [Basic Tutorial](/tutorials/basic/your_first_app/1_simple_cli.md). +The examples in this tutorial are available [here](https://github.com/facebookresearch/hydra/tree/master/examples/tutorials/structured_configs). + +Structured Configs use Python [dataclasses](https://docs.python.org/3.7/library/dataclasses.html) to +describe your configuration structure and types. They enable: + +* **Runtime type checking** as you compose or mutate your config +* **Static type checking** when using static type checkers (mypy, PyCharm, etc.) + +#### Structured Configs supports: +- Primitive types (`int`, `bool`, `float`, `str`, `Enums`) +- Nesting of Structured Configs +- Containers (List and Dict) containing primitives or Structured Configs +- Optional fields + +#### Structured Configs Limitations: +- `Union` types are not supported (except `Optional`) +- User methods are not supported + +#### There are two primary patterns for using Structured configs + +- As a [config](/tutorials/structured_config/1_minimal_example.md), in place of configuration files (often a starting place) +- As a [config schema](/tutorials/structured_config/5_schema.md) validating configuration files (better for complex use cases) + +With both patterns, you still get everything Hydra has to offer (config composition, Command line overrides etc). +This tutorial covers both. \***Read it in order**\*. + +Hydra supports OmegaConf's Structured Configs via the `ConfigStore` API. +This tutorial does not assume any knowledge of them. +It is recommended that you visit the OmegaConf Structured Configs page to learn more later. + + + +
diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/10_config_store.md b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/10_config_store.md new file mode 100644 index 0000000000000000000000000000000000000000..de53a74096d4f1edebe352ee92b1ac194d650dfd --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/10_config_store.md @@ -0,0 +1,36 @@ +--- +id: config_store +title: Config Store API +--- +`ConfigStore` is a singleton storing configs in memory. +The primary API for interacting with the `ConfigStore` is the store method described below. + +```python +class ConfigStore(metaclass=Singleton): + def store( + self, + name: str, + node: Any, + group: Optional[str] = None, + package: Optional[str] = "_group_", + provider: Optional[str] = None, + ) -> None: + """ + Stores a config node into the repository + :param name: config name + :param node: config node, can be DictConfig, ListConfig, Structured configs and even dict and list + :param group: config group, subgroup separator is '/', for example hydra/launcher + :param package: Config node package + :param provider: the name of the module/app providing this config. Helps debugging. + """ + ... +``` + + +> TODO: I actually want this in the minimal example. +#### Overriding default values in the `@dataclass` +You can use instances of the dataclasses to override default values in the stored config. +```python +cs.store(name="config", node=MySQLConfig(user="root", password="1234")) +``` +If you register more than one config with the same name the last one will replace the previous ones. diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/1_minimal_example.md b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/1_minimal_example.md new file mode 100644 index 0000000000000000000000000000000000000000..b3e6990a46217bead831ea0f3d84844005519fdc --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/1_minimal_example.md @@ -0,0 +1,81 @@ +--- +id: minimal_example +title: Minimal example +--- + +There are four key elements in this example: +- A `@dataclass` describes the application's configuration +- `ConfigStore` manages the Structured Config. +- `cfg` is `duck typed` as a `MySQLConfig` instead of a `DictConfig` +- There is a subtle typo in the code, can you spot it? + +In this example, the config node stored in the `ConfigStore` replaces the traditional `config.yaml` file. + +```python title="my_app_type_error.py" {18} +from dataclasses import dataclass + +import hydra +from hydra.core.config_store import ConfigStore + +@dataclass +class MySQLConfig: + host: str = "localhost" + port: int = 3306 + +cs = ConfigStore.instance() +# Registering the Config class with the name 'config'. +cs.store(name="config", node=MySQLConfig) + +@hydra.main(config_name="config") +def my_app(cfg: MySQLConfig) -> None: + # pork should be port! + if cfg.pork == 80: + print("Is this a webserver?!") + +if __name__ == "__main__": + my_app() +``` + +### Duck-typing enables static type checking + +Duck-typing the config object as `MySQLConfig` enables static type checkers like `mypy` to catch +type errors before you run your code: +``` +$ mypy my_app_type_error.py +my_app_type_error.py:21: error: "MySQLConfig" has no attribute "pork" +Found 1 error in 1 file (checked 1 source file) +``` + +### Structured Configs enable Hydra to catch type errors at runtime. +If you forget to run `mypy`, Hydra will report the error at runtime: +``` +$ python my_app_type_error.py +Key 'pork' not in 'MySQLConfig' + full_key: pork + reference_type=Optional[MySQLConfig] + object_type=MySQLConfig +``` + +Hydra will also catch typos, or type errors in the command line: +``` +$ python my_app_type_error.py port=fail +Error merging override port=fail +Value 'fail' could not be converted to Integer + full_key: port + reference_type=Optional[MySQLConfig] + object_type=MySQLConfig +``` +We will see additional types of runtime errors that Hydra can catch later in this tutorial. Such as: +- Trying to read or write a non existent field in your config object +- Assigning a value that is incompatible with the declared type +- Attempting to modify a [frozen config](https://omegaconf.readthedocs.io/en/latest/structured_config.html#frozen) + + +## Duck typing + +In the example above `cfg` is duck typed as `MySQLConfig`. +It is actually an instance of `DictConfig`. The duck typing enables static type checking by tools like Mypy or PyCharm. +This reduces development time by catching coding errors before you run your application. + +The name [Duck typing](https://en.wikipedia.org/wiki/Duck_typing) comes from the phrase "If it walks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck". +It can be useful when you care about the methods or attributes of an object, not the actual type of the object. diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/2_nesting_configs.md b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/2_nesting_configs.md new file mode 100644 index 0000000000000000000000000000000000000000..18c7bcba67111ee7cba695beaa041a2ed232db04 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/2_nesting_configs.md @@ -0,0 +1,53 @@ +--- +id: nesting +title: Nesting configs +--- +Configs can be nested using several different methods. + +### Nesting using a dataclass definition +This is the preferred approach; use it when possible. +There are two things of note in this example: +- A top level `MyConfig` class defined and stored in the `ConfigStore` +- The `cfg` object in `my_app` is annotated as the top level `MyConfig` class, providing static type safety for +the entire configuration tree + +```python +@dataclass +class MySQLConfig: + host: str = "localhost" + port: int = 3306 + +@dataclass +class MyConfig: + db: MySQLConfig = MySQLConfig() + +cs = ConfigStore.instance() +cs.store(name="config", node=MyConfig) + +@hydra.main(config_name="config") +def my_app(cfg: MyConfig) -> None: + # Python knows that the type of cfg.db is MySQLConfig without any additional hints + print(f"Host: {cfg.db.host}, port: {cfg.db.port}") + +if __name__ == "__main__": + my_app() +``` + +### Nesting by creating an ad-hoc config node +Ad-hoc config nodes can be created using Dictionaries. While this +allows great flexibility, it offers reduced type safety. + +```python +cfg_store.store( + name="config", + node={ + "src": MySQLConfig(host="localhost"), + "dst": MySQLConfig(host="example.com"), + }, +) + + +@hydra.main(config_name="config") +def my_app(cfg: DictConfig) -> None: + print(f"Copying {cfg.src.host}:{cfg.src.port} to {cfg.dst.host}:{cfg.dst.port}") +``` diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/3_config_groups.md b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/3_config_groups.md new file mode 100644 index 0000000000000000000000000000000000000000..6cbf082e1ad7dd9b50d5527b3982e4ef6c20081f --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/3_config_groups.md @@ -0,0 +1,114 @@ +--- +id: config_groups +title: Config Groups +--- +Structured Configs support config groups which are similar to file-based config groups. +The config options in config groups can be used as building blocks when composing the output config object. +One difference is that Structured Configs introduce runtime type safety which ensures that the resulting config object +adheres to the declared types. + +This example adds `mysql` and `postgresql` configs into the Config Group `db`. +Like with config files, the configs in the `ConfigStore` acts as building blocks to be used when composing the +output config object. + +The type of variable `db` in the `Config` is `Any`. This allows both `MySQLConfig` and `PostGreSQLConfig` +to be merged into it despite them not having a common superclass. + +```python +@dataclass +class MySQLConfig: + driver: str = "mysql" + host: str = "localhost" + port: int = 3306 + +@dataclass +class PostGreSQLConfig: + driver: str = "postgresql" + host: str = "localhost" + port: int = 5432 + timeout: int = 10 + +# Config is extending DictConfig to allow type safe access to the pretty() function below +@dataclass +class Config(DictConfig): + db: Any = MISSING + +cs = ConfigStore.instance() +cs.store(name="config", node=Config) +cs.store(group="db", name="mysql", node=MySQLConfig) +cs.store(group="db", name="postgresql", node=PostGreSQLConfig) + +@hydra.main(config_name="config") +def my_app(cfg: Config) -> None: + print(cfg.pretty()) +``` +You can select the database from the command line: +```yaml +$ python my_app.py +db=postgresql +db: + driver: postgresql + host: localhost + password: drowssap + port: 5432 + timeout: 10 + user: postgre_user +``` + +#### Config inheritance +We can improve on the above example by modeling the configuration with inheritance. +Noteworthy things in the example: +- We can move fields to the top level class, reducing repetition of field names, type and default values. +- The type of the `db` field in `Config` is `DBConfig`. This ensures that only subclasses of `DBConfig` +can be merged into db. +- We can use OmegaConf.get_type() to obtain the underlying type, and cast() to coerce the type checker to accept it. + +```python +@dataclass +class DBConfig: + host: str = "localhost" + port: int = MISSING + driver: str = MISSING + +@dataclass +class MySQLConfig(DBConfig): + driver = "mysql" + port = 3306 + +@dataclass +class PostGreSQLConfig(DBConfig): + driver = "postgresql" + port = 5432 + timeout: int = 10 + +@dataclass +class Config(DictConfig): + db: DBConfig = MISSING + +cs = ConfigStore.instance() +cs.store(name="config", node=Config) +cs.store(group="db", name="mysql", node=MySQLConfig) +cs.store(group="db", name="postgresql", node=PostGreSQLConfig) + +def connect_mysql(cfg: MySQLConfig) -> None: + print(f"Connecting to MySQL: {cfg.host}:{cfg.port}") + +def connect_postgresql(cfg: PostGreSQLConfig) -> None: + print(f"Connecting to PostGreSQL: {cfg.host}:{cfg.port} (timeout={cfg.timeout})") + +@hydra.main(config_name="config") +def my_app(cfg: Config) -> None: + # Remember that the actual type of Config and db inside it is DictConfig. + # If you need to get the underlying type of a config object use OmegaConf.get_type: + if OmegaConf.get_type(cfg.db) is MySQLConfig: + connect_mysql(cast(MySQLConfig, cfg.db)) + elif OmegaConf.get_type(cfg.db) is PostGreSQLConfig: + connect_postgresql(cast(PostGreSQLConfig, cfg.db)) + else: + raise ValueError() +``` + +Example output: +``` +$ python my_app_with_inheritance.py +db=postgresql +Connecting to PostGreSQL: localhost:5432 (timeout=10) +``` \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/4_defaults.md b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/4_defaults.md new file mode 100644 index 0000000000000000000000000000000000000000..4ac325ae47b0ef16b36da64cdc734e71767dd1bb --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/4_defaults.md @@ -0,0 +1,59 @@ +--- +id: defaults +title: Defaults +--- + +You can define a defaults list in your primary config just like you can in your primary config file. +The example below extends the previous example by adding a defaults list that will load db=mysql by default. + +```python +@dataclass +class MySQLConfig: + ... + +@dataclass +class PostGreSQLConfig: + ... + +defaults = [ + # Load the config "mysql" from the config group "database" + {"database": "mysql"} +] + +@dataclass +class Config(DictConfig): + # this is unfortunately verbose due to @dataclass limitations + defaults: List[Any] = field(default_factory=lambda: defaults) + + # Hydra will populate this field based on the defaults list + db: Any = MISSING + +cs = ConfigStore.instance() +cs.store(group="db", name="mysql", node=MySQLConfig) +cs.store(group="db", name="postgresql", node=PostGreSQLConfig) +cs.store(name="config", node=Config) + + +@hydra.main(config_name="config") +def my_app(cfg: Config) -> None: + print(cfg.pretty()) + + +if __name__ == "__main__": + my_app() +``` +Running `my_app.py` loads the mysql config option by default: +```yaml +$ python my_app.py +db: + driver: mysql + ... +``` + +You can override the default option via the command line: +```yaml +$ python my_app.py db=postgresql +db: + driver: postgresql + ... +``` \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/5_schema.md b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/5_schema.md new file mode 100644 index 0000000000000000000000000000000000000000..7afc74c68299991379ee8fd36b46b9e3d900bca2 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/tutorials/structured_config/5_schema.md @@ -0,0 +1,74 @@ +--- +id: schema +title: Structured config schema +--- +We have seen how to use Structured Configs as configuration, but they can also be used as a schema validating configuration files! +When Hydra loads a configuration, it looks for config with the same name in the `ConfigStore`. +If found, it is used as the schema for the newly loaded config. + +This is an example of defining and stores one schema for db/mysql and another for db/postgresql. + +Given a config directory structure like: +```text +$ tree conf/ +conf/ +├── config.yaml +└── db + ├── mysql.yaml + └── postgresql.yaml +``` + +The Structurd Configs below are stored as db/mysql and db/postgresql. They will be used as schema +when we load the corresponding config files. + +```python +@dataclass +class DBConfig: + driver: str = MISSING + host: str = "localhost" + port: int = MISSING + + +@dataclass +class MySQLConfig(DBConfig): + driver: str = "mysql" + port: int = 3306 + user: str = MISSING + password: str = MISSING + + +@dataclass +class PostGreSQLConfig(DBConfig): + driver: str = "postgresql" + port: int = 5432 + user: str = MISSING + password: str = MISSING + timeout: int = 10 + + +# registering db/mysql and db/postgresql schemas. +ss = ConfigStore.instance() +ss.store(group="db", name="mysql", node=MySQLConfig) +ss.store(group="db", name="postgresql", node=PostGreSQLConfig) + + +# config here is config.yaml under the conf directory. +# config.yaml will compose in db: mysql by default (per the defaults list), +# and it will be validated against the schema +@hydra.main(config_path="conf", config_name="config") +def my_app(cfg: DictConfig) -> None: + ... +``` + + +When `db/mysql.yaml` and `db/postgresql.yaml` are loaded, the corresponding configs from the `ConfigStore` are used automatically. +This can be used to validate that both the configuration files (`mysql.yaml` and `postgresql.yaml`) and the command line overrides are conforming to the schema. + +``` +$ python my_app.py db.port=fail +Error merging override db.port=fail +Value 'fail' could not be converted to Integer + full_key: db.port + reference_type=Optional[MySQLConfig] + object_type=MySQLConfig +``` \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/adding_a_package_directive.md b/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/adding_a_package_directive.md new file mode 100644 index 0000000000000000000000000000000000000000..68a5bf72773ffa1c18a9880e25ceb2d81dbb320c --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/adding_a_package_directive.md @@ -0,0 +1,59 @@ +--- +id: adding_a_package_directive +title: Adding an @package directive +--- +Hydra 1.0 introduces the concept of a config `package`. A `package` is the common parent +path of all nodes in the config file. + + - In Hydra 0.11, there was an implicit default of `_global_` ("") + - In Hydra 1.1 the default will be `_group_` (the name of the config group). + - Hydra 1.0 maintains the implicit default of `_global_` and issues a warning for +any config group file without a `@package` directive. + +By adding an explicit `@package` to these configs now, you guarantee that your configs +will not break when you upgrade to Hydra 1.1. + +The `@package` directive is described in details [here](/advanced/overriding_packages.md). + +## Upgrade instructions: +### Recommended (~10 seconds per config file): +`Case 1`: For config files where the common parent path matches the config group name: + - Add `# @package _group_` to the top of every config group file + - Remove the common parent path config file like in the example below. + +`Case 2`: For files without a common parent path: + - Add `# @package _global_`. + +### Alternative (not recommended): + - If you do not want to restructure the config at this time use `Case 2` for all your config files. + +### Example for `case 1`: + +#### Before +```yaml title="db/mysql.yaml" +db: + driver: mysql + host: localhost + port: 3306 +``` +#### After +```yaml title="db/mysql.yaml" +# @package _group_ +driver: mysql +host: localhost +port: 3306 +``` +The interpretations of the before and after files are identical. + +### Example for `case 2`: +```yaml title="env/prod.yaml" +# @package _global_ +db: + driver: mysql + host: 10.0.0.11 + port: 3306 + +webserver: + host: 10.0.0.11 + port: 443 +``` diff --git a/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/config_path_changes.md b/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/config_path_changes.md new file mode 100644 index 0000000000000000000000000000000000000000..fe7a72f7d00a68da50b13cd037a8a91742be7a29 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/config_path_changes.md @@ -0,0 +1,42 @@ +--- +id: config_path_changes +title: Config path changes +--- + +## Overview +Hydra 1.0 changes a new `config_name` parameter to `@hydra.main()` and changes the meaning of the `config_path`. +Previously, `config_path` encapsulated two things: +- Search path relative to the declaring python file. +- Optional config file (.yaml) to load. + +Having both of those things in the same parameter does not work well if you consider configs that are not files +such as Structured Configs. In addition, it prevents overriding just the `config_name` or just the `config_path` + +A second change is that the `config_name` no longer requires a file extension. For configs files the `.yaml` extension +will be added automatically when the file is loaded. + +This change is backward compatible, but support for the old style is deprecated and will be removed in the next major Hydra version. + +## Migration examples + +```python +# old +@hydra.main(config_path="config.yaml") +``` +Becomes: +```python +# new +@hydra.main(config_name="config") +``` + +And +```python +# old +@hydra.main(config_path="conf/config.yaml") +``` + +Becomes: +```python +# new +@hydra.main(config_path="conf", config_name="config") +``` diff --git a/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/strict_mode_flag_deprecated.md b/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/strict_mode_flag_deprecated.md new file mode 100644 index 0000000000000000000000000000000000000000..19f1ba7d6e822e2023a338cd7b4674c134db913a --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docs/upgrades/0.11_to_1.0/strict_mode_flag_deprecated.md @@ -0,0 +1,54 @@ +--- +id: strict_mode_flag_deprecated +title: strict flag mode deprecation +--- +## Overview +The strict mode is a flag added to `@hydra.main()` to enable two features: +- Command line error detection (overriding a field not in the config) +- Runtime config access error detection (accessing/setting a field not in the config) + +This flag is now deprecated and the ability to turn it off will be removed in Hydra 1.1. + +## Alternatives to `strict=False` +Below are a few common reasons for people disabling strict mode along with recommended alternatives. + +### Adding config fields through the command line +With strict mode disabled; you can add fields not specified in config file through the command line. +Hydra 1.0 introduces the + prefix to command line overrides, enabling the addition of fields not in the config file. + +```yaml title="config.yaml" +db: + driver: mysql +``` + +```yaml {1,6} +$ python my_app.py +db.host=localhost +db: + driver: mysql + host: localhost +``` + +### Adding fields at runtime +When strict mode is disabled, you can add fields to your config at runtime. +Strict mode is implemented by setting the OmegaConf `struct` flag to True on the root of the config. +- You can disable the struct flag a specific context using `open_dict`. +- You can disable the struct flag permanently for your config using `OmegaConf.set_struct(cfg, False)`. + +Learn more about OmegaConf struct flag here. + + +### Field existence check +With strict mode disabled, you can check if a field is in the config by comparing it to None: +```python +if cfg.host is None: + # host is not in the config +``` +This will no longer work because an exception will be thrown when the `host` field is accessed. +Use `in` or `hasattr` instead: +```python +if "host" not in cfg: + # host is not in the config + +if not hasattr(cfg, "host"): + # host is not in the config +``` \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/docusaurus.config.js b/testbed/facebookresearch__hydra/website/docusaurus.config.js new file mode 100644 index 0000000000000000000000000000000000000000..aca81388b039a2bc25b54e6391c85a0de680e96d --- /dev/null +++ b/testbed/facebookresearch__hydra/website/docusaurus.config.js @@ -0,0 +1,107 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +module.exports = { + title: 'Hydra', + tagline: 'A framework for elegantly configuring complex applications', + url: 'https://hydra.cc', + baseUrl: '/', + favicon: 'img/Hydra-head.svg', + organizationName: 'facebookresearch', // Usually your GitHub org/user name. + projectName: 'hydra', // Usually your repo name. + plugins: [require.resolve('docusaurus-plugin-internaldocs-fb')], + themeConfig: { + googleAnalytics: { + trackingID: 'UA-149862507-1', + }, + algolia: { + apiKey: '8e04f3376c4e6e060f9d8d56734fa67b', + indexName: 'hydra', + algoliaOptions: {}, + }, + navbar: { + title: 'Hydra', + logo: { + alt: 'Hydra logo', + src: 'img/logo.svg', + }, + links: [ + {to: 'docs/intro', label: 'Docs', position: 'left'}, + {to: 'versions', label: 'Versions', position: 'left'}, + {to: 'blog', label: 'Blog', position: 'left'}, + {to: 'https://github.com/facebookresearch/hydra', label: 'Hydra@GitHub', position: 'left'}, + ], + }, + footer: { + style: 'dark', + links: [ + { + title: "Links", + items: [ + { + label: 'Blog', + to: 'Blog' + }, + { + label: 'Docs', + to: 'docs/intro' + }, + { + label: 'Hydra@GitHub', + to: 'https://github.com/facebookresearch/hydra', + }, + { + label: 'Powered by OmegaConf', + to: 'https://github.com/omry/omegaconf', + }, + ], + }, + { + title: 'Legal', + // Please do not remove the privacy and terms, it's a legal requirement. + items: [ + { + label: 'Privacy', + href: 'https://opensource.facebook.com/legal/privacy/', + target: '_blank', + rel: 'noreferrer noopener', + }, + { + label: 'Terms', + href: 'https://opensource.facebook.com/legal/terms/', + target: '_blank', + rel: 'noreferrer noopener', + }, + ], + }, + ], + + + logo: { + alt: 'Facebook Open Source Logo', + src: 'https://docusaurus.io/img/oss_logo.png', + }, + copyright: `Copyright © ${new Date().getFullYear()} Facebook, Inc.`, + }, + }, + presets: [ + [ + '@docusaurus/preset-classic', + { + docs: { + sidebarPath: require.resolve('./sidebars.js'), + showLastUpdateAuthor: true, + showLastUpdateTime: true, + editUrl: 'https://github.com/facebookresearch/hydra/edit/master/website/', + }, + theme: { + customCss: require.resolve('./src/css/custom.css'), + }, + }, + ], + ], +}; diff --git a/testbed/facebookresearch__hydra/website/package.json b/testbed/facebookresearch__hydra/website/package.json new file mode 100644 index 0000000000000000000000000000000000000000..378462109a69e0b5f5aa72a0370b52695a2ff2f8 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/package.json @@ -0,0 +1,32 @@ +{ + "name": "website", + "version": "0.0.0", + "private": true, + "scripts": { + "docusaurus": "docusaurus", + "start": "docusaurus start", + "build": "docusaurus build", + "swizzle": "docusaurus swizzle", + "deploy": "docusaurus deploy" + }, + "dependencies": { + "@docusaurus/core": "^2.0.0-alpha.56", + "@docusaurus/preset-classic": "^2.0.0-alpha.56", + "classnames": "^2.2.6", + "docusaurus-plugin-internaldocs-fb": "^0.3.3", + "react": "^16.8.4", + "react-dom": "^16.8.4" + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/testbed/facebookresearch__hydra/website/sidebars.js b/testbed/facebookresearch__hydra/website/sidebars.js new file mode 100644 index 0000000000000000000000000000000000000000..dad4b1dc123a36f4cdd6aaf37028b475a6034bd9 --- /dev/null +++ b/testbed/facebookresearch__hydra/website/sidebars.js @@ -0,0 +1,120 @@ +// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved + +function FBInternalOnly(elements) { + return process.env.FB_INTERNAL ? elements : []; +} + +module.exports = { + Docs: { + About: [ + 'intro', + 'terminology', + ], + Tutorials: [ + 'tutorials/intro', + { + type: 'category', + label: 'Basic Tutorial', + items: [ + { + type: 'category', + label: 'Your first Hydra app', + items: [ + 'tutorials/basic/your_first_app/simple_cli', + 'tutorials/basic/your_first_app/config_file', + 'tutorials/basic/your_first_app/using_config', + 'tutorials/basic/your_first_app/config_groups', + 'tutorials/basic/your_first_app/defaults', + 'tutorials/basic/your_first_app/composition', + ] + }, + { + type: 'category', + label: 'Running your Hydra app', + items: [ + 'tutorials/basic/running_your_app/multi-run', + 'tutorials/basic/running_your_app/working_directory', + 'tutorials/basic/running_your_app/logging', + 'tutorials/basic/running_your_app/debugging', + 'tutorials/basic/running_your_app/tab_completion', + ] + }, + + ], + }, + + { + type: 'category', + label: 'Structured Configs Tutorial', + items: [ + 'tutorials/structured_config/intro', + 'tutorials/structured_config/minimal_example', + 'tutorials/structured_config/nesting', + 'tutorials/structured_config/config_groups', + 'tutorials/structured_config/defaults', + 'tutorials/structured_config/schema', + 'tutorials/structured_config/config_store', + ], + }, + ], + + 'Common Patterns': [ + 'patterns/objects', + 'patterns/specializing_config', + ], + + 'Configuring Hydra': [ + 'configure_hydra/intro', + 'configure_hydra/job', + 'configure_hydra/logging', + 'configure_hydra/workdir', + 'configure_hydra/app_help', + ], + + 'Plugins': [ + 'plugins/ax_sweeper', + 'plugins/colorlog', + 'plugins/joblib_launcher', + 'plugins/nevergrad_sweeper', + 'plugins/submitit_launcher', + ], + + 'Advanced': [ + 'advanced/overriding_packages', + 'advanced/command_line_overrides', + 'advanced/search_path', + 'advanced/plugins', + 'advanced/app_packaging', + ], + + "Experimental": [ + "experimental/intro", + 'experimental/compose_api', + 'experimental/ray_example', + ], + + 'Development': [ + 'development/contributing', + 'development/release', + ], + + Upgrades: [ + { + type: 'category', + label: '0.11 to 1.0', + items: [ + 'upgrades/0.11_to_1.0/config_path_changes', + 'upgrades/0.11_to_1.0/adding_a_package_directive', + 'upgrades/0.11_to_1.0/strict_mode_flag_deprecated', + ], + }, + ], + + 'FB Only': FBInternalOnly([ + 'fb/intro', + 'fb/fbcode', + 'fb/internal-fb-cluster', + 'fb/fair-cluster', + ]), + } +} diff --git a/testbed/facebookresearch__hydra/website/src/components/Script.jsx b/testbed/facebookresearch__hydra/website/src/components/Script.jsx new file mode 100644 index 0000000000000000000000000000000000000000..b20238f371c042f90f5c883266dd43ce91f82a7d --- /dev/null +++ b/testbed/facebookresearch__hydra/website/src/components/Script.jsx @@ -0,0 +1,29 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import React, {useEffect, useRef} from 'react'; + +export default function Script(props) { + const instance = useRef(null); + const script = useRef( + typeof document !== 'undefined' ? document.createElement('script') : null, + ); + + useEffect(() => { + instance.current.appendChild(script.current); + }, []); + + useEffect(() => { + for (const key in props) { + if (props.hasOwnProperty(key)) { + script.current[key] = props[key]; + } + } + }); + + return
; +} \ No newline at end of file diff --git a/testbed/facebookresearch__hydra/website/src/css/custom.css b/testbed/facebookresearch__hydra/website/src/css/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..aecbf6d4656507e15f8a69f55aea7abb0a945dec --- /dev/null +++ b/testbed/facebookresearch__hydra/website/src/css/custom.css @@ -0,0 +1,54 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Any CSS included here will be global. The classic template + * bundles Infima by default. Infima is a CSS framework designed to + * work well for content-centric websites. + */ + +/* You can override the default Infima variables here. */ +:root { + --ifm-color-primary: #89B8CD; + --ifm-color-primary-dark: rgb(33, 175, 144); + --ifm-color-primary-darker: rgb(31, 165, 136); + --ifm-color-primary-darkest: rgb(26, 136, 112); + --ifm-color-primary-light: rgb(70, 203, 174); + --ifm-color-primary-lighter: rgb(102, 212, 189); + --ifm-color-primary-lightest: rgb(146, 224, 208); +} + +.hero { + padding: 0; +} + +.hero .hero__title { + font-size: 6.5rem; + margin: 0 0 0.15em; + line-height: 1; +} + +.hero .hero__subtitle { + font-weight: 500; + line-height: 1.2; + opacity: .9;; + margin-bottom: 30px; + color: #276475; +} + +.docusaurus-highlight-code-line { + background-color: rgb(72, 77, 91); + display: block; + margin: 0 calc(-1 * var(--ifm-pre-padding)); + padding: 0 var(--ifm-pre-padding); +} + +/* If you have a different syntax highlighting theme for dark mode. */ +html[data-theme='dark'] .docusaurus-highlight-code-line { + background-color: /* Color which works with dark mode syntax highlighting theme */ +} + diff --git a/testbed/facebookresearch__hydra/website/src/pages/index.js b/testbed/facebookresearch__hydra/website/src/pages/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4486c473a452b7b4c601e63d0415b7015ebfe24f --- /dev/null +++ b/testbed/facebookresearch__hydra/website/src/pages/index.js @@ -0,0 +1,123 @@ +/** + * Copyright (c) 2017-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import React from 'react'; +import classnames from 'classnames'; +import Layout from '@theme/Layout'; +import Link from '@docusaurus/Link'; +import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; +import useBaseUrl from '@docusaurus/useBaseUrl'; +import styles from './styles.module.css'; + +const features = [ + { + title: <>No boilerplate, + imageUrl: 'img/undraw_site_content_hydra_plain.svg', + description: ( + <> + Hydra lets you focus on the problem at hand instead of spending time on boilerplate code like command line flags, loading configuration files, logging etc. + + ), + }, + { + title: <>Powerful configuration, + imageUrl: 'img/undraw_product_teardown_hydra_plain.svg', + description: ( + <> + With Hydra, you can compose your configuration dynamically, enabling you to easily + get the perfect configuration for each run. + You can override everything from the command line, which makes experimentation fast, and removes the need to maintain multiple similar configuration files. + + ), + }, + { + title: <>Pluggable architecture, + imageUrl: 'img/Hydra-plugins.svg', + description: ( + <> + Hydra has a pluggable architecture, enabling it to integrate with your infrastructure. + Future plugins will enable launching your code on AWS or other cloud providers directly from the command line. + + ), + }, +]; + +function Home() { + const context = useDocusaurusContext(); + const {siteConfig = {}} = context; + return ( + +
+
+ {/* Left */} +
+
+
+ {/* Right */} +
+

{siteConfig.title}

+

{siteConfig.tagline}

+
+
+ + Get Started + + +