"src/git@developer.sourcefind.cn:gaoqiong/migraphx.git" did not exist on "da0dccc7785ee2fa1a2b7033bfa5710b5bfd81ef"
Unverified Commit df4f05c7 authored by Chi Song's avatar Chi Song Committed by GitHub
Browse files

add Chinese translation (#661)

parent b38c0431
# **在 NNI 中调试代码**
*编写中……*
\ No newline at end of file
# 安装 NNI
当前仅支持 Linux 和 Mac。
## **安装**
* **通过 pip 命令安装 NNI**
先决条件:`python >= 3.5`
```bash
python3 -m pip install --upgrade nni
```
* **通过源代码安装 NNI**
先决条件:`python >=3.5, git, wget`
```bash
git clone -b v0.5.1 https://github.com/Microsoft/nni.git
cd nni
./install.sh
```
* **在 docker 映像中安装 NNI**
也可将 NNI 安装到 docker 映像中。 参考[这里](../deployment/docker/README.md)来生成 NNI 的 Docker 映像。 也可通过此命令从 Docker Hub 中直接拉取 NNI 的映像 `docker pull msranni/nni:latest`
## **系统需求**
以下是 NNI 在 Linux 下的最低配置。 由于程序变更,NNI 的最低配置会有所更改。
| | 最低配置 | 推荐配置 |
| -------- | ------------------------------------- | ----------------------------------------- |
| **操作系统** | Ubuntu 16.04 或以上版本 | Ubuntu 16.04 或以上版本 |
| **CPU** | Intel® Core™ i3 或 AMD Phenom™ X3 8650 | Intel® Core™ i5 或 AMD Phenom™ II X3 或更高配置 |
| **GPU** | NVIDIA® GeForce® GTX 460 | NVIDIA® GeForce® GTX 660 或更高配置 |
| **内存** | 4 GB | 6 GB |
| **存储** | 30 GB 可用的磁盘空间 | |
| **网络** | 宽带连接 | |
| **分辨率** | 1024 x 768 以上 | |
以下是 NNI 在 MacOS 下的最低配置。 由于程序变更,NNI 的最低配置会有所更改。
| | 最低配置 | 推荐配置 |
| -------- | -------------------------------------------------- | ------------------------ |
| **操作系统** | macOS 10.14.1 (最新版本) | macOS 10.14.1 (最新版本) |
| **CPU** | Intel® Core™ i5-760 或更高 | Intel® Core™ i7-4770 或更高 |
| **GPU** | NVIDIA® GeForce® GT 750M 或 AMD Radeon™ R9 M290 或更高 | AMD Radeon™ R9 M395X 或更高 |
| **内存** | 4 GB | 8 GB |
| **存储** | 70GB 可用空间及 7200 RPM 硬盘 | 70GB 可用空间 SSD 硬盘 |
| **网络** | 宽带连接 | |
| **分辨率** | 1024 x 768 以上 | |
## 更多
* [概述](Overview.md)
* [使用命令行工具 nnictl](NNICTLDOC.md)
* [使用 NNIBoard](WebUI.md)
* [定制搜索空间](SearchSpaceSpec.md)
* [配置 Experiment](ExperimentConfig.md)
* [如何在本机运行 Experiment (支持多 GPU 卡)?](tutorial_1_CR_exp_local_api.md)
* [如何在多机上运行 Experiment?](RemoteMachineMode.md)
* [如何在 OpenPAI 上运行 Experiment?](PAIMode.md)
* [如何通过 Kubeflow 在 Kubernetes 上运行 Experiment?](KubeflowMode.md)
* [如何通过 FrameworkController 在 Kubernetes 上运行 Experiment?](FrameworkControllerMode.md)
\ No newline at end of file
# **在 Kubeflow 上运行 Experiment**
NNI 支持在 [Kubeflow](https://github.com/kubeflow/kubeflow)上运行,称为 kubeflow 模式。 在开始使用 NNI 的 kubeflow 模式前,需要有一个 kubernetes 集群,可以是私有部署的,或者是 [Azure Kubernetes Service(AKS)](https://azure.microsoft.com/en-us/services/kubernetes-service/),并需要一台配置好 [kubeconfig](https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/) 的 Ubuntu 计算机连接到此 kubernetes 集群。 如果不熟悉 Kubernetes,可先浏览[这里](https://kubernetes.io/docs/tutorials/kubernetes-basics/)。 在 kubeflow 模式下,每个 Trial 程序会在 Kubernetes 集群中作为一个 kubeflow 作业来运行。
## 私有部署的 Kubernetes 的准备工作
1. 采用 Kubernetes 1.8 或更高版本。 根据[指南](https://kubernetes.io/docs/setup/)来安装 Kubernetes。
2. 在 Kubernetes 集群中下载、安装、部署 **Kubelow**。 根据[指南](https://www.kubeflow.org/docs/started/getting-started/)安装 Kubeflow。
3. 配置 **kubeconfig** 文件,NNI 将使用此配置与 Kubernetes API 服务交互。 默认情况下,NNI 管理器会使用 $(HOME)/.kube/config 作为 kubeconfig 文件的路径。 也可以通过环境变量 **KUBECONFIG** 来指定其它 kubeconfig 文件。 根据[指南](https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig)了解更多 kubeconfig 的信息。
4. 如果 NNI Trial 作业需要 GPU 资源,需按照[指南](https://github.com/NVIDIA/k8s-device-plugin)来配置 **Kubernetes 下的 Nvidia 插件**
5. 准备 **NFS 服务器** 并导出通用的装载 (mount),推荐将 NFS 服务器路径映射到 `root_squash 选项`,否则可能会在 NNI 复制文件到 NFS 时出现权限问题。 参考[页面](https://linux.die.net/man/5/exports),来了解关于 root_squash 选项,或 **Azure File Storage**
6. 在安装 NNI 并运行 nnictl 的计算机上安装 **NFS 客户端**。 运行此命令安装 NFSv4 客户端:
apt-get install nfs-common
7. 参考[指南](QuickStart.md)安装 **NNI**
## Azure 部署的 Kubernetes 的准备工作
1. NNI 支持基于 Azure Kubernetes Service 的 Kubeflow,参考[指南](https://azure.microsoft.com/en-us/services/kubernetes-service/)来设置 Azure Kubernetes Service。
2. 安装 [Azure CLI](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)**kubectl**。 使用 `az login` 命令来设置 Azure 账户吗,并将 kubectl 客户端连接到 AKS,参考此[指南](https://docs.microsoft.com/en-us/azure/aks/kubernetes-walkthrough#connect-to-the-cluster)
3. 在 Azure Kubernetes Service 上部署 Kubeflow,参考此[指南](https://www.kubeflow.org/docs/started/getting-started/)
4. 参考此[指南](https://docs.microsoft.com/en-us/azure/storage/common/storage-quickstart-create-account?tabs=portal)来创建 Azure 文件存储账户。 NNI 需要 Azure Storage Service 来存取代码和输出文件。
5. NNI 需要访问密钥来连接 Azure 存储服务,NNI 使用 [Azure Key Vault](https://azure.microsoft.com/en-us/services/key-vault/) 服务来保护私钥。 设置 Azure Key Vault 服务,并添加密钥到 Key Vault 中来存取 Azure 存储账户。 参考[指南](https://docs.microsoft.com/en-us/azure/key-vault/quick-create-cli)来存储访问密钥。
## 设计
![](./img/kubeflow_training_design.png) Kubeflow 训练服务会实例化一个 kubernetes 客户端来与 Kubernetes 集群的 API 服务器交互。
对于每个 Trial,会上传本机 codeDir 路径(在 nni_config.yml 中配置)中的所有文件,包括 parameter.cfg 这样的生成的文件到存储卷中。 当前支持两种存储卷:[nfs](https://en.wikipedia.org/wiki/Network_File_System)[Azure 文件存储](https://azure.microsoft.com/en-us/services/storage/files/),需要在 NNI 的 YAML 文件中进行配置。 当文件准备好后,Kubeflow 训练服务会调用 Kubernetes 的 API 来创建 Kubeflow 作业 ([tf-operator](https://github.com/kubeflow/tf-operator) 作业或 [pytorch-operator](https://github.com/kubeflow/pytorch-operator) 作业) ,并将存储卷挂载到作业的 pod 中。 Kubeflow 作业的输出文件,例如 stdout, stderr, trial.log 以及模型文件,也会被复制回存储卷。 NNI 会在网页中显示每个 Trial 的存储卷的 URL,以便浏览日志和输出文件。
## 支持的操作符(operator)
NNI 仅支持 kubeflow 的 tf-operator 和 pytorch-operator,其它操作符未经测试。 可以在配置文件中设置操作符类型。 这是 tf-operator 的设置:
kubeflowConfig:
operator: tf-operator
这是 pytorch-operator 的设置:
kubeflowConfig:
operator: pytorch-operator
如果要使用 tf-operator,需要在 Trial 配置中设置 `ps``worker`。如果要使用 pytorch-operator,需要在 Trial 配置中设置 `master``worker`
## 支持的存储类型
NNI 支持使用 NFS 和 Azure 存储来存储代码和输出文件,可在配置文件进行相应的配置。
NFS 存储配置如下:
kubeflowConfig:
storage: nfs
nfs:
# NFS 服务器 IP, 如 10.10.10.10
server: {your_nfs_server_ip}
# NFS 服务器的导出路径,如 /var/nfs/nni
path: {your_nfs_server_export_path}
如果使用了 Azure 存储,需要在 YAML 文件中如下设置 `kubeflowConfig`
kubeflowConfig:
storage: azureStorage
keyVault:
vaultName: {your_vault_name}
name: {your_secert_name}
azureStorage:
accountName: {your_storage_account_name}
azureShare: {your_azure_share_name}
## 运行 Experiment
`examples/trials/mnist` 为例。 这是一个 TensorFlow 作业,使用了 Kubeflow 的 tf-operator。 NNI 的 YAML 配置文件如下:
authorName: default
experimentName: example_mnist
trialConcurrency: 2
maxExecDuration: 1h
maxTrialNum: 20
#可选项: local, remote, pai, kubeflow
trainingServicePlatform: kubeflow
searchSpacePath: search_space.json
#可选项: true, false
useAnnotation: false
tuner:
#可选项: TPE, Random, Anneal, Evolution
builtinTunerName: TPE
classArgs:
#可选项: maximize, minimize
optimize_mode: maximize
assessor:
builtinAssessorName: Medianstop
classArgs:
optimize_mode: maximize
gpuNum: 0
trial:
codeDir: .
worker:
replicas: 2
command: python3 dist_mnist.py
gpuNum: 1
cpuNum: 1
memoryMB: 8196
image: msranni/nni:latest
ps:
replicas: 1
command: python3 dist_mnist.py
gpuNum: 0
cpuNum: 1
memoryMB: 8196
image: msranni/nni:latest
kubeflowConfig:
operator: tf-operator
apiVersion: v1alpha2
storage: nfs
nfs:
# NFS 服务器 IP,如 10.10.10.10
server: {your_nfs_server_ip}
# NFS 服务器的导出路径,如 /var/nfs/nni
path: {your_nfs_server_export_path}
注意:如果用 Kubeflow 模式运行,需要在 YAML 文件中显式设置 `trainingServicePlatform: kubeflow`
如果要运行 Pytorch 作业,需要如下配置:
authorName: default
experimentName: example_mnist_distributed_pytorch
trialConcurrency: 1
maxExecDuration: 1h
maxTrialNum: 10
#可选项: local, remote, pai, kubeflow
trainingServicePlatform: kubeflow
searchSpacePath: search_space.json
#可选项: true, false
useAnnotation: false
tuner:
#可选项: TPE, Random, Anneal, Evolution
builtinTunerName: TPE
classArgs:
#可选项: maximize, minimize
optimize_mode: minimize
trial:
codeDir: .
master:
replicas: 1
command: python3 dist_mnist.py
gpuNum: 1
cpuNum: 1
memoryMB: 2048
image: msranni/nni:latest
worker:
replicas: 1
command: python3 dist_mnist.py
gpuNum: 0
cpuNum: 1
memoryMB: 2048
image: msranni/nni:latest
kubeflowConfig:
operator: pytorch-operator
apiVersion: v1alpha2
nfs:
# NFS 服务器 IP,如 10.10.10.10
server: {your_nfs_server_ip}
# NFS 服务器导出路径,如 /var/nfs/nni
path: {your_nfs_server_export_path}
Kubeflow 模式的配置有下列主键:
* codeDir
* 代码目录,存放训练代码和配置文件
* worker (必填)。 此部分用于配置 TensorFlow 的 worker 角色
* replicas
* 必填。 需要运行的 TensorFlow woker 角色的数量,必须为正数。
* command
* 必填。 用来运行 Trial 作业的命令,例如: ```python mnist.py```
* memoryMB
* 必填。 Trial 程序的内存需求,必须为正数。
* cpuNum
* gpuNum
* image
* 必填。 在 kubeflow 模式中,Kubernetes 会安排 Trial 程序在 [Pod](https://kubernetes.io/docs/concepts/workloads/pods/pod/) 中执行。 此键用来指定 Trial 程序的 pod 使用的 Docker 映像。
* [Docker Hub](https://hub.docker.com/) 上有预制的 NNI Docker 映像 [msranni/nni](https://hub.docker.com/r/msranni/nni/)。 它包含了用来启动 NNI Experiment 所依赖的所有 Python 包,Node 模块和 JavaScript。 生成此 Docker 映像的文件在[这里](https://github.com/Microsoft/nni/tree/master/deployment/Dockerfile.build.base)。 可以直接使用此映像,或参考它来生成自己的映像。
* apiVersion
* 必填。 Kubeflow 的 API 版本。
* ps (可选)。 此部分用于配置 TensorFlow 的 parameter 服务器角色。
* master (可选)。 此部分用于配置 PyTorch 的 parameter 服务器角色。
完成并保存 NNI Experiment 配置文件后(例如可保存为:exp_kubeflow.yml),运行以下命令:
nnictl create --config exp_kubeflow.yml
来在 Kubeflow 模式下启动 Experiment。 NNI 会为每个 Trial 创建 Kubeflow tfjob 或 pytorchjob,作业名称的格式为 `nni_exp_{experiment_id}_trial_{trial_id}`。 可以在 Kubernetes 面板中看到创建的 Kubeflow tfjob。
注意:Kubeflow 模式下,NNIManager 会启动 RESTful 服务,监听端口为 NNI 网页服务器的端口加1。 例如,如果网页端口为`8080`,那么 RESTful 服务器会监听在 `8081`端口,来接收运行在 Kubernetes 中的 Trial 作业的指标。 因此,需要在防火墙中启用端口 `8081` 的 TCP 协议,以允许传入流量。
当一个 Trial 作业完成后,可以在 NNI 网页的概述页面(如:http://localhost:8080/oview)中查看 Trial 的信息。
如果在使用 Kubeflow 模式时遇到任何问题,请到 [NNI Github](https://github.com/Microsoft/nni) 中创建问题。
\ No newline at end of file
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
\ No newline at end of file
# nnictl
## 介绍
**nnictl** 是一个命令行工具,用来控制 NNI Experiment,如启动、停止、继续 Experiment,启动、停止 NNIBoard 等等。
## 命令
nnictl 支持的命令:
* [nnictl create](#create)
* [nnictl resume](#resume)
* [nnictl stop](#stop)
* [nnictl update](#update)
* [nnictl trial](#trial)
* [nnictl top](#top)
* [nnictl experiment show](#experiment)
* [nnictl config](#config)
* [nnictl log](#log)
* [nnictl webui](#webui)
* [nnictl tensorboard](#tensorboard)
* [nnictl package](#package)
* [nnictl --version](#version)
### 管理 Experiment
<a name="create"></a>
* **nnictl create**
* 说明
此命令使用参数中的配置文件,来创建新的 Experiment。
此命令成功完成后,上下文会被设置为此 Experiment。这意味着如果不显式改变上下文(暂不支持),输入的以下命令,都作用于此 Experiment。
* 用法
```bash
nnictl create [OPTIONS]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ------------ | ----- | --- | ---------------------- |
| --config, -c | True | | Experiment 的 YAML 配置文件 |
| --port, -p | False | | RESTful 服务的端口 |
<a name="resume"></a>
* **nnictl resume**
* 说明
使用此命令恢复已停止的 Experiment。
* 用法
```bash
nnictl resume [OPTIONS]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ---------- | ----- | --- | -------------------------------- |
| id | False | | 要恢复的 Experiment 标识 |
| --port, -p | False | | 要恢复的 Experiment 使用的 RESTful 服务端口 |
<a name="stop"></a>
* **nnictl stop**
* 说明
使用此命令来停止正在运行的单个或多个 Experiment。
* 用法
```bash
nnictl stop [id]
```
* 详细说明
1. 如果指定了 id,并且此 id 匹配正在运行的 Experiment,nnictl 会停止相应的 Experiment,否则会输出错误信息。
2. 如果没有指定 id,并且当前有运行的 Experiment,则会停止该 Experiment,否则会输出错误信息。
3. 如果 id 以 * 结尾,nnictl 会停止所有匹配此通配符的 Experiment。
4. 如果 id 不存在,但匹配了某个Experiment 的 id 前缀,nnictl 会停止匹配的Experiment 。
5. 如果 id 不存在,但匹配多个 Experiment id 的前缀,nnictl 会输出这些 id 的信息。
6. 可使用 'nnictl stop all' 来停止所有的 Experiment。
<a name="update"></a>
* **nnictl update**
* **nnictl update searchspace**
* 说明
可以用此命令来更新 Experiment 的搜索空间。
* 用法
```bash
nnictl update searchspace [OPTIONS]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| -------------- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
| --filename, -f | True | | 新的搜索空间文件名 |
* **nnictl update concurrency**
* 说明
可以用此命令来更新 Experiment 的并发设置。
* 用法
```bash
nnictl update concurrency [OPTIONS]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ----------- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
| --value, -v | True | | 允许同时运行的 Trial 的数量 |
* **nnictl update duration**
* 说明
可以用此命令来更新 Experiment 的运行时间。
* 用法
```bash
nnictl update duration [OPTIONS]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ----------- | ----- | --- | ----------------------------------------------------------------------- |
| id | False | | 需要设置的 Experiment 的 id |
| --value, -v | True | | Experiment 持续时间如没有单位,则为秒。 后缀可以为 's' 即秒 (默认值), 'm' 即分钟, 'h' 即小时或 'd' 即天。 |
* **nnictl update trialnum**
* 说明
可以用此命令来更新 Experiment 的最大 Trial 数量。
* 用法
```bash
nnictl update trialnum [OPTIONS]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ----------- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
| --value, -v | True | | 需要设置的 maxtrialnum 的数量 |
<a name="trial"></a>
* **nnictl trial**
* **nnictl trial ls**
* 说明
使用此命令来查看 Trial 的信息。
* 用法
```bash
nnictl trial ls
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ----- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
* **nnictl trial kill**
* 说明
此命令用于终止 Trial。
* 用法
```bash
nnictl trial kill [OPTIONS]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ------------- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
| --trialid, -t | True | | 需要终止的 Trial 的 id。 |
<a name="top"></a>
* **nnictl top**
* 说明
查看正在运行的 Experiment。
* 用法
```bash
nnictl top
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ---------- | ----- | --- | ------------------------------------ |
| id | False | | 需要设置的 Experiment 的 id |
| --time, -t | False | | 刷新 Experiment 状态的时间间隔,单位为秒,默认值为 3 秒。 |
<a name="experiment"></a>
### 管理 Experiment 信息
* **nnictl experiment show**
* 说明
显示 Experiment 的信息。
* 用法
```bash
nnictl experiment show
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ----- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
* **nnictl experiment status**
* 说明
显示 Experiment 的状态。
* 用法
```bash
nnictl experiment status
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ----- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
* **nnictl experiment list**
* 说明
显示正在运行的 Experiment 的信息
* 用法
```bash
nnictl experiment list
```
<a name="config"></a>
* **nnictl config show**
* 说明
显示当前上下文信息。
* 用法
```bash
nnictl config show
```
<a name="log"></a>
### 管理日志
* **nnictl log stdout**
* 说明
显示 stdout 日志内容。
* 用法
```bash
nnictl log stdout [options]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ---------- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
| --head, -h | False | | 显示 stdout 开始的若干行 |
| --tail, -t | False | | 显示 stdout 结尾的若干行 |
| --path, -p | False | | 显示 stdout 文件的路径 |
* **nnictl log stderr**
* 说明
显示 stderr 日志内容。
* 用法
```bash
nnictl log stderr [options]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ---------- | ----- | --- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
| --head, -h | False | | 显示 stderr 开始的若干行 |
| --tail, -t | False | | 显示 stderr 结尾的若干行 |
| --path, -p | False | | 显示 stderr 文件的路径 |
* **nnictl log trial**
* 说明
显示 Trial 日志的路径。
* 用法
```bash
nnictl log trial [options]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ----- | ----- | --- | ---------- |
| id | False | | Trial 的 id |
<a name="webui"></a>
### 管理网页
* **nnictl webui url**
<a name="tensorboard"></a>
### 管理 tensorboard
* **nnictl tensorboard start**
* 说明
启动 tensorboard 进程。
* 用法
```bash
nnictl tensorboard start
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| --------- | ----- | ---- | --------------------- |
| id | False | | 需要设置的 Experiment 的 id |
| --trialid | False | | Trial 的 id |
| --port | False | 6006 | tensorboard 进程的端口 |
* 详细说明
1. NNICTL 当前仅支持本机和远程平台的 tensorboard,其它平台暂不支持。
2. 如果要使用 tensorboard,需要将 tensorboard 日志输出到环境变量 [NNI_OUTPUT_DIR] 路径下。
3. 在 local 模式中,nnictl 会直接设置 --logdir=[NNI_OUTPUT_DIR] 并启动 tensorboard 进程。
4. 在 remote 模式中,nnictl 会创建一个 ssh 客户端来将日志数据从远程计算机复制到本机临时目录中,然后在本机开始 tensorboard 进程。 需要注意的是,nnictl 只在使用此命令时复制日志数据,如果要查看最新的 tensorboard 结果,需要再次执行 nnictl tensorboard 命令。
5. 如果只有一个 Trial 任务,不需要设置 trialid。 如果有多个运行的 Trial 作业,需要设置 trialid,或使用 [nnictl tensorboard start --trialid all] 来将 --logdir 映射到所有 Trial 的路径。
* **nnictl tensorboard stop**
* 说明
停止所有 tensorboard 进程。
* 用法
```bash
nnictl tensorboard stop
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ----- | ----- | --- | ----------- |
| id | False | | 需要设置的实验的 id |
<a name="package"></a>
### 管理安装包
* **nnictl package install**
* 说明
安装 NNI 实验所需要的包。
* 用法
```bash
nnictl package install [OPTIONS]
```
* 选项
| 参数及缩写 | 是否必需 | 默认值 | 说明 |
| ------ | ---- | --- | ------- |
| --name | True | | 要安装的包名称 |
* **nnictl package show**
* 说明
列出支持的安装包
* 用法
```bash
nnictl package show
```
<a name="version"></a>
### 检查 NNI 版本
* **nnictl --version**
* 说明
显示当前安装的 NNI 的版本。
* 用法
```bash
nnictl --version
```
\ No newline at end of file
# 概述
NNI (Neural Network Intelligence) 是一个工具包,可有效的帮助用户设计并调优机器学习模型的神经网络架构,复杂系统的参数(如超参)等。 NNI 的特性包括:易于使用,可扩展,灵活,高效。
* **易于使用**:NNI 可通过 pip 安装。 只需要在代码中添加几行,就可以利用 NNI 来调优参数。 可使用命令行工具或 Web 界面来查看实验过程。
* **可扩展**:调优超参或网络结构通常需要大量的计算资源。NNI 在设计时就支持了多种不同的计算资源,如远程服务器组,训练平台(如:OpenPAI,Kubernetes),等等。 通过训练平台,可拥有同时运行数百个 Trial 的能力。
* **灵活**:除了内置的算法,NNI 中还可以轻松集成自定义的超参调优算法,神经网络架构搜索算法,提前终止算法等等。 还可以将 NNI 连接到更多的训练平台上,如云中的虚拟机集群,Kubernetes 服务等等。 此外,NNI 还可以连接到外部环境中的特殊应用和模型上。
* **高效**:NNI 在系统及算法级别上不停的优化。 例如:通过 Trial 早期的反馈来加速调优过程。
下图显示了 NNI 的体系结构。
<p align="center">
<img src="https://user-images.githubusercontent.com/23273522/51816536-ed055580-2301-11e9-8ad8-605a79ee1b9a.png" alt="drawing" width="700"/>
</p>
## 主要概念
* *Experiment(实验)*:实验是一次找到模型的最佳超参组合,或最好的神经网络架构的任务。 它由 Trial 和自动机器学习算法所组成。
* *搜索空间*:是模型调优的范围。 例如,超参的取值范围。
* *Configuration(配置)*:配置是来自搜索空间的一个参数实例,每个超参都会有一个特定的值。
* *Trial*: Trial 是一次尝试,它会使用某组配置(例如,一组超参值,或者特定的神经网络架构)。 Trial 会基于提供的配置来运行。
* *Tuner*: Tuner 是一个自动机器学习算法,会为下一个 Trial 生成新的配置。 新的 Trial 会使用这组配置来运行。
* *Assessor*:Assessor 分析 Trial 的中间结果(例如,测试数据集上定期的精度),来确定 Trial 是否应该被提前终止。
* *训练平台*:是 Trial 的执行环境。 根据 Experiment 的配置,可以是本机,远程服务器组,或其它大规模训练平台(如,OpenPAI,Kubernetes)。
Experiment 的运行过程为:Tuner 接收搜索空间并生成配置。 这些配置将被提交到训练平台,如本机,远程服务器组或训练集群。 执行的性能结果会被返回给 Tuner。 然后,再生成并提交新的配置。
每次 Experiment 执行时,用户只需要定义搜索空间,改动几行代码,就能利用 NNI 内置的 Tuner/Assessor 和训练服务来搜索最好的超参组合以及神经网络结构。 基本上分为三步:
> 第一步:[定义搜索空间](SearchSpaceSpec.md)
>
> 第二步:[改动模型代码](Trials.md)
>
> 第三步:[定义 Experiment 配置](ExperimentConfig.md)
<p align="center">
<img src="https://user-images.githubusercontent.com/23273522/51816627-5d13db80-2302-11e9-8f3e-627e260203d5.jpg" alt="drawing"/>
</p>
更多 Experiment 运行的详情,参考[快速入门](QuickStart.md)
## 了解更多信息
* [开始使用](QuickStart.md)
* [如何为 NNI 调整代码?](Trials.md)
* [NNI 支持哪些 Tuner?](Builtin_Tuner.md)
* [如何自定义 Tuner?](Customize_Tuner.md)
* [NNI 支持哪些 Assessor?](Builtin_Assessors.md)
* [如何自定义 Assessor?](Customize_Assessor.md)
* [如何在本机上运行 Experiment?](tutorial_1_CR_exp_local_api.md)
* [如何在多机上运行 Experiment?](RemoteMachineMode.md)
* [如何在 OpenPAI 上运行 Experiment?](PAIMode.md)
* [样例](mnist_examples.md)
\ No newline at end of file
# **在 OpenPAI 上运行 Experiment**
NNI 支持在 [OpenPAI](https://github.com/Microsoft/pai) (简称 pai)上运行 Experiment,即 pai 模式。 在使用 NNI 的 pai 模式前, 需要有 [OpenPAI](https://github.com/Microsoft/pai) 群集的账户。 如果没有 OpenPAI 账户,参考[这里](https://github.com/Microsoft/pai#how-to-deploy)来进行部署。 在 pai 模式中,会在 Docker 创建的容器中运行 Trial 程序。
## 设置环境
参考[指南](QuickStart.md)安装 NNI。
## 运行 Experiment
`examples/trials/mnist-annotation` 为例。 NNI 的 YAML 配置文件如下:
```yaml
authorName: your_name
experimentName: auto_mnist
# 并发运行的 Trial 数量
trialConcurrency: 2
# Experiment 的最长持续运行时间
maxExecDuration: 3h
# 空表示一直运行
maxTrialNum: 100
# 可选项: local, remote, pai
trainingServicePlatform: pai
# 可选项: true, false
useAnnotation: true
tuner:
builtinTunerName: TPE
classArgs:
optimize_mode: maximize
trial:
command: python3 mnist.py
codeDir: ~/nni/examples/trials/mnist-annotation
gpuNum: 0
cpuNum: 1
memoryMB: 8196
image: openpai/pai.example.tensorflow
dataDir: hdfs://10.1.1.1:9000/nni
outputDir: hdfs://10.1.1.1:9000/nni
# 配置访问的 OpenPAI 集群
paiConfig:
userName: your_pai_nni_user
passWord: your_pai_password
host: 10.1.1.1
```
注意:如果用 pai 模式运行,需要在 YAML 文件中设置 `trainingServicePlatform: pai`
与本机模式,以及[远程计算机模式](RemoteMachineMode.md)相比,pai 模式的 Trial 有额外的配置:
* cpuNum
* 必填。 Trial 程序的 CPU 需求,必须为正数。
* memoryMB
* 必填。 Trial 程序的内存需求,必须为正数。
* image
* 必填。 在 pai 模式中,Trial 程序由 OpenPAI 在 [Docker 容器](https://www.docker.com/)中安排运行。 此键用来指定 Trial 程序的容器使用的 Docker 映像。
* [Docker Hub](https://hub.docker.com/) 上有预制的 NNI Docker 映像 [nnimsra/nni](https://hub.docker.com/r/msranni/nni/)。 它包含了用来启动 NNI Experiment 所依赖的所有 Python 包,Node 模块和 JavaScript。 生成此 Docker 映像的文件在[这里](https://github.com/Microsoft/nni/tree/master/deployment/Dockerfile.build.base)。 可以直接使用此映像,或参考它来生成自己的映像。
* dataDir
* 可选。 指定了 Trial 用于下载数据的 HDFS 数据目录。 格式应为 hdfs://{your HDFS host}:9000/{数据目录}
* outputDir
* 可选。 指定了 Trial 的 HDFS 输出目录。 Trial 在完成(成功或失败)后,Trial 的 stdout, stderr 会被 NNI 自动复制到此目录中。 格式应为 hdfs://{your HDFS host}:9000/{输出目录}
完成并保存 NNI Experiment 配置文件后(例如可保存为:exp_pai.yml),运行以下命令:
nnictl create --config exp_pai.yml
来在 pai 模式下启动 Experiment。 NNI 会为每个 Trial 创建 OpenPAI 作业,作业名称的格式为 `nni_exp_{experiment_id}_trial_{trial_id}`。 可以在 OpenPAI 集群的网站中看到 NNI 创建的作业,例如: ![](./img/nni_pai_joblist.jpg)
注意:pai 模式下,NNIManager 会启动 RESTful 服务,监听端口为 NNI 网页服务器的端口加1。 例如,如果网页端口为`8080`,那么 RESTful 服务器会监听在 `8081`端口,来接收运行在 Kubernetes 中的 Trial 作业的指标。 因此,需要在防火墙中启用端口 `8081` 的 TCP 协议,以允许传入流量。
当一个 Trial 作业完成后,可以在 NNI 网页的概述页面(如:http://localhost:8080/oview)中查看 Trial 的信息。
在 Trial 列表页面中展开 Trial 信息,点击如下的 logPath: ![](./img/nni_webui_joblist.jpg)
接着将会打开 HDFS 的 WEB 界面,并浏览到 Trial 的输出文件: ![](./img/nni_trial_hdfs_output.jpg)
在输出目录中可以看到三个文件:stderr, stdout, 以及 trial.log
如果希望将 Trial 的模型数据等其它输出保存到HDFS中,可在 Trial 代码中使用 `NNI_OUTPUT_DIR` 来自己保存输出文件,NNI SDK会从 Trial 的容器中将 `NNI_OUTPUT_DIR` 中的文件复制到 HDFS 中。
如果在使用 pai 模式时遇到任何问题,请到 [NNI Github](https://github.com/Microsoft/nni) 中创建问题。
\ No newline at end of file
# 快速入门
## 安装
当前支持 Linux 和 MacOS。测试并支持的版本包括:Ubuntu 16.04 及更高版本,MacOS 10.14.1。 在 `python >= 3.5` 的环境中,只需要运行 `pip install` 即可完成安装。
```bash
python3 -m pip install --upgrade nni
```
注意:
* 如果需要将 NNI 安装到自己的 home 目录中,可使用 `--user`,这样也不需要任何特殊权限。
* 如果遇到如`Segmentation fault` 这样的任何错误请参考[常见问题](FAQ.md)
* 参考[安装 NNI](Installation.md),来了解`系统需求`
## MNIST 上的 "Hello World"
NNI 是一个能进行自动机器学习实验的工具包。 它可以自动进行获取超参、运行 Trial,测试结果,调优超参的循环。 下面会展示如何使用 NNI 来找到最佳超参组合。
这是还**没有 NNI** 的样例代码,用 CNN 在 MNIST 数据集上训练:
```python
def run_trial(params):
# 输入数据
mnist = input_data.read_data_sets(params['data_dir'], one_hot=True)
# 构建网络
mnist_network = MnistNetwork(channel_1_num=params['channel_1_num'], channel_2_num=params['channel_2_num'], conv_size=params['conv_size'], hidden_size=params['hidden_size'], pool_size=params['pool_size'], learning_rate=params['learning_rate'])
mnist_network.build_network()
test_acc = 0.0
with tf.Session() as sess:
# 训练网络
mnist_network.train(sess, mnist)
# 评估网络
test_acc = mnist_network.evaluate(mnist)
if __name__ == '__main__':
params = {'data_dir': '/tmp/tensorflow/mnist/input_data', 'dropout_rate': 0.5, 'channel_1_num': 32, 'channel_2_num': 64, 'conv_size': 5, 'pool_size': 2, 'hidden_size': 1024, 'learning_rate': 1e-4, 'batch_num': 2000, 'batch_size': 32}
run_trial(params)
```
注意:完整实现请参考 [examples/trials/mnist/mnist_before.py](https://github.com/Microsoft/nni/tree/master/examples/trials/mnist/mnist_before.py)
上面的代码一次只能尝试一组参数,如果想要调优学习率,需要手工改动超参,并一次次尝试。
NNI 就是用来帮助调优工作的。它的工作流程如下:
输入: 搜索空间, Trial 代码, 配置文件
输出: 一组最佳的超参配置
1: For t = 0, 1, 2, ..., maxTrialNum,
2: hyperparameter = 从搜索空间选择一组参数
3: final result = run_trial_and_evaluate(hyperparameter)
4: 返回最终结果给 NNI
5: If 时间达到上限,
6: 停止实验
7: return 最好的实验结果
如果需要使用 NNI 来自动训练模型,找到最佳超参,需要如下三步:
**使用 NNI 时的三个步骤**
**第一步**:定义 JSON 格式的`搜索空间`文件,包括所有需要搜索的超参的`名称``分布`(离散和连续值均可)。
```diff
- params = {'data_dir': '/tmp/tensorflow/mnist/input_data', 'dropout_rate': 0.5, 'channel_1_num': 32, 'channel_2_num': 64,
- 'conv_size': 5, 'pool_size': 2, 'hidden_size': 1024, 'learning_rate': 1e-4, 'batch_num': 2000, 'batch_size': 32}
+ {
+ "dropout_rate":{"_type":"uniform","_value":[0.5, 0.9]},
+ "conv_size":{"_type":"choice","_value":[2,3,5,7]},
+ "hidden_size":{"_type":"choice","_value":[124, 512, 1024]},
+ "batch_size": {"_type":"choice", "_value": [1, 4, 8, 16, 32]},
+ "learning_rate":{"_type":"choice","_value":[0.0001, 0.001, 0.01, 0.1]}
+ }
```
*实现代码:[search_space.json](https://github.com/Microsoft/nni/tree/master/examples/trials/mnist/search_space.json)*
**第二步**:修改 `Trial` 代码来从 NNI 获取超参,并返回 NNI 最终结果。
```diff
+ import nni
def run_trial(params):
mnist = input_data.read_data_sets(params['data_dir'], one_hot=True)
mnist_network = MnistNetwork(channel_1_num=params['channel_1_num'], channel_2_num=params['channel_2_num'], conv_size=params['conv_size'], hidden_size=params['hidden_size'], pool_size=params['pool_size'], learning_rate=params['learning_rate'])
mnist_network.build_network()
with tf.Session() as sess:
mnist_network.train(sess, mnist)
test_acc = mnist_network.evaluate(mnist)
+ nni.report_final_result(acc)
if __name__ == '__main__':
- params = {'data_dir': '/tmp/tensorflow/mnist/input_data', 'dropout_rate': 0.5, 'channel_1_num': 32, 'channel_2_num': 64,
- 'conv_size': 5, 'pool_size': 2, 'hidden_size': 1024, 'learning_rate': 1e-4, 'batch_num': 2000, 'batch_size': 32}
+ params = nni.get_next_parameter()
run_trial(params)
```
*实现代码:[mnist.py](https://github.com/Microsoft/nni/tree/master/examples/trials/mnist/mnist.py)*
**第三步**:定义 YAML 格式的`配置`文件,其中声明了搜索空间和 Trial 文件的`路径`,以及`其它信息`,如调优算法,最大尝试次数,最大运行时间等等。
```yaml
authorName: default
experimentName: example_mnist
trialConcurrency: 1
maxExecDuration: 1h
maxTrialNum: 10
trainingServicePlatform: local
# 搜索空间文件
searchSpacePath: search_space.json
useAnnotation: false
tuner:
builtinTunerName: TPE
# 运行的命令,以及 Trial 代码的路径
trial:
command: python3 mnist.py
codeDir: .
gpuNum: 0
```
*实现代码:[config.yml](https://github.com/Microsoft/nni/tree/master/examples/trials/mnist/config.yml)*
上面的代码都已准备好,并保存在 [examples/trials/mnist/](https://github.com/Microsoft/nni/tree/master/examples/trials/mnist)
上述步骤完成后,**从命令行运行 config.yml 文件来开始 Experiment**
```bash
nnictl create --config nni/examples/trials/mnist/config.yml
```
注意:**nnictl** 是一个命令行工具,用来控制 NNI Experiment,如启动、停止、继续 Experiment,启动、停止 NNIBoard 等等。 查看[这里](NNICTLDOC.md),了解 `nnictl` 更多用法。
在命令行中等待输出 `INFO: Successfully started experiment!`。 此消息表明 Experiment 已成功启动。 期望的输出如下:
INFO: Starting restful server...
INFO: Successfully started Restful server!
INFO: Setting local config...
INFO: Successfully set local config!
INFO: Starting experiment...
INFO: Successfully started experiment!
-----------------------------------------------------------------------
The experiment id is egchD4qy
The Web UI urls are: [Your IP]:8080
-----------------------------------------------------------------------
You can use these commands to get more information about the experiment
-----------------------------------------------------------------------
commands description
1. nnictl experiment show show the information of experiments
2. nnictl trial ls list all of trial jobs
3. nnictl top monitor the status of running experiments
4. nnictl log stderr show stderr log content
5. nnictl log stdout show stdout log content
6. nnictl stop stop an experiment
7. nnictl trial kill kill a trial job by id
8. nnictl --help get help information about nnictl
-----------------------------------------------------------------------
如果根据上述步骤准备好了相应 `Trial`, `搜索空间``配置`,并成功创建的 NNI 任务。NNI 会自动开始通过配置的搜索空间来运行不同的超参集合,搜索最好的超参。 通过 Web 界面可看到 NNI 的进度。
## Web 界面
启动 Experiment 后,可以在命令行界面找到如下的 `Web 界面地址`
The Web UI urls are: [IP 地址]:8080
在浏览器中打开 `Web 界面地址`(即:`[IP 地址]:8080`),就可以看到 Experiment 的详细信息,以及所有的 Trial 任务。
#### 查看概要页面
点击标签 "Overview"。
Experiment 相关信息会显示在界面上,配置和搜索空间等。 可通过 **Download** 按钮来`下载信息和参数`。 可以在运行中或结束后,随时下载 Experiment 的结果。
![](./img/QuickStart1.png)
前 10 个 Trial 结果也会列在 Overview 页面中,可以在 "Trials Detail" 部分浏览所有的 Trial。
![](./img/QuickStart2.png)
#### 查看 Trial 详情页面
点击 "Default Metric" 来查看所有 Trial 的点图。 悬停鼠标来查看默认指标和搜索空间信息。
![](./img/QuickStart3.png)
点击 "Hyper Parameter" 标签查看图像。
* 可选择百分比查看最好的 Trial。
* 选择两个轴来交换位置。
![](./img/QuickStart4.png)
点击 "Trial Duration" 标签来查看柱状图。
![](./img/QuickStart5.png)
下面是所有 Trial 的状态。 包括:
* Trial 详情:Trial 的 id,持续时间,开始时间,结束时间,状态,精度和搜索空间。
* 如果在 OpenPAI 平台上运行,还可以看到 hdfsLog。
* Kill: 可终止正在运行的任务。
* 支持搜索某个特定的 Trial。
![](./img/QuickStart6.png)
* 中间结果图
![](./img/QuickStart7.png)
## 相关主题
* [尝试不同的 Tuner](Builtin_Tuner.md)
* [尝试不同的 Assessor](Builtin_Assessors.md)
* [使用命令行工具 nnictl](NNICTLDOC.md)
* [如何编写 Trial 代码](Trials.md)
* [如何在本机运行 Experiment (支持多 GPU 卡)?](tutorial_1_CR_exp_local_api.md)
* [如何在多机上运行 Experiment?](RemoteMachineMode.md)
* [如何在 OpenPAI 上运行 Experiment?](PAIMode.md)
* [如何通过 Kubeflow 在 Kubernetes 上运行 Experiment?](KubeflowMode.md)
* [如何通过 FrameworkController 在 Kubernetes 上运行 Experiment?](FrameworkControllerMode.md)
\ No newline at end of file
# 更改日志
## 发布 0.5.0 - 01/14/2019
### 主要功能
#### 支持新的 Tuner 和 Assessor
* 支持 [Metis tuner](./HowToChooseTuner.md#MetisTuner) 作为 NNI 的 Tuner。 **在线**超参调优的场景下,Metis 算法已经被证明非常有效。
* 支持 [ENAS customized tuner](https://github.com/countif/enas_nni)。由 GitHub 社区用户所贡献。它是神经网络的搜索算法,能够通过强化学习来学习神经网络架构,比 NAS 的性能更好。
* 支持 [Curve fitting (曲线拟合)Assessor](./HowToChooseTuner.md#Curvefitting),通过曲线拟合的策略来实现提前终止 Trial。
* 进一步支持 [Weight Sharing(权重共享)](./AdvancedNAS.md):为 NAS Tuner 通过 NFS 来提供权重共享。
#### 改进训练平台
* [FrameworkController 训练服务](./FrameworkControllerMode.md): 支持使用在 Kubernetes 上使用 FrameworkController。
* FrameworkController 是 Kubernetes 上非常通用的控制器(Controller),能用来运行基于各种机器学习框架的分布式作业,如 TensorFlow,Pytorch, MXNet 等。
* NNI 为作业定义了统一而简单的规范。
* 如何使用 FrameworkController 的 MNIST 样例。
#### 改进用户体验
* 为 OpenPAI, Kubeflow 和 FrameworkController 模式提供更好的日志支持。
* 改进后的日志架构能将尝试的 stdout/stderr 通过 HTTP POST 方式发送给 NNI 管理器。 NNI 管理器将 Trial 的 stdout/stderr 消息存储在本地日志文件中。
* 在 WEB 界面上显示 Trial 日志的链接。
* 支持将最终结果显示为键值对。
## 发布 0.4.1 - 12/14/2018
### 主要功能
#### 支持新的 Tuner
* 支持新 Tuner [network morphism](./HowToChooseTuner.md#NetworkMorphism)
#### 改进训练平台
*[Kubeflow 训练服务](KubeflowMode.md)的依赖从 kubectl CLI 迁移到 [Kubernetes API](https://kubernetes.io/docs/concepts/overview/kubernetes-api/) 客户端。
* Kubeflow 训练服务支持 [Pytorch-operator](https://github.com/kubeflow/pytorch-operator)
* 改进将本地代码文件上传到 OpenPAI HDFS 的性能。
* 修复 OpenPAI 在 WEB 界面的 Bug:当 OpenPAI 认证过期后,Web 界面无法更新 Trial 作业的状态。
#### 改进 NNICTL
* 在 nnictl 和 WEB 界面中显示 NNI 的版本信息。 可使用 **nnictl -v** 来显示安装的 NNI 版本。
#### 改进 WEB 界面
* 在 Experiment 运行中可修改并发数量
* 增加指向 NNI Github 的反馈链接,可直接创建问题
* 可根据指标,定制选择(最大或最小)的前 10 个 Trial。
* 为 dispatcher 和 nnimanager 提供下载日志的功能
* 为指标数值图提供自动缩放的数轴
* 改进 Annotation,支持在搜索空间中显示实际的选项
### 新样例
* [FashionMnist](https://github.com/Microsoft/nni/tree/master/examples/trials/network_morphism),使用 network morphism Tuner
* 使用 PyTorch 的[分布式 MNIST 样例](https://github.com/Microsoft/nni/tree/master/examples/trials/mnist-distributed-pytorch)
## 发布 0.4 - 12/6/2018
### 主要功能
* [Kubeflow 训练服务](./KubeflowMode.md)
* 支持 tf-operator
* Kubeflow 上的[分布式 Trial 样例](../examples/trials/mnist-distributed/dist_mnist.py)
* [网格搜索 Tuner](Builtin_Tuner.md#GridSearch)
* [Hyperband Tuner](Builtin_Tuner.md#Hyperband)
* 支持在 MAC 上运行 NNI Experiment
* WebUI
* 支持 hyperband Tuner
* 移除 tensorboard 按钮
* 显示 Experiment 的错误消息
* 显示搜索空间和 Trial 配置的行号
* 支持通过指定的 Trial id 来搜索
* 显示 Trial 的 hdfsLogPath
* 下载 Experiment 参数
### 其它
* 异步调度
* 更新 Docker 文件,增加 pytorch 库
* 重构 'nnictl stop' 过程,发送 SIGTERM 给 NNI 管理器进程,而不是调用停止 Restful API.
* 修复 OpenPAI 训练服务的 Bug
* 在 NNI 管理器中为 OpenPAI 集群配置文件支持 IP 配置(nniManagerIp),来修复用户计算机没有 eth0 设备的问题。
* codeDir 中的文件数量上限改为1000,避免用户无意中填写了 root 目录。
* 移除 OpenPAI 作业的 stdout 日志中无用的 ‘metrics is empty’。 在新指标被记录时,仅输出有用的消息,来减少用户检查 OpenPAI Trial 输出时的困惑。
* 在 Trial keeper 的开始增加时间戳。
## 发布 0.3.0 - 11/2/2018
### NNICTL 的新功能和更新
* 支持同时运行多个 Experiment。
在 v0.3 以前,NNI 仅支持一次运行一个 Experiment。 此版本开始,用户可以同时运行多个 Experiment。 每个 Experiment 都需要一个唯一的端口,第一个 Experiment 会像以前版本一样使用默认端口。 需要为其它 Experiment 指定唯一端口:
```bash
nnictl create --port 8081 --config <config file path>
```
* 支持更新最大 Trial 的数量。 使用 `nnictl update --help` 了解详情。 或参考 [NNICTL 说明](NNICTLDOC.md)来查看完整帮助。
### API 的新功能和更新
* <span style="color:red"><strong>不兼容的改动</strong></span>:nn.get_parameters() 改为 nni.get_next_parameter。 所有以前版本的样例将无法在 v0.3 上运行,需要重新克隆 NNI 代码库获取新样例。 如果在自己的代码中使用了 NNI,也需要相应的更新。
* 新 API **nni.get_sequence_id()**。 每个 Trial 任务都会被分配一个唯一的序列数字,可通过 nni.get_sequence_id() API 来获取。
```bash
git clone -b v0.3 https://github.com/Microsoft/nni.git
```
* **nni.report_final_result(result)** API 对结果参数支持更多的数据类型。
可用类型:
* int
* float
* 包含有 'default' 键值的 dict,'default' 的值必须为 int 或 float。 dict 可以包含任何其它键值对。
### 支持新的 Tuner
* **Batch Tuner(批处理调参器)** 会执行所有超参组合,可被用来批量提交 Trial 任务。
### 新样例
* 公共的 NNI Docker 映像:
```bash
docker pull msranni/nni:latest
```
* 新的尝试样例: [NNI Sklearn 样例](https://github.com/Microsoft/nni/tree/master/examples/trials/sklearn)
* 新的竞赛样例:[Kaggle Competition TGS Salt](https://github.com/Microsoft/nni/tree/master/examples/trials/kaggle-tgs-salt)
### 其它
* 界面重构,参考[网页文档](WebUI.md),了解如何使用新界面。
* 持续集成:NNI 已切换到 Azure pipelines。
* [0.3.0 的已知问题](https://github.com/Microsoft/nni/labels/nni030knownissues)
## 发布 0.2.0 - 9/29/2018
### 主要功能
* 支持 [OpenPAI](https://github.com/Microsoft/pai) (又称 pai) 训练平台 (参考[这里](./PAIMode.md)来了解如何在 pai 模式下提交 NNI 任务)
* 支持 pai 模式的训练服务。 NNI Trial 可发送至 OpenPAI 集群上运行
* NNI Trial 输出 (包括日志和模型文件) 会被复制到 OpenPAI 的 HDFS 中。
* 支持 [SMAC](https://www.cs.ubc.ca/~hutter/papers/10-TR-SMAC.pdf) Tuner (参考[这里](HowToChooseTuner.md),了解如何使用 SMAC Tuner)
* [SMAC](https://www.cs.ubc.ca/~hutter/papers/10-TR-SMAC.pdf) 基于 Sequential Model-Based Optimization (SMBO). 它会利用使用过的结果好的模型(高斯随机过程模型),并将随机森林引入到 SMBO 中,来处理分类参数。 NNI 的 SMAC 通过包装 [SMAC3](https://github.com/automl/SMAC3) 来支持。
* 支持将 NNI 安装在 [conda](https://conda.io/docs/index.html) 和 Python 虚拟环境中。
* 其它
* 更新 ga squad 样例与相关文档
* 用户体验改善及 Bug 修复
### 已知问题
[0.2.0 的已知问题](https://github.com/Microsoft/nni/labels/nni020knownissues)
## 发布 0.1.0 - 9/10/2018 (首个版本)
首次发布 Neural Network Intelligence (NNI)。
### 主要功能
* 安装和部署
* 支持 pip 和源代码安装
* 支持本机(包括多 GPU 卡)训练和远程多机训练模式
* Tuner ,Assessor 和 Trial
* 支持的自动机器学习算法包括: hyperopt_tpe, hyperopt_annealing, hyperopt_random, 和 evolution_tuner。
* 支持 Assessor(提前终止)算法包括:medianstop。
* 提供 Python API 来自定义 Tuner 和 Assessor
* 提供 Python API 来包装 Trial 代码,以便能在 NNI 中运行
* Experiment
* 提供命令行工具 'nnictl' 来管理 Experiment
* 提供网页界面来查看并管理 Experiment
* 持续集成
* 使用 Ubuntu 的 [travis-ci](https://github.com/travis-ci) 来支持持续集成
* 其它
* 支持简单的 GPU 任务调度
### 已知问题
[0.1.0 的已知问题](https://github.com/Microsoft/nni/labels/nni010knownissues)
\ No newline at end of file
参考
==================
.. toctree::
:maxdepth: 3
命令行<NNICTLDOC>
Annotation<AnnotationSpec>
配置<ExperimentConfig>
搜索空间<SearchSpaceSpec>
\ No newline at end of file
# 在多机上运行 Experiment
NNI 支持通过 SSH 通道在多台计算机上运行 Experiment,称为 `remote` 模式。 NNI 需要这些计算机的访问权限,并假定已配置好了深度学习训练环境。
例如:有三台服务器,登录账户为 `bob`(注意:账户不必在各台计算机上一致):
| IP | 用户名 | 密码 |
| -------- | --- | ------ |
| 10.1.1.1 | bob | bob123 |
| 10.1.1.2 | bob | bob123 |
| 10.1.1.3 | bob | bob123 |
## 设置 NNI 环境
按照[指南](QuickStart.md)在每台计算机上安装 NNI。
## 运行 Experiment
在另一台计算机,或在其中任何一台上安装 NNI,并运行 nnictl 工具。
`examples/trials/mnist-annotation` 为例。 `cat ~/nni/examples/trials/mnist-annotation/config_remote.yml` 来查看详细配置:
```yaml
authorName: default
experimentName: example_mnist
trialConcurrency: 1
maxExecDuration: 1h
maxTrialNum: 10
#可选项: local, remote, pai
trainingServicePlatform: remote
#可选项: true, false
useAnnotation: true
tuner:
#可选项: TPE, Random, Anneal, Evolution, BatchTuner
#SMAC (SMAC 需要通过 nnictl 安装)
builtinTunerName: TPE
classArgs:
#可选项: maximize, minimize
optimize_mode: maximize
trial:
command: python3 mnist.py
codeDir: .
gpuNum: 0
#local 模式下 machineList 可为空
machineList:
- ip: 10.1.1.1
username: bob
passwd: bob123
#使用默认端口 22 时,该配置可跳过
#port: 22
- ip: 10.1.1.2
username: bob
passwd: bob123
- ip: 10.1.1.3
username: bob
passwd: bob123
```
填好 `machineList` 部分,然后运行:
```bash
nnictl create --config ~/nni/examples/trials/mnist-annotation/config_remote.yml
```
来启动 Experiment。
\ No newline at end of file
# 在阅读理解上使用自动模型架构搜索
该样例展示了如何使用遗传算法为阅读理解任务找到好的模型架构。
## 1. 搜索空间
对于阅读理解项目,注意力和循环神经网络(RNN)已经被证明非常有效。 使用的搜索空间如下:
1. IDENTITY (Effectively 表示继续训练)。
2. INSERT-RNN-LAYER (插入 LSTM。 在 Experiment 中比较了 GRU 和 LSTM 的性能后,我们决定在这里采用 LSTM。)
3. REMOVE-RNN-LAYER
4. INSERT-ATTENTION-LAYER (插入注意力层。)
5. REMOVE-ATTENTION-LAYER
6. ADD-SKIP (在随机层之间一致).
7. REMOVE-SKIP (移除随机跳过).
![](https://github.com/Microsoft/nni/tree/master/examples/trials/ga_squad/ga_squad.png)
### 新版本
另一个时间更快,性能更好的版本正在开发中。 很快将发布。
## 2. 如何在本机运行此样例?
### 2.1 使用下载脚本来下载数据
执行下列命令来下载所需要的数据:
```bash
chmod +x ./download.sh
./download.sh
```
或手动下载
1. 在 https://rajpurkar.github.io/SQuAD-explorer/ 下载 "dev-v1.1.json" 和 "train-v1.1.json"。
```bash
wget https://rajpurkar.github.io/SQuAD-explorer/dataset/train-v1.1.json
wget https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json
```
2. 在 https://nlp.stanford.edu/projects/glove/ 下载 "glove.840B.300d.txt"。
```bash
wget http://nlp.stanford.edu/data/glove.840B.300d.zip
unzip glove.840B.300d.zip
```
### 2.2 更新配置
修改 `nni/examples/trials/ga_squad/config.yml`,以下是默认配置:
```yaml
authorName: default
experimentName: example_ga_squad
trialConcurrency: 1
maxExecDuration: 1h
maxTrialNum: 1
#可选项: local, remote
trainingServicePlatform: local
#可选项: true, false
useAnnotation: false
tuner:
codeDir: ~/nni/examples/tuners/ga_customer_tuner
classFileName: customer_tuner.py
className: CustomerTuner
classArgs:
optimize_mode: maximize
trial:
command: python3 trial.py
codeDir: ~/nni/examples/trials/ga_squad
gpuNum: 0
```
在 "Trial" 部分中,如果需要使用 GPU 来进行架构搜索,可将 `gpuNum``0` 改为 `1`。 根据训练时长,可以增加 `maxTrialNum``maxExecDuration`
### 2.3 提交任务
```bash
nnictl create --config ~/nni/examples/trials/ga_squad/config.yml
```
## 3 在 OpenPAI 上运行此样例
根据上传大小的限制,仅上传源代码,并在训练过程中下载数据。 本 Experiment 需要的内存 `memoryMB >= 32G`,训练过程可能需要数小时。
### 3.1 更新配置
修改 `nni/examples/trials/ga_squad/config_pai.yml`,以下是默认配置:
```yaml
authorName: default
experimentName: example_ga_squad
trialConcurrency: 1
maxExecDuration: 1h
maxTrialNum: 10
#可选项: local, remote, pai
trainingServicePlatform: pai
#可选项: true, false
useAnnotation: false
# nni_manager 的 ip
nniManagerIp: 10.10.10.10
tuner:
codeDir: ../../tuners/ga_customer_tuner
classFileName: customer_tuner.py
className: CustomerTuner
classArgs:
optimize_mode: maximize
trial:
command: chmod +x ./download.sh && ./download.sh && python3 trial.py
codeDir: https://github.com/Microsoft/nni/tree/master/examples/tuners/ga_customer_tuner
gpuNum: 0
cpuNum: 1
memoryMB: 32869
#在 OpenPAI 上运行 NNI 任务的 Docker 映像
image: msranni/nni:latest
#在 OpenPAI 的 hdfs 目录上存储数据的目录,如:'hdfs://host:port/directory'
dataDir: hdfs://10.10.10.10:9000/username/nni
#在 OpenPAI 的 hdfs 目录上存储输出的目录,如:'hdfs://host:port/directory'
outputDir: hdfs://10.10.10.10:9000/username/nni
paiConfig:
#登录 OpenPAI 的用户名
userName: username
#登录 OpenPAI 的密码
passWord: password
# OpenPAI 的 RESTful 服务器地址
host: 10.10.10.10
```
将默认值改为个人账户和服务器信息。 包括 `nniManagerIp`, `dataDir`, `outputDir`, `userName`, `passWord``host`
在 "trial" 部分中,如果需要使用 GPU 来进行架构搜索,可将 `gpuNum``0` 改为 `1`。 根据训练时长,可以增加 `maxTrialNum``maxExecDuration`
`trialConcurrency` 是并发运行的 Trial 的数量。如果将 `gpuNum` 设置为 1,则需要与 GPU 数量一致。
### 3.2 提交任务
```bash
nnictl create --config ~/nni/examples/trials/ga_squad/config_pai.yml
```
## 4. 代码实现
### 4.1 实现方法
基于进化算法架构的问答和其它样例一样,有两个部分:Trial 和 Tuner。
### 4.2 Trial
Trial 有大量的文件、函数和类。 这里只简单介绍最重要的文件:
* `attention.py` 包含了 Tensorflow 注意力算法的实现。
* `data.py` 包含了数据处理函数。
* `evaluate.py` 包含了评估脚本。
* `graph.py` 包含了计算图的定义。
* `rnn.py` 包含了 TensorFlow 的 GRU 实现。
* `train_model.py` 是整个文档模型的封装。
这些文件中,`trial.py``graph_to_tf.py` 非常特别。
`graph_to_tf.py` 有一个叫做 `graph_to_network`的函数,其框架代码如下:
```python
def graph_to_network(input1,
input2,
input1_lengths,
input2_lengths,
graph,
dropout_rate,
is_training,
num_heads=1,
rnn_units=256):
topology = graph.is_topology()
layers = dict()
layers_sequence_lengths = dict()
num_units = input1.get_shape().as_list()[-1]
layers[0] = input1*tf.sqrt(tf.cast(num_units, tf.float32)) + \
positional_encoding(input1, scale=False, zero_pad=False)
layers[1] = input2*tf.sqrt(tf.cast(num_units, tf.float32))
layers[0] = dropout(layers[0], dropout_rate, is_training)
layers[1] = dropout(layers[1], dropout_rate, is_training)
layers_sequence_lengths[0] = input1_lengths
layers_sequence_lengths[1] = input2_lengths
for _, topo_i in enumerate(topology):
if topo_i == '|':
continue
if graph.layers[topo_i].graph_type == LayerType.input.value:
# ......
elif graph.layers[topo_i].graph_type == LayerType.attention.value:
# ......
# 处理更多层
```
正如我们看到的,这个函数实际上是个编译器。它将内部模型的 DAG 配置`图`(在`模型配置格式`章节介绍)转换为 Tensorflow 的计算图。
```python
topology = graph.is_topology()
```
将内部图表示进行拓扑排序,代码在下列循环中:
```python
for _, topo_i in enumerate(topology):
```
执行实际转换,将每层映射为 TensorFlow 计算图中的一部分。
### 4.3 Tuner
Tuner 比 Trial 代码简单很多。 它们共用了同样的 `graph.py`。 此外,Tuner 有 `customer_tuner.py`,其中最重要的类是 `CustomerTuner`
```python
class CustomerTuner(Tuner):
# ......
def generate_parameters(self, parameter_id):
"""将一组 Trial 图配置作为序列化对象返回。
parameter_id : int
"""
if len(self.population) <= 0:
logger.debug("the len of poplution lower than zero.")
raise Exception('The population is empty')
pos = -1
for i in range(len(self.population)):
if self.population[i].result == None:
pos = i
break
if pos != -1:
indiv = copy.deepcopy(self.population[pos])
self.population.pop(pos)
temp = json.loads(graph_dumps(indiv.config))
else:
random.shuffle(self.population)
if self.population[0].result > self.population[1].result:
self.population[0] = self.population[1]
indiv = copy.deepcopy(self.population[0])
self.population.pop(1)
indiv.mutation()
graph = indiv.config
temp = json.loads(graph_dumps(graph))
# ......
```
重载函数 `generate_parameters` 实现了简单的变异算法。 代码如下:
```python
if self.population[0].result > self.population[1].result:
self.population[0] = self.population[1]
indiv = copy.deepcopy(self.population[0])
```
控制突变过程。 它会在种群中随机取出两个个体,对更好结果的一个保留数据,并突变另一个。
### 4.4 模型配置格式
这是模型配置的样例,在架构搜索过程中,从 Tuner 传入 Trial 的代码。
```json
{
"max_layer_num": 50,
"layers": [
{
"input_size": 0,
"type": 3,
"output_size": 1,
"input": [],
"size": "x",
"output": [4, 5],
"is_delete": false
},
{
"input_size": 0,
"type": 3,
"output_size": 1,
"input": [],
"size": "y",
"output": [4, 5],
"is_delete": false
},
{
"input_size": 1,
"type": 4,
"output_size": 0,
"input": [6],
"size": "x",
"output": [],
"is_delete": false
},
{
"input_size": 1,
"type": 4,
"output_size": 0,
"input": [5],
"size": "y",
"output": [],
"is_delete": false
},
{"Comment": "实际图会有更多层。"}
]
}
```
每个模型配置都有一个 "layers" 部分,这是层定义的 JSON 列表。 每层的定义也是一个 JSON 对象:
* `type` 是层的类型。 0, 1, 2, 3, 4 对应注意力、自注意力、RNN、输入和输出层。
* `size` 是输出的长度。 "x", "y" 对应文档长度和问题长度。
* `input_size` 是该层的输入数量。
* `input` 表示输入层的索引。
* `output` 是输出层的索引,该层会作为这些层的输入。
* `is_delete` 表示此层是否可用。
\ No newline at end of file
# 搜索空间
## 概述
在 NNI 中,Tuner 会根据搜索空间来取样生成参数和网络架构。搜索空间通过 JSON 文件来定义。
要定义搜索空间,需要定义变量名称、采样策略的类型及其参数。
* 搜索空间样例如下:
```yaml
{
"dropout_rate":{"_type":"uniform","_value":[0.1,0.5]},
"conv_size":{"_type":"choice","_value":[2,3,5,7]},
"hidden_size":{"_type":"choice","_value":[124, 512, 1024]},
"batch_size":{"_type":"choice","_value":[50, 250, 500]},
"learning_rate":{"_type":"uniform","_value":[0.0001, 0.1]}
}
```
将第一行作为样例。 `dropout_rate` 定义了一个变量,先验分布为均匀分布,范围从 `0.1``0.5`
## 类型
所有采样策略和参数如下:
* {"_type":"choice","_value":options}
* 这表示变量值应该是列表中的选项之一。 选项的元素也可以是 [nested](嵌套的)随机表达式。 在这种情况下,随机选项仅会在条件满足时出现。
* {"_type":"randint","_value":[upper]}
* 此变量为范围 [0, upper) 之间的随机整数。 这种分布的语义,在较远整数与附近整数之间的损失函数无太大关系, 这是用来描述随机种子的较好分布。 如果损失函数与较近的整数更相关,则应该使用某个"quantized"的连续分布,如quniform, qloguniform, qnormal 或 qlognormal。 注意,如果需要改动数字下限,可以使用 `quniform`
* {"_type":"uniform","_value":[low, high]}
* 变量是 low 和 high 之间均匀分布的值。
* 当优化时,此变量值会在两侧区间内。
* {"_type":"quniform","_value":[low, high, q]}
* 这表示变量值会类似于 round(uniform(low, high) / q) * q
* 适用于离散,同时反映了某种"平滑"的数值,但上下限都有限制。 如果需要从范围 [low, high] 中均匀选择整数,可以如下定义 `_value``[low, high, 1]`
* {"_type":"loguniform","_value":[low, high]}
* 变量值在范围 [low, high] 中是 loguniform 分布,如 exp(uniform(log(low), log(high))),因此返回值是对数均匀分布的。
* 当优化时,此变量必须是正数。
* {"_type":"qloguniform","_value":[low, high, q]}
* 这表示变量值会类似于 round(loguniform(low, high)) / q) * q
* 适用于值是“平滑”的离散变量,但上下限均有限制。
* {"_type":"normal","_value":[label, mu, sigma]}
* 变量值为实数,且为正态分布,均值为 mu,标准方差为 sigma。 优化时,此变量不受约束。
* {"_type":"qnormal","_value":[label, mu, sigma, q]}
* 这表示变量值会类似于 round(normal(mu, sigma) / q) * q
* 适用于在 mu 周围的离散变量,且没有上下限限制。
* {"_type":"lognormal","_value":[label, mu, sigma]}
* 变量值为 exp(normal(mu, sigma)) 分布,范围值是对数的正态分布。 当优化时,此变量必须是正数。
* {"_type":"qlognormal","_value":[label, mu, sigma, q]}
* 这表示变量值会类似于 round(exp(normal(mu, sigma)) / q) * q
* 适用于值是“平滑”的离散变量,但某一边有界。
## 每种 Tuner 支持的搜索空间类型
| | choice | randint | uniform | quniform | loguniform | qloguniform | normal | qnormal | lognormal | qlognormal |
|:-------------------:|:--------:|:--------:|:--------:|:--------:|:----------:|:-----------:|:--------:|:--------:|:---------:|:----------:|
| TPE Tuner | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; |
| Random Search Tuner | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; |
| Anneal Tuner | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; |
| Evolution Tuner | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; |
| SMAC Tuner | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | | | | | |
| Batch Tuner | &#10003; | | | | | | | | | |
| Grid Search Tuner | &#10003; | | | &#10003; | | &#10003; | | | | |
| Hyperband Advisor | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; | &#10003; |
| Metis Tuner | &#10003; | &#10003; | &#10003; | &#10003; | | | | | | |
注意,在 Grid Search Tuner 中,为了使用方便 `quniform``qloguniform` 的定义也有所改变,其中的 q 表示采样值的数量。 详情如下:
* 类型 'quniform' 接收三个值 [low, high, q], 其中 [low, high] 指定了范围,而 'q' 指定了会被均匀采样的值的数量。 注意 q 至少为 2。 它的第一个采样值为 'low',每个采样值都会比前一个大 (high-low)/q 。
* 类型 'qloguniform' 的行为与 'quniform' 类似,不同处在于首先将范围改为 [log(low), log(high)] 采样后,再将数值还原。
注意 Metis Tuner 当前仅支持在 `choice` 中使用数值。
\ No newline at end of file
**设置 NNI 开发环境**
===
## 调试 NNI 源代码的最佳实践
要调试 NNI 源代码,需要 Ubuntu 16.04 或更高版本系统的开发环境,并需要安装 Python 3.x 以及 pip3,然后遵循以下步骤。
**1. 克隆源代码**
运行命令
git clone https://github.com/Microsoft/nni.git
来克隆源代码
**2. 准备调试环境并安装依赖项**
将目录切换到源码目录,然后运行命令
make install-dependencies
来安装环境的依赖项工具
**3. 生成源代码**
运行命令
make build
来生成源代码
**4. 将 NNI 安装到开发环境中**
运行命令
make dev-install
来安装分发内容到开发环境,并创建 cli 脚本
**5. 检查环境是否正确**
Trial 启动 Experiment 来检查环境。 例如,运行命令
nnictl create --config ~/nni/examples/trials/mnist/config.yml
并打开网页界面查看
**6. 重新部署**
代码改动后,用**第 3 步**来重新生成代码,改动会立即生效。
* * *
最后,希望一切顺利。 参考[贡献](./CONTRIBUTING.md)文档,来了解更多创建拉取请求或问题的指南。
\ No newline at end of file
# 实现 NNI 的 Trial(尝试)代码
**Trial(尝试)**是将一组参数组合(例如,超参)在模型上独立的一次尝试。
定义 NNI 的 Trial,需要首先定义参数组,并更新模型代码。 NNI 有两种方法来实现 Trial:[NNI API](#nni-api) 以及 [NNI Python annotation](#nni-annotation)。 参考[这里的](#more-examples)更多 Trial 样例。
<a name="nni-api"></a>
## NNI API
### 第一步:准备搜索空间参数文件。
样例如下:
```json
{
"dropout_rate":{"_type":"uniform","_value":[0.1,0.5]},
"conv_size":{"_type":"choice","_value":[2,3,5,7]},
"hidden_size":{"_type":"choice","_value":[124, 512, 1024]},
"learning_rate":{"_type":"uniform","_value":[0.0001, 0.1]}
}
```
参考 [SearchSpaceSpec.md](./SearchSpaceSpec.md) 进一步了解搜索空间。 Tuner 会根据搜索空间来生成配置,即从每个超参的范围中选一个值。
### 第二步:更新模型代码
* Import NNI
在 Trial 代码中加上 `import nni`
* 从 Tuner 获得参数值
```python
RECEIVED_PARAMS = nni.get_next_parameter()
```
`RECEIVED_PARAMS` 是一个对象,如: `{"conv_size": 2, "hidden_size": 124, "learning_rate": 0.0307, "dropout_rate": 0.2029}`.
* 定期返回指标数据(可选)
```python
nni.report_intermediate_result(metrics)
```
`指标`可以是任意的 Python 对象。 如果使用了 NNI 内置的 Tuner/Assessor,`指标`只可以是两种类型:1) 数值类型,如 float、int, 2) dict 对象,其中必须由键名为 `default`,值为数值的项目。 `指标`会发送给[Assessor](Builtin_Assessors.md)。 通常,`指标`是损失值或精度。
* 返回配置的最终性能
```python
nni.report_final_result(metrics)
```
`指标`也可以是任意的 Python 对象。 如果使用了内置的 Tuner/Assessor,`指标`格式和 `report_intermediate_result` 中一样,这个数值表示模型的性能,如精度、损失值等。 `指标`会发送给 [Tuner](Builtin_Tuner.md)
### 第三步:启用 NNI API
要启用 NNI 的 API 模式,需要将 useAnnotation 设置为 *false*,并提供搜索空间文件的路径(即第一步中定义的文件):
```yaml
useAnnotation: false
searchSpacePath: /path/to/your/search_space.json
```
参考 [这里](ExperimentConfig.md) 进一步了解如何配置实验。
*参考[这里](sdk_reference.md),了解更多 NNI API (例如:`nni.get_sequence_id()`)。
<a name="nni-annotation"></a>
## NNI Annotation
另一种实现 Trial 的方法是使用 Python 注释来标记 NNI。 就像其它 Python Annotation,NNI 的 Annotation 和代码中的注释一样。 不需要在代码中做大量改动。 只需要添加一些 NNI Annotation,就能够:
* 标记需要调整的参数变量
* 指定变量的搜索空间范围
* 标记哪个变量需要作为中间结果范围给 `Assessor`
* 标记哪个变量需要作为最终结果(例如:模型精度)返回给 `Tuner`
同样以 MNIST 为例,只需要两步就能用 NNI Annotation 来实现 Trial 代码。
### 第一步:在代码中加入 Annotation
下面是加入了 Annotation 的 TensorFlow 代码片段,高亮的 4 行 Annotation 用于:
1. 调优 batch\_size 和 dropout\_rate
2. 每执行 100 步返回 test\_acc
3. 最后返回 test\_acc 作为最终结果。
新添加的代码都是注释,不会影响以前的执行逻辑。因此这些代码仍然能在没有安装 NNI 的环境中运行。
```diff
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
+ """@nni.variable(nni.choice(50, 250, 500), name=batch_size)"""
batch_size = 128
for i in range(10000):
batch = mnist.train.next_batch(batch_size)
+ """@nni.variable(nni.choice(1, 5), name=dropout_rate)"""
dropout_rate = 0.5
mnist_network.train_step.run(feed_dict={mnist_network.images: batch[0],
mnist_network.labels: batch[1],
mnist_network.keep_prob: dropout_rate})
if i % 100 == 0:
test_acc = mnist_network.accuracy.eval(
feed_dict={mnist_network.images: mnist.test.images,
mnist_network.labels: mnist.test.labels,
mnist_network.keep_prob: 1.0})
+ """@nni.report_intermediate_result(test_acc)"""
test_acc = mnist_network.accuracy.eval(
feed_dict={mnist_network.images: mnist.test.images,
mnist_network.labels: mnist.test.labels,
mnist_network.keep_prob: 1.0})
+ """@nni.report_final_result(test_acc)"""
```
**注意**
* `@nni.variable` 会对它的下面一行进行修改,左边被赋值变量必须在 `@nni.variable``name` 参数中指定。
* `@nni.report_intermediate_result`/`@nni.report_final_result` 会将数据发送给 Assessor、Tuner。
Annotation 的语法和用法等,参考 [Annotation](AnnotationSpec.md)
### 第二步:启用 Annotation
在 YAML 配置文件中设置 *useAnnotation* 为 true 来启用 Annotation:
useAnnotation: true
<a name="more-examples"></a>
## 更多 Trial 的样例
* [MNIST 样例](mnist_examples.md)
* [为 CIFAR 10 分类找到最佳的 optimizer](cifar10_examples.md)
* [如何在 NNI 调优 SciKit-learn 的参数](sklearn_examples.md)
* [在阅读理解上使用自动模型架构搜索。](SQuAD_evolution_examples.md)
* [如何在 NNI 上调优 GBDT](gbdt_example.md)
\ No newline at end of file
######################
教程
######################
.. toctree::
安装<Installation>
实现 Trial<Trials>
Tuner<tuners>
Assessor<assessors>
Web 界面<WebUI>
训练平台<training_services>
高级功能<advanced>
\ No newline at end of file
# Web 界面
## 查看概要页面
点击标签 "Overview"。
* 查看 Experiment 的配置和搜索空间内容。
* 支持下载 Experiment 结果。
![](./img/webui-img/over1.png)
* 查看最好结果的 Trial。
![](./img/webui-img/over2.png)
## 查看任务默认指标
点击 "Default Metric" 来查看所有 Trial 的点图。 悬停鼠标来查看默认指标和搜索空间信息。
![](./img/accuracy.png)
## 查看超参
点击 "Hyper Parameter" 标签查看图像。
* 可选择百分比查看最好的 Trial。
* 选择两个轴来交换位置。
![](./img/hyperPara.png)
## 查看 Trial 运行时间
点击 "Trial Duration" 标签来查看柱状图。
![](./img/trial_duration.png)
## 查看 Trial 状态
点击 "Trials Detail" 标签查看所有 Trial 的状态。 特别是:
* Trial 详情:Trial 的 id,持续时间,开始时间,结束时间,状态,精度和搜索空间。
![](./img/webui-img/detail-local.png)
* 如果在 OpenPAI 或 Kubeflow 平台上运行,还可以看到 hdfsLog。
![](./img/webui-img/detail-pai.png)
* Kill: 可终止正在运行的任务。
* 支持搜索某个特定的 Trial。
* 中间结果图。
![](./img/intermediate.png)
\ No newline at end of file
高级功能
=====================
.. toctree::
多阶段<multiPhase>
高级网络架构搜索(AdvancedNAS)<AdvancedNAS>
\ No newline at end of file
Assessor(评估器)
==============
为了节省计算资源,在 NNI 中可通过创建 **Assessor**,来配置提前终止策略。
Assessor 从 Trial 中接收中间结果,并通过指定的算法决定此 Trial 是否应该终止。 一旦 Trial 满足了提前终止策略(这表示 Assessor 认为最终结果不会太好),Assessor 会终止此 Trial,并将其状态标志为 `"EARLY_STOPPED"`。
这是 MNIST 在使用了 'Curvefitting' Assessor 的 'maximize' 模式后的实验结果,可以看到 Assessor 成功的将大量最终结果不好的 Trial **提前结束**了。 使用 Assessor,能在相同的计算资源下,得到更好的结果。
*实现代码:config_assessor.yml <https://github.com/Microsoft/nni/blob/master/examples/trials/mnist/config_assessor.yml>*
.. image:: ./img/Assessor.png
与 Tuner 类似,可使用内置的 Assessor,也可以自定义 Assessor。 参考下列教程,获取详细信息:
.. toctree::
内置 Assessor<Builtin_Assessors>
自定义 Assessor<Customize_Assessor>
# CIFAR-10 样例
## 概述
[CIFAR-10](https://www.cs.toronto.edu/~kriz/cifar.html) 分类是机器学习中常用的基准问题。 CIFAR-10 数据集是图像的集合。 它也是机器学习领域最常用的数据集之一,包含 60000 万张 32x32 的图像,共有 10 个分类。 因此以 CIFAR-10 分类为例来介绍 NNI 的用法。
### **目标**
总所周知,模型 optimizer (优化器)的选择直接影响了最终指标的性能。 本教程的目标是**调优出性能更好的优化器**,从而为图像识别训练出一个相对较小的卷积网络(CNN)。
本例中,选择了以下常见的深度学习优化器:
> "SGD", "Adadelta", "Adagrad", "Adam", "Adamax"
### **实验**
#### 准备
此样例需要安装 PyTorch。 PyTorch 安装包需要选择所基于的 Python 和 CUDA 版本。
这是环境 python==3.5 且 cuda == 8.0 的样例,然后用下列命令来安装 [ PyTorch](https://pytorch.org/)
```bash
python3 -m pip install http://download.pytorch.org/whl/cu80/torch-0.4.1-cp35-cp35m-linux_x86_64.whl
python3 -m pip install torchvision
```
#### NNI 与 CIFAR-10
**搜索空间**
正如本文目标,要为 CIFAR-10 找到最好的`优化器`。 使用不同的优化器时,还要相应的调整`学习率``网络架构`。 因此,选择这三个参数作为超参,并创建如下的搜索空间。
```json
{
"lr":{"_type":"choice", "_value":[0.1, 0.01, 0.001, 0.0001]},
"optimizer":{"_type":"choice", "_value":["SGD", "Adadelta", "Adagrad", "Adam", "Adamax"]},
"model":{"_type":"choice", "_value":["vgg", "resnet18", "googlenet", "densenet121", "mobilenet", "dpn92", "senet18"]}
}
```
*实现代码:[search_space.json](https://github.com/Microsoft/nni/blob/master/examples/trials/cifar10_pytorch/search_space.json)*
**Trial(尝试)**
这是超参集合的训练代码,关注以下几点:
* 使用 `nni.get_next_parameter()` 来获取下一组训练的超参组合。
* 使用 `nni.report_intermediate_result(acc)` 在每个 epoch 结束时返回中间结果。
* 使用 `nni.report_intermediate_result(acc)` 在每个 Trial 结束时返回最终结果。
*实现代码:[main.py](https://github.com/Microsoft/nni/blob/master/examples/trials/cifar10_pytorch/main.py)*
也可以直接使用以前的代码来修改,参考:[如何编写 Trial](./Trials.md)
**配置**
这是在本机运行 Experiment 的样例(多GPU):
代码:[examples/trials/cifar10_pytorch/config.yml](https://github.com/Microsoft/nni/blob/master/examples/trials/cifar10_pytorch/config.yml)
这是在 OpenPAI 上运行 Experiment 的样例:
代码:[examples/trials/cifar10_pytorch/config_pai.yml](https://github.com/Microsoft/nni/blob/master/examples/trials/cifar10_pytorch/config_pai.yml)
*完整样例:[examples/trials/cifar10_pytorch/](https://github.com/Microsoft/nni/tree/master/examples/trials/cifar10_pytorch)*
#### 运行 Experiment
以上即为 Experiment 的代码介绍,**从命令行运行 config.yml 文件来开始 Experiment**
```bash
nnictl create --config nni/examples/trials/cifar10_pytorch/config.yml
```
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment