Nest - A flexible tool for building and sharing deep learning modules

Overview

Nest - A flexible tool for building and sharing deep learning modules

Nest is a flexible deep learning module manager, which aims at encouraging code reuse and sharing. It ships with a bunch of useful features, such as CLI based module management, runtime checking, and experimental task runner, etc. You can integrate Nest with PyTorch, Tensorflow, MXNet, or any deep learning framework you like that provides a python interface.

Moreover, a set of Pytorch-backend Nest modules, e.g., network trainer, data loader, optimizer, dataset, visdom logging, are already provided. More modules and framework support will be added later.


Prerequisites

  • System (tested on Ubuntu 14.04LTS, Win10, and MacOS High Sierra)
  • Python >= 3.5.4
  • Git

Installation

# directly install via pip
pip install git+https://github.com/ZhouYanzhao/Nest.git

# manually download and install
git clone https://github.com/ZhouYanzhao/Nest.git
pip install ./Nest

Basic Usage

The official website and documentation are under construction.

Create your first Nest module

  1. Create "hello.py" under your current path with the following content:

    from nest import register
    
    @register(author='Yanzhao', version='1.0.0')
    def hello_nest(name: str) -> str:
        """My first Nest module!"""
    
        return 'Hello ' + name

    Note that the type of module parameters and return values must be clearly defined. This helps the user to better understand the module, and at runtime Nest automatically checks whether each module receives and outputs as expected, thus helping you to identify potential bugs earlier.

  2. Execute the following command in your shell to verify the module:

    str # Documentation: # My first Nest module! # author: Yanzhao # module_path: /Users/yanzhao/Workspace/Nest.doc # version: 1.0.0 ">
    $ nest module list -v
    # Output:
    # 
    # 1 Nest module found.
    # [0] main.hello_nest (1.0.0) by "Yanzhao":
    #     hello_nest(
    #         name:str) -> str
    
    # Documentation:
    #     My first Nest module!
    #     author: Yanzhao
    #     module_path: /Users/yanzhao/Workspace/Nest.doc
    #     version: 1.0.0 

    Note that all modules under current path are registered under the "main" namespace.

    With the CLI tool, you can easily manage Nest modules. Execute nest -h for more details.

  3. That's it. You just created a simple Nest module!

Use your Nest module in Python

  1. Open an interactive python interpreter under the same path of "hello.py" and run following commands:

    >> modules.hello_nest('Yanzhao', wrong=True) # Output: # # Unexpected param(s) "wrong" for Nest module: # hello_nest( # name:str) -> str ">
    >>> from nest import modules
    >>> print(modules.hello_nest) # access the module
    # Output:
    # 
    # hello_nest(
    # name:str) -> str
    >>> print(modules['*_nes?']) # wildcard search
    # Output:
    # 
    # hello_nest(
    # name:str) -> str
    >>> print(modules['r/main.\w+_nest']) # regex search
    # Output:
    # 
    # hello_nest(
    # name:str) -> str
    >>> modules.hello_nest('Yanzhao') # use the module
    # Output:
    #
    # 'Hello Yanzhao'
    >>> modules.hello_nest(123) # runtime type checking
    # Output:
    #
    # TypeError: The param "name" of Nest module "hello_nest" should be type of "str". Got "123".
    >>> modules.hello_nest('Yanzhao', wrong=True)
    # Output:
    #
    # Unexpected param(s) "wrong" for Nest module:
    # hello_nest(
    # name:str) -> str

    Note that Nest automatically imports modules and checks them as they are used to make sure everything is as expected.

  2. You can also directly import modules like this:

    >>> from nest.main.hello import hello_nest
    >>> hello_nest('World')
    # Output:
    #
    # 'Hello World'

    The import syntax is from nest. . import

  3. Access to Nest modules through code is flexible and easy.

