Unverified Commit f9ee589c authored by SparkSnail's avatar SparkSnail Committed by GitHub
Browse files

Merge pull request #222 from microsoft/master

merge master
parents 36e6e350 4f3ee9cb
...@@ -22,8 +22,8 @@ jobs: ...@@ -22,8 +22,8 @@ jobs:
cd src/nni_manager cd src/nni_manager
yarn eslint yarn eslint
# uncomment following 2 lines to enable webui eslint # uncomment following 2 lines to enable webui eslint
# cd ../webui cd ../webui
# yarn eslint yarn eslint
displayName: 'Run eslint' displayName: 'Run eslint'
- script: | - script: |
python3 -m pip install torch==0.4.1 --user python3 -m pip install torch==0.4.1 --user
......
...@@ -54,6 +54,8 @@ assessor: ...@@ -54,6 +54,8 @@ assessor:
Please noted in **2**. The object `trial_history` are exact the object that Trial send to Assessor by using SDK `report_intermediate_result` function. Please noted in **2**. The object `trial_history` are exact the object that Trial send to Assessor by using SDK `report_intermediate_result` function.
The working directory of your assessor is `<home>/nni/experiments/<experiment_id>/log`, which can be retrieved with environment variable `NNI_LOG_DIRECTORY`,
More detail example you could see: More detail example you could see:
> * [medianstop-assessor](https://github.com/Microsoft/nni/tree/master/src/sdk/pynni/nni/medianstop_assessor) > * [medianstop-assessor](https://github.com/Microsoft/nni/tree/master/src/sdk/pynni/nni/medianstop_assessor)
> * [curvefitting-assessor](https://github.com/Microsoft/nni/tree/master/src/sdk/pynni/nni/curvefitting_assessor) > * [curvefitting-assessor](https://github.com/Microsoft/nni/tree/master/src/sdk/pynni/nni/curvefitting_assessor)
\ No newline at end of file
...@@ -34,10 +34,13 @@ trial: ...@@ -34,10 +34,13 @@ trial:
cpuNum: 1 cpuNum: 1
memoryMB: 8196 memoryMB: 8196
image: msranni/nni:latest image: msranni/nni:latest
virtualCluster: default
nniManagerNFSMountPath: /home/user/mnt
containerNFSMountPath: /mnt/data/user
# Configuration to access OpenPAI Cluster # Configuration to access OpenPAI Cluster
paiConfig: paiConfig:
userName: your_pai_nni_user userName: your_pai_nni_user
passWord: your_pai_password token: your_pai_token
host: 10.1.1.1 host: 10.1.1.1
``` ```
...@@ -53,52 +56,13 @@ Compared with [LocalMode](LocalMode.md) and [RemoteMachineMode](RemoteMachineMod ...@@ -53,52 +56,13 @@ Compared with [LocalMode](LocalMode.md) and [RemoteMachineMode](RemoteMachineMod
* We already build a docker image [nnimsra/nni](https://hub.docker.com/r/msranni/nni/) on [Docker Hub](https://hub.docker.com/). It contains NNI python packages, Node modules and javascript artifact files required to start experiment, and all of NNI dependencies. The docker file used to build this image can be found at [here](https://github.com/Microsoft/nni/tree/master/deployment/docker/Dockerfile). You can either use this image directly in your config file, or build your own image based on it. * We already build a docker image [nnimsra/nni](https://hub.docker.com/r/msranni/nni/) on [Docker Hub](https://hub.docker.com/). It contains NNI python packages, Node modules and javascript artifact files required to start experiment, and all of NNI dependencies. The docker file used to build this image can be found at [here](https://github.com/Microsoft/nni/tree/master/deployment/docker/Dockerfile). You can either use this image directly in your config file, or build your own image based on it.
* virtualCluster * virtualCluster
* Optional key. Set the virtualCluster of OpenPAI. If omitted, the job will run on default virtual cluster. * Optional key. Set the virtualCluster of OpenPAI. If omitted, the job will run on default virtual cluster.
* shmMB * nniManagerNFSMountPath
* Optional key. Set the shmMB configuration of OpenPAI, it set the shared memory for one task in the task role. * Required key. Set the mount path in your nniManager machine.
* authFile * containerNFSMountPath
* Optional key, Set the auth file path for private registry while using PAI mode, [Refer](https://github.com/microsoft/pai/blob/2ea69b45faa018662bc164ed7733f6fdbb4c42b3/docs/faq.md#q-how-to-use-private-docker-registry-job-image-when-submitting-an-openpai-job), you can prepare the authFile and simply provide the local path of this file, NNI will upload this file to HDFS for you. * Required key. Set the mount path in your container used in PAI.
* portList * paiStoragePlugin
* Optional key. Set the portList configuration of OpenPAI, it specifies a list of port used in container, [Refer](https://github.com/microsoft/pai/blob/b2324866d0280a2d22958717ea6025740f71b9f0/docs/job_tutorial.md#specification). * Required key. Set the storage plugin name used in PAI.
The config schema in NNI is shown below:
```
portList:
- label: test
beginAt: 8080
portNumber: 2
```
Let's say you want to launch a tensorboard in the mnist example using the port. So the first step is to write a wrapper script `launch_pai.sh` of `mnist.py`.
```bash
export TENSORBOARD_PORT=PAI_PORT_LIST_${PAI_CURRENT_TASK_ROLE_NAME}_0_tensorboard
tensorboard --logdir . --port ${!TENSORBOARD_PORT} &
python3 mnist.py
```
The config file of portList should be filled as following:
```yaml
trial:
command: bash launch_pai.sh
portList:
- label: tensorboard
beginAt: 0
portNumber: 1
```
NNI support two kind of authorization method in PAI, including password and PAI token, [refer](https://github.com/microsoft/pai/blob/b6bd2ab1c8890f91b7ac5859743274d2aa923c22/docs/rest-server/API.md#2-authentication). The authorization is configured in `paiConfig` field.
For password authorization, the `paiConfig` schema is:
```
paiConfig:
userName: your_pai_nni_user
passWord: your_pai_password
host: 10.1.1.1
```
For pai token authorization, the `paiConfig` schema is:
```
paiConfig:
userName: your_pai_nni_user
token: your_pai_token
host: 10.1.1.1
```
Once complete to fill NNI experiment config file and save (for example, save as exp_pai.yml), then run the following command Once complete to fill NNI experiment config file and save (for example, save as exp_pai.yml), then run the following command
``` ```
...@@ -121,9 +85,7 @@ And you will be redirected to HDFS web portal to browse the output files of that ...@@ -121,9 +85,7 @@ And you will be redirected to HDFS web portal to browse the output files of that
You can see there're three fils in output folder: stderr, stdout, and trial.log You can see there're three fils in output folder: stderr, stdout, and trial.log
## data management ## data management
If your training data is not too large, it could be put into codeDir, and nni will upload the data to hdfs, or you could build your own docker image with the data. If you have large dataset, it's not appropriate to put the data in codeDir, and you could follow the [guidance](https://github.com/microsoft/pai/blob/master/docs/user/storage.md) to mount the data folder in container. Befour using NNI to start your experiment, users should set the corresponding mount data path in your nniManager machine. PAI has their own storage(NFS, AzureBlob ...), and the storage will used in PAI will be mounted to the container when it start a job. Users should set the PAI storage type by `paiStoragePlugin` field to choose a storage in PAI. Then users should mount the storage to their nniManager machine, and set the `nniManagerNFSMountPath` field in configuration file, NNI will generate bash files and copy data in `codeDir` to the `nniManagerNFSMountPath` folder, then NNI will start a trial job. The data in `nniManagerNFSMountPath` will be sync to PAI storage, and will be mounted to PAI's container. The data path in container is set in `containerNFSMountPath`, NNI will enter this folder first, and then run scripts to start a trial job.
If you also want to save trial's other output into HDFS, like model files, you can use environment variable `NNI_OUTPUT_DIR` in your trial code to save your own output files, and NNI SDK will copy all the files in `NNI_OUTPUT_DIR` from trial's container to HDFS, the target path is `hdfs://host:port/{username}/nni/{experiments}/{experimentId}/trials/{trialId}/nnioutput`
## version check ## version check
NNI support version check feature in since version 0.6. It is a policy to insure the version of NNIManager is consistent with trialKeeper, and avoid errors caused by version incompatibility. NNI support version check feature in since version 0.6. It is a policy to insure the version of NNIManager is consistent with trialKeeper, and avoid errors caused by version incompatibility.
......
**Run an Experiment on OpenpaiYarn**
===
The original `pai` mode is modificated to `paiYarn` mode, which is a distributed training platform based on Yarn.
## Setup environment
Install NNI, follow the install guide [here](../Tutorial/QuickStart.md).
## Run an experiment
Use `examples/trials/mnist-annotation` as an example. The NNI config YAML file's content is like:
```yaml
authorName: your_name
experimentName: auto_mnist
# how many trials could be concurrently running
trialConcurrency: 2
# maximum experiment running duration
maxExecDuration: 3h
# empty means never stop
maxTrialNum: 100
# choice: local, remote, pai, paiYarn
trainingServicePlatform: paiYarn
# search space file
searchSpacePath: search_space.json
# choice: 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: msranni/nni:latest
# Configuration to access OpenpaiYarn Cluster
paiYarnConfig:
userName: your_paiYarn_nni_user
passWord: your_paiYarn_password
host: 10.1.1.1
```
Note: You should set `trainingServicePlatform: paiYarn` in NNI config YAML file if you want to start experiment in paiYarn mode.
Compared with [LocalMode](LocalMode.md) and [RemoteMachineMode](RemoteMachineMode.md), trial configuration in paiYarn mode have these additional keys:
* cpuNum
* Required key. Should be positive number based on your trial program's CPU requirement
* memoryMB
* Required key. Should be positive number based on your trial program's memory requirement
* image
* Required key. In paiYarn mode, your trial program will be scheduled by OpenpaiYarn to run in [Docker container](https://www.docker.com/). This key is used to specify the Docker image used to create the container in which your trial will run.
* We already build a docker image [nnimsra/nni](https://hub.docker.com/r/msranni/nni/) on [Docker Hub](https://hub.docker.com/). It contains NNI python packages, Node modules and javascript artifact files required to start experiment, and all of NNI dependencies. The docker file used to build this image can be found at [here](https://github.com/Microsoft/nni/tree/master/deployment/docker/Dockerfile). You can either use this image directly in your config file, or build your own image based on it.
* virtualCluster
* Optional key. Set the virtualCluster of OpenpaiYarn. If omitted, the job will run on default virtual cluster.
* shmMB
* Optional key. Set the shmMB configuration of OpenpaiYarn, it set the shared memory for one task in the task role.
* authFile
* Optional key, Set the auth file path for private registry while using paiYarn mode, [Refer](https://github.com/microsoft/paiYarn/blob/2ea69b45faa018662bc164ed7733f6fdbb4c42b3/docs/faq.md#q-how-to-use-private-docker-registry-job-image-when-submitting-an-openpaiYarn-job), you can prepare the authFile and simply provide the local path of this file, NNI will upload this file to HDFS for you.
* portList
* Optional key. Set the portList configuration of OpenpaiYarn, it specifies a list of port used in container, [Refer](https://github.com/microsoft/paiYarn/blob/b2324866d0280a2d22958717ea6025740f71b9f0/docs/job_tutorial.md#specification).
The config schema in NNI is shown below:
```
portList:
- label: test
beginAt: 8080
portNumber: 2
```
Let's say you want to launch a tensorboard in the mnist example using the port. So the first step is to write a wrapper script `launch_paiYarn.sh` of `mnist.py`.
```bash
export TENSORBOARD_PORT=paiYarn_PORT_LIST_${paiYarn_CURRENT_TASK_ROLE_NAME}_0_tensorboard
tensorboard --logdir . --port ${!TENSORBOARD_PORT} &
python3 mnist.py
```
The config file of portList should be filled as following:
```yaml
trial:
command: bash launch_paiYarn.sh
portList:
- label: tensorboard
beginAt: 0
portNumber: 1
```
NNI support two kind of authorization method in paiYarn, including password and paiYarn token, [refer](https://github.com/microsoft/paiYarn/blob/b6bd2ab1c8890f91b7ac5859743274d2aa923c22/docs/rest-server/API.md#2-authentication). The authorization is configured in `paiYarnConfig` field.
For password authorization, the `paiYarnConfig` schema is:
```
paiYarnConfig:
userName: your_paiYarn_nni_user
passWord: your_paiYarn_password
host: 10.1.1.1
```
For paiYarn token authorization, the `paiYarnConfig` schema is:
```
paiYarnConfig:
userName: your_paiYarn_nni_user
token: your_paiYarn_token
host: 10.1.1.1
```
Once complete to fill NNI experiment config file and save (for example, save as exp_paiYarn.yml), then run the following command
```
nnictl create --config exp_paiYarn.yml
```
to start the experiment in paiYarn mode. NNI will create OpenpaiYarn job for each trial, and the job name format is something like `nni_exp_{experiment_id}_trial_{trial_id}`.
You can see jobs created by NNI in the OpenpaiYarn cluster's web portal, like:
![](../../img/nni_paiYarn_joblist.jpg)
Notice: In paiYarn mode, NNIManager will start a rest server and listen on a port which is your NNI WebUI's port plus 1. For example, if your WebUI port is `8080`, the rest server will listen on `8081`, to receive metrics from trial job running in Kubernetes. So you should `enable 8081` TCP port in your firewall rule to allow incoming traffic.
Once a trial job is completed, you can goto NNI WebUI's overview page (like http://localhost:8080/oview) to check trial's information.
Expand a trial information in trial list view, click the logPath link like:
![](../../img/nni_webui_joblist.jpg)
And you will be redirected to HDFS web portal to browse the output files of that trial in HDFS:
![](../../img/nni_trial_hdfs_output.jpg)
You can see there're three fils in output folder: stderr, stdout, and trial.log
## data management
If your training data is not too large, it could be put into codeDir, and nni will upload the data to hdfs, or you could build your own docker image with the data. If you have large dataset, it's not appropriate to put the data in codeDir, and you could follow the [guidance](https://github.com/microsoft/paiYarn/blob/master/docs/user/storage.md) to mount the data folder in container.
If you also want to save trial's other output into HDFS, like model files, you can use environment variable `NNI_OUTPUT_DIR` in your trial code to save your own output files, and NNI SDK will copy all the files in `NNI_OUTPUT_DIR` from trial's container to HDFS, the target path is `hdfs://host:port/{username}/nni/{experiments}/{experimentId}/trials/{trialId}/nnioutput`
## version check
NNI support version check feature in since version 0.6. It is a policy to insure the version of NNIManager is consistent with trialKeeper, and avoid errors caused by version incompatibility.
Check policy:
1. NNIManager before v0.6 could run any version of trialKeeper, trialKeeper support backward compatibility.
2. Since version 0.6, NNIManager version should keep same with triakKeeper version. For example, if NNIManager version is 0.6, trialKeeper version should be 0.6 too.
3. Note that the version check feature only check first two digits of version.For example, NNIManager v0.6.1 could use trialKeeper v0.6 or trialKeeper v0.6.2, but could not use trialKeeper v0.5.1 or trialKeeper v0.7.
If you could not run your experiment and want to know if it is caused by version check, you could check your webUI, and there will be an error message about version check.
![](../../img/version_check.png)
...@@ -160,6 +160,7 @@ Similar to TPE, SMAC is also a black-box tuner which can be tried in various sce ...@@ -160,6 +160,7 @@ Similar to TPE, SMAC is also a black-box tuner which can be tried in various sce
**Requirement of classArgs** **Requirement of classArgs**
* **optimize_mode** (*maximize or minimize, optional, default = maximize*) - If 'maximize', the tuner will target to maximize metrics. If 'minimize', the tuner will target to minimize metrics. * **optimize_mode** (*maximize or minimize, optional, default = maximize*) - If 'maximize', the tuner will target to maximize metrics. If 'minimize', the tuner will target to minimize metrics.
* **config_dedup** (*True or False, optional, default = False*) - If True, the tuner will not generate a configuration that has been already generated. If False, a configuration may be generated twice, but it is rare for relatively large search space.
**Usage example** **Usage example**
......
...@@ -33,6 +33,8 @@ advisor: ...@@ -33,6 +33,8 @@ advisor:
arg1: value1 arg1: value1
``` ```
**Note that** The working directory of your advisor is `<home>/nni/experiments/<experiment_id>/log`, which can be retrieved with environment variable `NNI_LOG_DIRECTORY`.
## Example ## Example
Here we provide an [example](https://github.com/microsoft/nni/tree/master/examples/tuners/mnist_keras_customized_advisor). Here we provide an [example](https://github.com/microsoft/nni/tree/master/examples/tuners/mnist_keras_customized_advisor).
...@@ -77,7 +77,7 @@ parameters = {"dropout": 0.3, "learning_rate": 0.4} ...@@ -77,7 +77,7 @@ parameters = {"dropout": 0.3, "learning_rate": 0.4}
value = 0.93 value = 0.93
``` ```
**Note that** if you want to access a file (e.g., `data.txt`) in the directory of your own tuner, you cannot use `open('data.txt', 'r')`. Instead, you should use the following: **Note that** The working directory of your tuner is `<home>/nni/experiments/<experiment_id>/log`, which can be retrieved with environment variable `NNI_LOG_DIRECTORY`, therefore, if you want to access a file (e.g., `data.txt`) in the directory of your own tuner, you cannot use `open('data.txt', 'r')`. Instead, you should use the following:
```python ```python
_pwd = os.path.dirname(__file__) _pwd = os.path.dirname(__file__)
......
...@@ -35,7 +35,6 @@ def train(model, quantizer, device, train_loader, optimizer): ...@@ -35,7 +35,6 @@ def train(model, quantizer, device, train_loader, optimizer):
loss = F.nll_loss(output, target) loss = F.nll_loss(output, target)
loss.backward() loss.backward()
optimizer.step() optimizer.step()
quantizer.step()
if batch_idx % 100 == 0: if batch_idx % 100 == 0:
print('{:2.0f}% Loss {}'.format(100 * batch_idx / len(train_loader), loss.item())) print('{:2.0f}% Loss {}'.format(100 * batch_idx / len(train_loader), loss.item()))
......
...@@ -27,7 +27,7 @@ interface ExperimentParams { ...@@ -27,7 +27,7 @@ interface ExperimentParams {
versionCheck?: boolean; versionCheck?: boolean;
logCollection?: string; logCollection?: string;
tuner?: { tuner?: {
className: string; className?: string;
builtinTunerName?: string; builtinTunerName?: string;
codeDir?: string; codeDir?: string;
classArgs?: any; classArgs?: any;
...@@ -37,7 +37,7 @@ interface ExperimentParams { ...@@ -37,7 +37,7 @@ interface ExperimentParams {
gpuIndices?: string; gpuIndices?: string;
}; };
assessor?: { assessor?: {
className: string; className?: string;
builtinAssessorName?: string; builtinAssessorName?: string;
codeDir?: string; codeDir?: string;
classArgs?: any; classArgs?: any;
...@@ -45,7 +45,7 @@ interface ExperimentParams { ...@@ -45,7 +45,7 @@ interface ExperimentParams {
checkpointDir: string; checkpointDir: string;
}; };
advisor?: { advisor?: {
className: string; className?: string;
builtinAdvisorName?: string; builtinAdvisorName?: string;
codeDir?: string; codeDir?: string;
classArgs?: any; classArgs?: any;
......
...@@ -17,7 +17,7 @@ import * as util from 'util'; ...@@ -17,7 +17,7 @@ import * as util from 'util';
import { Database, DataStore } from './datastore'; import { Database, DataStore } from './datastore';
import { ExperimentStartupInfo, getExperimentStartupInfo, setExperimentStartupInfo } from './experimentStartupInfo'; import { ExperimentStartupInfo, getExperimentStartupInfo, setExperimentStartupInfo } from './experimentStartupInfo';
import { Manager } from './manager'; import { ExperimentParams, Manager } from './manager';
import { HyperParameters, TrainingService, TrialJobStatus } from './trainingService'; import { HyperParameters, TrainingService, TrialJobStatus } from './trainingService';
function getExperimentRootDir(): string { function getExperimentRootDir(): string {
...@@ -130,15 +130,6 @@ function parseArg(names: string[]): string { ...@@ -130,15 +130,6 @@ function parseArg(names: string[]): string {
return ''; return '';
} }
function encodeCmdLineArgs(args: any): any {
if(process.platform === 'win32'){
return JSON.stringify(args);
}
else{
return JSON.stringify(JSON.stringify(args));
}
}
function getCmdPy(): string { function getCmdPy(): string {
let cmd = 'python3'; let cmd = 'python3';
if(process.platform === 'win32'){ if(process.platform === 'win32'){
...@@ -150,83 +141,14 @@ function getCmdPy(): string { ...@@ -150,83 +141,14 @@ function getCmdPy(): string {
/** /**
* Generate command line to start automl algorithm(s), * Generate command line to start automl algorithm(s),
* either start advisor or start a process which runs tuner and assessor * either start advisor or start a process which runs tuner and assessor
* @param tuner : For builtin tuner:
* {
* className: 'EvolutionTuner'
* classArgs: {
* optimize_mode: 'maximize',
* population_size: 3
* }
* }
* customized:
* {
* codeDir: '/tmp/mytuner'
* classFile: 'best_tuner.py'
* className: 'BestTuner'
* classArgs: {
* optimize_mode: 'maximize',
* population_size: 3
* }
* }
* *
* @param assessor: similiar as tuner * @param expParams: experiment startup parameters
* @param advisor: similar as tuner
* *
*/ */
function getMsgDispatcherCommand(tuner: any, assessor: any, advisor: any, multiPhase: boolean = false, multiThread: boolean = false): string { function getMsgDispatcherCommand(expParams: ExperimentParams): string {
if ((tuner || assessor) && advisor) { const clonedParams = Object.assign({}, expParams);
throw new Error('Error: specify both tuner/assessor and advisor is not allowed'); delete clonedParams.searchSpace;
} return `${getCmdPy()} -m nni --exp_params ${Buffer.from(JSON.stringify(clonedParams)).toString('base64')}`;
if (!tuner && !advisor) {
throw new Error('Error: specify neither tuner nor advisor is not allowed');
}
let command: string = `${getCmdPy()} -m nni`;
if (multiPhase) {
command += ' --multi_phase';
}
if (multiThread) {
command += ' --multi_thread';
}
if (advisor) {
command += ` --advisor_class_name ${advisor.className}`;
if (advisor.classArgs !== undefined) {
command += ` --advisor_args ${encodeCmdLineArgs(advisor.classArgs)}`;
}
if (advisor.codeDir !== undefined && advisor.codeDir.length > 1) {
command += ` --advisor_directory ${advisor.codeDir}`;
}
if (advisor.classFileName !== undefined && advisor.classFileName.length > 1) {
command += ` --advisor_class_filename ${advisor.classFileName}`;
}
} else {
command += ` --tuner_class_name ${tuner.className}`;
if (tuner.classArgs !== undefined) {
command += ` --tuner_args ${encodeCmdLineArgs(tuner.classArgs)}`;
}
if (tuner.codeDir !== undefined && tuner.codeDir.length > 1) {
command += ` --tuner_directory ${tuner.codeDir}`;
}
if (tuner.classFileName !== undefined && tuner.classFileName.length > 1) {
command += ` --tuner_class_filename ${tuner.classFileName}`;
}
if (assessor !== undefined && assessor.className !== undefined) {
command += ` --assessor_class_name ${assessor.className}`;
if (assessor.classArgs !== undefined) {
command += ` --assessor_args ${encodeCmdLineArgs(assessor.classArgs)}`;
}
if (assessor.codeDir !== undefined && assessor.codeDir.length > 1) {
command += ` --assessor_directory ${assessor.codeDir}`;
}
if (assessor.classFileName !== undefined && assessor.classFileName.length > 1) {
command += ` --assessor_class_filename ${assessor.classFileName}`;
}
}
}
return command;
} }
/** /**
......
{
"kind": "CustomResourceDefinition",
"spec": {
"scope": "Namespaced",
"version": "v1",
"group": "kubeflow.org",
"names": {
"kind": "TFJob",
"plural": "tfjobs",
"singular": "tfjob"
}
},
"apiVersion": "apiextensions.k8s.io/v1beta1",
"metadata": {
"name": "tfjobs.kubeflow.org"
}
}
...@@ -170,8 +170,7 @@ class NNIManager implements Manager { ...@@ -170,8 +170,7 @@ class NNIManager implements Manager {
this.trainingService.setClusterMetadata('log_collection', expParams.logCollection.toString()); this.trainingService.setClusterMetadata('log_collection', expParams.logCollection.toString());
} }
const dispatcherCommand: string = getMsgDispatcherCommand(expParams.tuner, expParams.assessor, expParams.advisor, const dispatcherCommand: string = getMsgDispatcherCommand(expParams);
expParams.multiPhase, expParams.multiThread);
this.log.debug(`dispatcher command: ${dispatcherCommand}`); this.log.debug(`dispatcher command: ${dispatcherCommand}`);
const checkpointDir: string = await this.createCheckpointDir(); const checkpointDir: string = await this.createCheckpointDir();
this.setupTuner( this.setupTuner(
...@@ -211,8 +210,7 @@ class NNIManager implements Manager { ...@@ -211,8 +210,7 @@ class NNIManager implements Manager {
this.trainingService.setClusterMetadata('version_check', expParams.versionCheck.toString()); this.trainingService.setClusterMetadata('version_check', expParams.versionCheck.toString());
} }
const dispatcherCommand: string = getMsgDispatcherCommand(expParams.tuner, expParams.assessor, expParams.advisor, const dispatcherCommand: string = getMsgDispatcherCommand(expParams);
expParams.multiPhase, expParams.multiThread);
this.log.debug(`dispatcher command: ${dispatcherCommand}`); this.log.debug(`dispatcher command: ${dispatcherCommand}`);
const checkpointDir: string = await this.createCheckpointDir(); const checkpointDir: string = await this.createCheckpointDir();
this.setupTuner( this.setupTuner(
...@@ -361,6 +359,7 @@ class NNIManager implements Manager { ...@@ -361,6 +359,7 @@ class NNIManager implements Manager {
} }
const nniEnv = { const nniEnv = {
SDK_PROCESS: 'dispatcher',
NNI_MODE: mode, NNI_MODE: mode,
NNI_CHECKPOINT_DIRECTORY: dataDirectory, NNI_CHECKPOINT_DIRECTORY: dataDirectory,
NNI_LOG_DIRECTORY: getLogDir(), NNI_LOG_DIRECTORY: getLogDir(),
......
...@@ -21,18 +21,26 @@ function startProcess(): void { ...@@ -21,18 +21,26 @@ function startProcess(): void {
const dispatcherCmd: string = getMsgDispatcherCommand( const dispatcherCmd: string = getMsgDispatcherCommand(
// Mock tuner config // Mock tuner config
{ {
className: 'DummyTuner', experimentName: 'exp1',
codeDir: './', maxExecDuration: 3600,
classFileName: 'dummy_tuner.py' searchSpace: '',
}, trainingServicePlatform: 'local',
// Mock assessor config authorName: '',
{ trialConcurrency: 1,
className: 'DummyAssessor', maxTrialNum: 5,
codeDir: './', tuner: {
classFileName: 'dummy_assessor.py' className: 'DummyTuner',
}, codeDir: './',
// advisor classFileName: 'dummy_tuner.py',
undefined checkpointDir: './'
},
assessor: {
className: 'DummyAssessor',
codeDir: './',
classFileName: 'dummy_assessor.py',
checkpointDir: './'
}
}
); );
const proc: ChildProcess = getTunerProc(dispatcherCmd, stdio, 'core/test', process.env); const proc: ChildProcess = getTunerProc(dispatcherCmd, stdio, 'core/test', process.env);
proc.on('error', (error: Error): void => { proc.on('error', (error: Error): void => {
......
...@@ -42,9 +42,9 @@ describe('Unit test for nnimanager', function () { ...@@ -42,9 +42,9 @@ describe('Unit test for nnimanager', function () {
maxExecDuration: 5, maxExecDuration: 5,
maxTrialNum: 3, maxTrialNum: 3,
trainingServicePlatform: 'local', trainingServicePlatform: 'local',
searchSpace: '{"x":1}', searchSpace: '{"lr": {"_type": "choice", "_value": [0.01,0.001]}}',
tuner: { tuner: {
className: 'TPE', builtinTunerName: 'TPE',
classArgs: { classArgs: {
optimize_mode: 'maximize' optimize_mode: 'maximize'
}, },
...@@ -52,7 +52,7 @@ describe('Unit test for nnimanager', function () { ...@@ -52,7 +52,7 @@ describe('Unit test for nnimanager', function () {
gpuNum: 0 gpuNum: 0
}, },
assessor: { assessor: {
className: 'Medianstop', builtinAssessorName: 'Medianstop',
checkpointDir: '', checkpointDir: '',
gpuNum: 1 gpuNum: 1
} }
...@@ -65,9 +65,9 @@ describe('Unit test for nnimanager', function () { ...@@ -65,9 +65,9 @@ describe('Unit test for nnimanager', function () {
maxExecDuration: 6, maxExecDuration: 6,
maxTrialNum: 2, maxTrialNum: 2,
trainingServicePlatform: 'local', trainingServicePlatform: 'local',
searchSpace: '{"y":2}', searchSpace: '{"lr": {"_type": "choice", "_value": [0.01,0.001]}}',
tuner: { tuner: {
className: 'TPE', builtinTunerName: 'TPE',
classArgs: { classArgs: {
optimize_mode: 'maximize' optimize_mode: 'maximize'
}, },
...@@ -75,7 +75,7 @@ describe('Unit test for nnimanager', function () { ...@@ -75,7 +75,7 @@ describe('Unit test for nnimanager', function () {
gpuNum: 0 gpuNum: 0
}, },
assessor: { assessor: {
className: 'Medianstop', builtinAssessorName: 'Medianstop',
checkpointDir: '', checkpointDir: '',
gpuNum: 1 gpuNum: 1
} }
...@@ -198,7 +198,7 @@ describe('Unit test for nnimanager', function () { ...@@ -198,7 +198,7 @@ describe('Unit test for nnimanager', function () {
it('test updateExperimentProfile SEARCH_SPACE', () => { it('test updateExperimentProfile SEARCH_SPACE', () => {
return nniManager.updateExperimentProfile(experimentProfile, 'SEARCH_SPACE').then(() => { return nniManager.updateExperimentProfile(experimentProfile, 'SEARCH_SPACE').then(() => {
nniManager.getExperimentProfile().then((updateProfile) => { nniManager.getExperimentProfile().then((updateProfile) => {
expect(updateProfile.params.searchSpace).to.be.equal('{"y":2}'); expect(updateProfile.params.searchSpace).to.be.equal('{"lr": {"_type": "choice", "_value": [0.01,0.001]}}');
}); });
}).catch((error) => { }).catch((error) => {
assert.fail(error); assert.fail(error);
......
...@@ -20,7 +20,8 @@ import { NNIRestServer } from './rest_server/nniRestServer'; ...@@ -20,7 +20,8 @@ import { NNIRestServer } from './rest_server/nniRestServer';
import { FrameworkControllerTrainingService } from './training_service/kubernetes/frameworkcontroller/frameworkcontrollerTrainingService'; import { FrameworkControllerTrainingService } from './training_service/kubernetes/frameworkcontroller/frameworkcontrollerTrainingService';
import { KubeflowTrainingService } from './training_service/kubernetes/kubeflow/kubeflowTrainingService'; import { KubeflowTrainingService } from './training_service/kubernetes/kubeflow/kubeflowTrainingService';
import { LocalTrainingService } from './training_service/local/localTrainingService'; import { LocalTrainingService } from './training_service/local/localTrainingService';
import { PAITrainingService } from './training_service/pai/paiTrainingService'; import { PAIK8STrainingService } from './training_service/pai/paiK8S/paiK8STrainingService';
import { PAIYarnTrainingService } from './training_service/pai/paiYarn/paiYarnTrainingService';
import { import {
RemoteMachineTrainingService RemoteMachineTrainingService
} from './training_service/remote_machine/remoteMachineTrainingService'; } from './training_service/remote_machine/remoteMachineTrainingService';
...@@ -44,7 +45,11 @@ async function initContainer(platformMode: string, logFileName?: string): Promis ...@@ -44,7 +45,11 @@ async function initContainer(platformMode: string, logFileName?: string): Promis
.scope(Scope.Singleton); .scope(Scope.Singleton);
} else if (platformMode === 'pai') { } else if (platformMode === 'pai') {
Container.bind(TrainingService) Container.bind(TrainingService)
.to(PAITrainingService) .to(PAIK8STrainingService)
.scope(Scope.Singleton);
} else if (platformMode === 'paiYarn') {
Container.bind(TrainingService)
.to(PAIYarnTrainingService)
.scope(Scope.Singleton); .scope(Scope.Singleton);
} else if (platformMode === 'kubeflow') { } else if (platformMode === 'kubeflow') {
Container.bind(TrainingService) Container.bind(TrainingService)
...@@ -76,7 +81,7 @@ async function initContainer(platformMode: string, logFileName?: string): Promis ...@@ -76,7 +81,7 @@ async function initContainer(platformMode: string, logFileName?: string): Promis
function usage(): void { function usage(): void {
console.info('usage: node main.js --port <port> --mode \ console.info('usage: node main.js --port <port> --mode \
<local/remote/pai/kubeflow/frameworkcontroller> --start_mode <new/resume> --experiment_id <id>'); <local/remote/pai/kubeflow/frameworkcontroller/paiYarn> --start_mode <new/resume> --experiment_id <id>');
} }
const strPort: string = parseArg(['--port', '-p']); const strPort: string = parseArg(['--port', '-p']);
...@@ -88,7 +93,7 @@ if (!strPort || strPort.length === 0) { ...@@ -88,7 +93,7 @@ if (!strPort || strPort.length === 0) {
const port: number = parseInt(strPort, 10); const port: number = parseInt(strPort, 10);
const mode: string = parseArg(['--mode', '-m']); const mode: string = parseArg(['--mode', '-m']);
if (!['local', 'remote', 'pai', 'kubeflow', 'frameworkcontroller'].includes(mode)) { if (!['local', 'remote', 'pai', 'kubeflow', 'frameworkcontroller', 'paiYarn'].includes(mode)) {
console.log(`FATAL: unknown mode: ${mode}`); console.log(`FATAL: unknown mode: ${mode}`);
usage(); usage();
process.exit(1); process.exit(1);
......
...@@ -36,6 +36,9 @@ export namespace ValidationSchemas { ...@@ -36,6 +36,9 @@ export namespace ValidationSchemas {
virtualCluster: joi.string(), virtualCluster: joi.string(),
shmMB: joi.number(), shmMB: joi.number(),
authFile: joi.string(), authFile: joi.string(),
nniManagerNFSMountPath: joi.string().min(1),
containerNFSMountPath: joi.string().min(1),
paiStoragePlugin: joi.string().min(1),
nasMode: joi.string().valid('classic_mode', 'enas_mode', 'oneshot_mode', 'darts_mode'), nasMode: joi.string().valid('classic_mode', 'enas_mode', 'oneshot_mode', 'darts_mode'),
portList: joi.array().items(joi.object({ portList: joi.array().items(joi.object({
label: joi.string().required(), label: joi.string().required(),
...@@ -89,12 +92,18 @@ export namespace ValidationSchemas { ...@@ -89,12 +92,18 @@ export namespace ValidationSchemas {
}) })
}) })
}), }),
pai_config: joi.object({ // eslint-disable-line @typescript-eslint/camelcase pai_yarn_config: joi.object({ // eslint-disable-line @typescript-eslint/camelcase
userName: joi.string().min(1).required(), userName: joi.string().min(1).required(),
passWord: joi.string().min(1), passWord: joi.string().min(1),
token: joi.string().min(1), token: joi.string().min(1),
host: joi.string().min(1).required() host: joi.string().min(1).required()
}), }),
pai_config: joi.object({ // eslint-disable-line @typescript-eslint/camelcase
userName: joi.string().min(1).required(),
passWord: joi.string().min(1),
token: joi.string().min(1),
host: joi.string().min(1).required(),
}),
kubeflow_config: joi.object({ // eslint-disable-line @typescript-eslint/camelcase kubeflow_config: joi.object({ // eslint-disable-line @typescript-eslint/camelcase
operator: joi.string().min(1).required(), operator: joi.string().min(1).required(),
storage: joi.string().min(1), storage: joi.string().min(1),
......
...@@ -13,6 +13,7 @@ export enum TrialConfigMetadataKey { ...@@ -13,6 +13,7 @@ export enum TrialConfigMetadataKey {
EXPERIMENT_ID = 'experimentId', EXPERIMENT_ID = 'experimentId',
MULTI_PHASE = 'multiPhase', MULTI_PHASE = 'multiPhase',
RANDOM_SCHEDULER = 'random_scheduler', RANDOM_SCHEDULER = 'random_scheduler',
PAI_YARN_CLUSTER_CONFIG = 'pai_yarn_config',
PAI_CLUSTER_CONFIG = 'pai_config', PAI_CLUSTER_CONFIG = 'pai_config',
KUBEFLOW_CLUSTER_CONFIG = 'kubeflow_config', KUBEFLOW_CLUSTER_CONFIG = 'kubeflow_config',
NNI_MANAGER_IP = 'nni_manager_ip', NNI_MANAGER_IP = 'nni_manager_ip',
......
...@@ -65,6 +65,25 @@ class TFOperatorClientV1Beta2 extends KubernetesCRDClient { ...@@ -65,6 +65,25 @@ class TFOperatorClientV1Beta2 extends KubernetesCRDClient {
} }
} }
class TFOperatorClientV1 extends KubernetesCRDClient {
/**
* constructor, to initialize tfjob CRD definition
*/
public constructor() {
super();
this.crdSchema = JSON.parse(fs.readFileSync('./config/kubeflow/tfjob-crd-v1.json', 'utf8'));
this.client.addCustomResourceDefinition(this.crdSchema);
}
protected get operator(): any {
return this.client.apis['kubeflow.org'].v1.namespaces('default').tfjobs;
}
public get containerName(): string {
return 'tensorflow';
}
}
class PyTorchOperatorClientV1Alpha2 extends KubernetesCRDClient { class PyTorchOperatorClientV1Alpha2 extends KubernetesCRDClient {
/** /**
* constructor, to initialize tfjob CRD definition * constructor, to initialize tfjob CRD definition
...@@ -142,6 +161,9 @@ class KubeflowOperatorClientFactory { ...@@ -142,6 +161,9 @@ class KubeflowOperatorClientFactory {
case 'v1beta2': { case 'v1beta2': {
return new TFOperatorClientV1Beta2(); return new TFOperatorClientV1Beta2();
} }
case 'v1': {
return new TFOperatorClientV1();
}
default: default:
throw new Error(`Invalid tf-operator apiVersion ${operatorApiVersion}`); throw new Error(`Invalid tf-operator apiVersion ${operatorApiVersion}`);
} }
......
...@@ -4,91 +4,8 @@ ...@@ -4,91 +4,8 @@
'use strict'; 'use strict';
import {TrialConfig} from '../common/trialConfig'; import {TrialConfig} from '../common/trialConfig';
import { TrialJobApplicationForm, TrialJobDetail, TrialJobStatus } from '../../common/trainingService';
/**
* Task role for PAI
*/
export class PAITaskRole {
// Name for the task role
public readonly name: string;
// Number of tasks for the task role, no less than 1
public readonly taskNumber: number;
// CPU number for one task in the task role, no less than 1
public readonly cpuNumber: number;
// Memory for one task in the task role, no less than 100
public readonly memoryMB: number;
// GPU number for one task in the task role, no less than 0
public readonly gpuNumber: number;
// Executable command for tasks in the task role, can not be empty
public readonly command: string;
//Shared memory for one task in the task role
public readonly shmMB?: number;
//portList to specify the port used in container
public portList?: PortListMetaData[];
/**
* Constructor
* @param name Name for the task role
* @param taskNumber Number of tasks for the task role, no less than 1
* @param cpuNumber CPU number for one task in the task role, no less than 1
* @param memoryMB Memory for one task in the task role, no less than 100
* @param gpuNumber GPU number for one task in the task role, no less than 0
* @param command Executable command for tasks in the task role, can not be empty
*/
constructor(name: string, taskNumber: number, cpuNumber: number, memoryMB: number, gpuNumber: number,
command: string, shmMB?: number, portList?: PortListMetaData[]) {
this.name = name;
this.taskNumber = taskNumber;
this.cpuNumber = cpuNumber;
this.memoryMB = memoryMB;
this.gpuNumber = gpuNumber;
this.command = command;
this.shmMB = shmMB;
this.portList = portList;
}
}
/**
* Trial job configuration submitted to PAI
*/
export class PAIJobConfig {
// Name for the job, need to be unique
public readonly jobName: string;
// URL pointing to the Docker image for all tasks in the job
public readonly image: string;
// Code directory on HDFS
public readonly codeDir: string;
//authentication file used for private Docker registry
public readonly authFile?: string;
// List of taskRole, one task role at least
public taskRoles: PAITaskRole[];
//The virtual cluster job runs on.
public readonly virtualCluster: string;
/**
* Constructor
* @param jobName Name for the job, need to be unique
* @param image URL pointing to the Docker image for all tasks in the job
* @param dataDir Data directory existing on HDFS
* @param outputDir Output directory on HDFS
* @param taskRoles List of taskRole, one task role at least
*/
constructor(jobName: string, image: string, codeDir: string,
taskRoles: PAITaskRole[], virtualCluster: string, authFile?: string) {
this.jobName = jobName;
this.image = image;
this.codeDir = codeDir;
this.taskRoles = taskRoles;
this.virtualCluster = virtualCluster;
this.authFile = authFile;
}
}
/**
* PAI cluster configuration
*/
export class PAIClusterConfig { export class PAIClusterConfig {
public readonly userName: string; public readonly userName: string;
public readonly passWord?: string; public readonly passWord?: string;
...@@ -111,41 +28,31 @@ export class PAIClusterConfig { ...@@ -111,41 +28,31 @@ export class PAIClusterConfig {
} }
/** /**
* portList data structure used in PAI taskRole * PAI trial job detail
*/ */
export class PortListMetaData { export class PAITrialJobDetail implements TrialJobDetail {
public readonly label: string = ''; public id: string;
public readonly beginAt: number = 0; public status: TrialJobStatus;
public readonly portNumber: number = 0; public paiJobName: string;
} public submitTime: number;
public startTime?: number;
public endTime?: number;
/** public tags?: string[];
* PAI trial configuration public url?: string;
*/ public workingDirectory: string;
export class NNIPAITrialConfig extends TrialConfig { public form: TrialJobApplicationForm;
public readonly cpuNum: number; public logPath: string;
public readonly memoryMB: number; public isEarlyStopped?: boolean;
public readonly image: string;
constructor(id: string, status: TrialJobStatus, paiJobName: string,
//The virtual cluster job runs on. If omitted, the job will run on default virtual cluster submitTime: number, workingDirectory: string, form: TrialJobApplicationForm, logPath: string) {
public virtualCluster?: string; this.id = id;
//Shared memory for one task in the task role this.status = status;
public shmMB?: number; this.paiJobName = paiJobName;
//authentication file used for private Docker registry this.submitTime = submitTime;
public authFile?: string; this.workingDirectory = workingDirectory;
//portList to specify the port used in container this.form = form;
public portList?: PortListMetaData[]; this.tags = [];
this.logPath = logPath;
constructor(command: string, codeDir: string, gpuNum: number, cpuNum: number, memoryMB: number,
image: string, virtualCluster?: string, shmMB?: number, authFile?: string, portList?: PortListMetaData[]) {
super(command, codeDir, gpuNum);
this.cpuNum = cpuNum;
this.memoryMB = memoryMB;
this.image = image;
this.virtualCluster = virtualCluster;
this.shmMB = shmMB;
this.authFile = authFile;
this.portList = portList;
} }
} }
...@@ -8,8 +8,7 @@ import { Deferred } from 'ts-deferred'; ...@@ -8,8 +8,7 @@ import { Deferred } from 'ts-deferred';
import { NNIError, NNIErrorNames } from '../../common/errors'; import { NNIError, NNIErrorNames } from '../../common/errors';
import { getLogger, Logger } from '../../common/log'; import { getLogger, Logger } from '../../common/log';
import { TrialJobStatus } from '../../common/trainingService'; import { TrialJobStatus } from '../../common/trainingService';
import { PAIClusterConfig } from './paiConfig'; import { PAIClusterConfig, PAITrialJobDetail } from './paiConfig';
import { PAITrialJobDetail } from './paiData';
/** /**
* Collector PAI jobs info from PAI cluster, and update pai job status locally * Collector PAI jobs info from PAI cluster, and update pai job status locally
...@@ -26,8 +25,8 @@ export class PAIJobInfoCollector { ...@@ -26,8 +25,8 @@ export class PAIJobInfoCollector {
this.finalStatuses = ['SUCCEEDED', 'FAILED', 'USER_CANCELED', 'SYS_CANCELED', 'EARLY_STOPPED']; this.finalStatuses = ['SUCCEEDED', 'FAILED', 'USER_CANCELED', 'SYS_CANCELED', 'EARLY_STOPPED'];
} }
public async retrieveTrialStatus(paiToken? : string, paiClusterConfig?: PAIClusterConfig): Promise<void> { public async retrieveTrialStatus(token? : string, paiBaseClusterConfig?: PAIClusterConfig): Promise<void> {
if (paiClusterConfig === undefined || paiToken === undefined) { if (paiBaseClusterConfig === undefined || token === undefined) {
return Promise.resolve(); return Promise.resolve();
} }
...@@ -36,7 +35,7 @@ export class PAIJobInfoCollector { ...@@ -36,7 +35,7 @@ export class PAIJobInfoCollector {
if (paiTrialJob === undefined) { if (paiTrialJob === undefined) {
throw new NNIError(NNIErrorNames.NOT_FOUND, `trial job id ${trialJobId} not found`); throw new NNIError(NNIErrorNames.NOT_FOUND, `trial job id ${trialJobId} not found`);
} }
updatePaiTrialJobs.push(this.getSinglePAITrialJobInfo(paiTrialJob, paiToken, paiClusterConfig)); updatePaiTrialJobs.push(this.getSinglePAITrialJobInfo(paiTrialJob, token, paiBaseClusterConfig));
} }
await Promise.all(updatePaiTrialJobs); await Promise.all(updatePaiTrialJobs);
...@@ -56,7 +55,7 @@ export class PAIJobInfoCollector { ...@@ -56,7 +55,7 @@ export class PAIJobInfoCollector {
uri: `http://${paiClusterConfig.host}/rest-server/api/v1/user/${paiClusterConfig.userName}/jobs/${paiTrialJob.paiJobName}`, uri: `http://${paiClusterConfig.host}/rest-server/api/v1/user/${paiClusterConfig.userName}/jobs/${paiTrialJob.paiJobName}`,
method: 'GET', method: 'GET',
json: true, json: true,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
Authorization: `Bearer ${paiToken}` Authorization: `Bearer ${paiToken}`
} }
...@@ -114,8 +113,12 @@ export class PAIJobInfoCollector { ...@@ -114,8 +113,12 @@ export class PAIJobInfoCollector {
paiTrialJob.endTime = response.body.jobStatus.completedTime; paiTrialJob.endTime = response.body.jobStatus.completedTime;
} }
// Set pai trial job's url to WebHDFS output path // Set pai trial job's url to WebHDFS output path
if (paiTrialJob.hdfsLogPath !== undefined) { if (paiTrialJob.logPath !== undefined) {
paiTrialJob.url += `,${paiTrialJob.hdfsLogPath}`; if (paiTrialJob.url) {
paiTrialJob.url += `,${paiTrialJob.logPath}`;
} else {
paiTrialJob.url = `${paiTrialJob.logPath}`;
}
} }
} }
} }
......
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