Debug your Nest modules

  1. Open an interactive python interpreter under the same path of "hello.py" and run following commands:

    >>> from nest import modules
    >>> modules.hello_nest('Yanzhao')
    # Output:
    #
    # 'Hello Yanzhao'
  2. Keep the interpreter OPEN and use an externel editor to modify the "hello.py":

    # change Line7 from "return 'Hello ' + name" to
    return 'Nice to meet you, ' + name
  3. Back to the interpreter and rerun the same command:

    >>> modules.hello_nest('Yanzhao')
    # Output:
    #
    # 'Nice to meet you, Yanzhao'

    Note that Nest detects source file modifications and automatically reloads the module.

  4. You can use this feature to develop and debug your Nest modules efficiently.

Install Nest modules from local path

  1. Create a folder my_namespace and move the hello.py into it:

    $ mkdir my_namespace
    $ mv hello.py ./my_namespace/
  2. Create a new file more.py under the folder my_namespace with the following content:

    float: """Multiply two numbers.""" return a * b ">
    from nest import register
    
    @register(author='Yanzhao', version='1.0.0')
    def sum(a: int, b: int) -> int:
        """Sum two numbers."""
    
        return a + b
    
    # There is no need to repeatedly declare meta information
    # as modules within the same file automatically reuse the 
    # previous information. But overriding is also supported.
    @register(version='2.0.0')
    def mul(a: float, b: float) -> float:
        """Multiply two numbers."""
        
        return a * b

    Now we have:

    current path/
    ├── my_namespace/
    │   ├── hello.py
    │   ├── more.py
    
  3. Run the following command in the shell:

    Search paths. Continue? (Y/n) [Press ] ">
    $ nest module install ./my_namespace hello_word
    # Output:
    #
    # Install "./my_namespace/" -> Search paths. Continue? (Y/n) [Press 
          
           ]
          

    This command will add "my_namespace" folder to Nest's search path, and register all Nest modules in it under the namespace "hello_word". If the last argument is omitted, the directory name, "my_namespace" in this case, is used as the namespace.

  4. Verify the installation via CLI:

    $ nest module list
    # Output:
    #
    # 3 Nest modules found.
    # [0] hello_world.hello_nest (1.0.0)
    # [1] hello_world.mul (2.0.0)
    # [2] hello_world.sum (1.0.0)

    Note that those Nest modules can now be accessed regardless of your working path.

  5. Verify the installation via Python interpreter:

    $ ipython # open IPython interpreter
    >>> from nest import modules
    >>> print(len(modules))
    # Output:
    #
    # 3
    >>> modules.[Press <Tab>] # IPython Auto-completion
    # Output:
    #
    # hello_nest
    # mul
    # sum
    >>> modules.sum(3, 2)
    # Output:
    #
    # 5
    >>> modules.mul(2.5, 4.0)
    # Output:
    #
    # 10.0
  6. Thanks to the auto-import feature of Nest, you can easily share modules between different local projects.

Install Nest modules from URL

  1. You can use the CLI tool to install modules from URL:

    # select one of the following commands to execute
    # 0. install from Github repo via short URL (GitLab, Bitbucket are also supported)
    $ nest module install github@ZhouYanzhao/Nest:pytorch pytorch
    # 1. install from Git repo
    $ nest module install "-b pytorch https://github.com/ZhouYanzhao/Nest.git" pytorch
    # 2. install from zip file URL
    $ nest module install "https://github.com/ZhouYanzhao/Nest/archive/pytorch.zip" pytorch

    The last optional argument is used to specify the namespace, "pytorch" in this case.

  2. Verify the installation:

    $ nest module list
    # Output:
    #
    # 26 Nest modules found.
    # [0] hello_world.hello_nest (1.0.0)
    # [1] hello_world.mul (2.0.0)
    # [2] hello_world.sum (1.0.0)
    # [3] pytorch.adadelta_optimizer (0.1.0)
    # [4] pytorch.checkpoint (0.1.0)
    # [5] pytorch.cross_entropy_loss (0.1.0)
    # [6] pytorch.fetch_data (0.1.0)
    # [7] pytorch.finetune (0.1.0)
    # [8] pytorch.image_transform (0.1.0)
    # ...

Uninstall Nest modules

  1. You can remove modules from Nest's search path by executing:

    # given namespace
    $ nest module remove hello_world
    # given path to the namespace
    $ nest module remove ./my_namespace/
  2. You can also delete the corresponding files by appending a --delete or -d flag:

    $ nest module remove hello_world --delete

Version control Nest modules

  1. When installing modules, Nest adds the namespace to its search path without modifying or moving the original files. So you can use any version control system you like, e.g., Git, to manage modules. For example:

    $ cd <path of the namespace>
    # update modules
    $ git pull
    # specify version
    $ git checkout v1.0
  2. When developing a Nest module, it is recommended to define meta information for the module, such as the author, version, requirements, etc. Those information will be used by Nest's CLI tool. There are two ways to set meta information:

    • define meta information in code
    from nest import register
    
    @register(author='Yanzhao', version='1.0')
    def my_module() -> None:
        """My Module"""
        pass
    • define meta information in a nest.yml under the path of namespace
    author: Yanzhao
    version: 1.0
    requirements:
        - {url: opencv, tool: conda}
        # default tool is pip
        - torch>=0.4

    Note that you can use both ways at the same time.

Use Nest to manage your experiments

  1. Make sure you have Pytorch-backend modules installed, and if not, execute the following command:

    $ nest module install github@ZhouYanzhao/Nest:pytorch pytorch
  2. Create "train_mnist.yml" with the following content:

    _name: network_trainer
    data_loaders:
      _name: fetch_data
      dataset: 
        _name: mnist
        data_dir: ./data
      batch_size: 128
      num_workers: 4
      transform:
        _name: image_transform
        image_size: 28
        mean: [0.1307]
        std: [0.3081]
      train_splits: [train]
      test_splits: [test]
    model:
      _name: lenet5
    criterion:
      _name: cross_entropy_loss
    optimizer:
      _name: adadelta_optimizer
    meters:
      top1:
        _name: topk_meter
        k: 1
    max_epoch: 10
    device: cpu
    hooks:
      on_end_epoch: 
        - 
          _name: print_state
          formats:
            - 'epoch: {epoch_idx}'
            - 'train_acc: {metrics[train_top1]:.1f}%'
            - 'test_acc: {metrics[test_top1]:.1f}%'   

    Check HERE for more comprehensive demos.

  3. Run your experiments through CLI:

    $ nest task run ./train_mnist.yml
  4. You can also use Nest's task runner in your code:

    >>> from nest import run_tasks
    >>> run_tasks('./train_mnist.yml')
  5. Based on the task runner feature, Nest modules can be flexibly replaced and assembled to create your desired experiment settings.

Contact

Yanzhao Zhou

Issues

Feel free to submit bug reports and feature requests.

Contribution

Pull requests are welcome.

License

MIT

Copyright © 2018-present, Yanzhao Zhou

You might also like...
A flexible framework of neural networks for deep learning
A flexible framework of neural networks for deep learning

Chainer: A deep learning framework Website | Docs | Install Guide | Tutorials (ja) | Examples (Official, External) | Concepts | ChainerX Forum (en, ja

Open source implementation of AceNAS: Learning to Rank Ace Neural Architectures with Weak Supervision of Weight Sharing

AceNAS This repo is the experiment code of AceNAS, and is not considered as an official release. We are working on integrating AceNAS as a built-in st

A multi-functional library for full-stack Deep Learning. Simplifies Model Building, API development, and Model Deployment.
A multi-functional library for full-stack Deep Learning. Simplifies Model Building, API development, and Model Deployment.

chitra What is chitra? chitra (चित्र) is a multi-functional library for full-stack Deep Learning. It simplifies Model Building, API development, and M

A library of extension and helper modules for Python's data analysis and machine learning libraries.
A library of extension and helper modules for Python's data analysis and machine learning libraries.

Mlxtend (machine learning extensions) is a Python library of useful tools for the day-to-day data science tasks. Sebastian Raschka 2014-2020 Links Doc

Official code for paper
Official code for paper "Demystifying Local Vision Transformer: Sparse Connectivity, Weight Sharing, and Dynamic Weight"

Demysitifing Local Vision Transformer, arxiv This is the official PyTorch implementation of our paper. We simply replace local self attention by (dyna

Implementation of Bidirectional Recurrent Independent Mechanisms (Learning to Combine Top-Down and Bottom-Up Signals in Recurrent Neural Networks with Attention over Modules)

BRIMs Bidirectional Recurrent Independent Mechanisms Implementation of the paper Learning to Combine Top-Down and Bottom-Up Signals in Recurrent Neura

PyTorch implementation of
PyTorch implementation of "Efficient Neural Architecture Search via Parameters Sharing"

Efficient Neural Architecture Search (ENAS) in PyTorch PyTorch implementation of Efficient Neural Architecture Search via Parameters Sharing. ENAS red

[ICCV 2021] Official Tensorflow Implementation for
[ICCV 2021] Official Tensorflow Implementation for "Single Image Defocus Deblurring Using Kernel-Sharing Parallel Atrous Convolutions"

KPAC: Kernel-Sharing Parallel Atrous Convolutional block This repository contains the official Tensorflow implementation of the following paper: Singl

DI-HPC is an acceleration operator component for general algorithm modules in reinforcement learning algorithms

DI-HPC: Decision Intelligence - High Performance Computation DI-HPC is an acceleration operator component for general algorithm modules in reinforceme

Comments
  • CLI module list error

    CLI module list error

    Originally reported by @doudoubilly.

    Execute " nest module list --filter prm" and get the following result.(Ubuntu16)

    (pt-py3) root@ebe535e9a1a8:~# nest module list --filter prm Traceback (most recent call last): File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 346, in _import_nest_modules_from_file spec.loader.exec_module(py_module) File "", line 665, in exec_module File "", line 222, in _call_with_frames_removed File "/root/PRM/install/prm.py", line 30, in filter_type: Union[str, int, float] = 'median') -> nn.Module: File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 262, in _register return create_module(args[0]) File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 259, in create_module return type('NestModule', (NestModule,), dict(slots=(), doc=doc))(func, nest_meta) File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 69, in init self._check_definition() File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 80, in _check_definition if v.default is not inspect.Parameter.empty and not U.is_annotation_matched(v.default, v.annotation): File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/logger.py", line 59, in wrapper res = func(*args, **kwargs) File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/utils.py", line 236, in is_annotation_matched sub_annotation = annotation.args AttributeError: type object 'Union' has no attribute 'args'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "/root/Envs/pt-py3/bin/nest", line 11, in sys.exit(main()) File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/main.py", line 4, in main CLI() File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/cli.py", line 71, in init getattr(self, 'cmd_' + args.command)('nest ' + args.command, sys.argv[2:]) File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/cli.py", line 162, in cmd_module module_info = ['%s (%s)' % (k, v.meta.get('version', 'version')) for k, v in module_manager] File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 702, in iter self._update_modules() File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 692, in _update_modules ModuleManager._import_nest_modules_from_dir(meta['module_path'], namespace, self.py_modules, self.nest_modules, meta) File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 407, in _import_nest_modules_from_dir ModuleManager._import_nest_modules_from_file(file_path, namespace, py_modules, nest_modules, meta) File "/root/Envs/pt-py3/lib/python3.5/site-packages/nest/modules.py", line 356, in _import_nest_modules_from_file if (type(exc_info) is ModuleNotFoundError or type(exc_info) is ImportError) and exc_info.name is not None: NameError: name 'ModuleNotFoundError' is not defined

    opened by ZhouYanzhao 13
  • RuntimeError: Unable to load global settings of Nest. load() missing 1 required positional argument: 'Loader'

    RuntimeError: Unable to load global settings of Nest. load() missing 1 required positional argument: 'Loader'

    Hi, I just downloaded the Nest and S3N and try to get it run. When importing the nest module, an error shown as title occurs. Any idea can solve this problem? Many thanks!

    Input: from nest import register

    Output: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/nest/settings.py", line 126, in settings = SettingManager() File "/usr/local/lib/python3.6/dist-packages/nest/settings.py", line 107, in init self.load() File "/usr/local/lib/python3.6/dist-packages/nest/settings.py", line 119, in load self.settings, self.user_settings = SettingManager.load_settings() File "/usr/local/lib/python3.6/dist-packages/nest/settings.py", line 93, in load_settings settings = yaml.load(DEFAULT_SETTINGS) TypeError: load() missing 1 required positional argument: 'Loader'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.6/dist-packages/nest/init.py", line 1, in from nest.parser import run_tasks File "/usr/local/lib/python3.6/dist-packages/nest/parser.py", line 7, in import nest.utils as U File "/usr/local/lib/python3.6/dist-packages/nest/utils.py", line 12, in from nest.logger import exception File "/usr/local/lib/python3.6/dist-packages/nest/logger.py", line 7, in from nest.settings import settings File "/usr/local/lib/python3.6/dist-packages/nest/settings.py", line 128, in raise RuntimeError('Unable to load global settings of Nest. %s' % exc_info) RuntimeError: Unable to load global settings of Nest. load() missing 1 required positional argument: 'Loader'

    Platform: Ubuntu 20.04 Python 3.6

    opened by SteamerLee 1
Owner
ZhouYanzhao
ZhouYanzhao
Nest Protect integration for Home Assistant. This will allow you to integrate your smoke, heat, co and occupancy status real-time in HA.

Nest Protect integration for Home Assistant Custom component for Home Assistant to interact with Nest Protect devices via an undocumented and unoffici

Mick Vleeshouwer 175 Dec 29, 2022
Convolutional neural network web app trained to track our infant’s sleep schedule using our Google Nest camera.

Machine Learning Sleep Schedule Tracker What is it? Convolutional neural network web app trained to track our infant’s sleep schedule using our Google

g-parki 7 Jul 15, 2022
API for RL algorithm design & testing of BCA (Building Control Agent) HVAC on EnergyPlus building energy simulator by wrapping their EMS Python API

RL - EmsPy (work In Progress...) The EmsPy Python package was made to facilitate Reinforcement Learning (RL) algorithm research for developing and tes

null 20 Jan 5, 2023
Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler; for Python, R, Julia, Scala, Go, Javascript and more

Apache MXNet (incubating) for Deep Learning Apache MXNet is a deep learning framework designed for both efficiency and flexibility. It allows you to m

The Apache Software Foundation 20.2k Jan 8, 2023
Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler; for Python, R, Julia, Scala, Go, Javascript and more

Apache MXNet (incubating) for Deep Learning Apache MXNet is a deep learning framework designed for both efficiency and flexibility. It allows you to m

The Apache Software Foundation 20.2k Jan 5, 2023
Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler; for Python, R, Julia, Scala, Go, Javascript and more

Apache MXNet (incubating) for Deep Learning Apache MXNet is a deep learning framework designed for both efficiency and flexibility. It allows you to m

The Apache Software Foundation 19.3k Feb 12, 2021
Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler; for Python, R, Julia, Scala, Go, Javascript and more

Apache MXNet (incubating) for Deep Learning Master Docs License Apache MXNet (incubating) is a deep learning framework designed for both efficiency an

ROCm Software Platform 29 Nov 16, 2022
An integration of several popular automatic augmentation methods, including OHL (Online Hyper-Parameter Learning for Auto-Augmentation Strategy) and AWS (Improving Auto Augment via Augmentation Wise Weight Sharing) by Sensetime Research.

An integration of several popular automatic augmentation methods, including OHL (Online Hyper-Parameter Learning for Auto-Augmentation Strategy) and AWS (Improving Auto Augment via Augmentation Wise Weight Sharing) by Sensetime Research.

null 45 Dec 8, 2022
This is a Machine Learning Based Hand Detector Project, It Uses Machine Learning Models and Modules Like Mediapipe, Developed By Google!

Machine Learning Hand Detector This is a Machine Learning Based Hand Detector Project, It Uses Machine Learning Models and Modules Like Mediapipe, Dev

Popstar Idhant 3 Feb 25, 2022
A flexible framework of neural networks for deep learning

Chainer: A deep learning framework Website | Docs | Install Guide | Tutorials (ja) | Examples (Official, External) | Concepts | ChainerX Forum (en, ja

Chainer 5.8k Jan 6, 2023