-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program.cs
203 lines (182 loc) · 10.2 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Linq;
using Microsoft.Azure.Management.BatchAI.Fluent;
using Microsoft.Azure.Management.BatchAI.Fluent.Models;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.Storage.Fluent;
using Microsoft.Azure.Management.Storage.Fluent.Models;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using ExecutionState = Microsoft.Azure.Management.BatchAI.Fluent.Models.ExecutionState;
namespace ManageBatchAI
{
public class Program
{
/**
* Azure Batch AI sample.
* - Create Storage account and Azure file share
* - Upload sample data to Azure file share
* - Create a workspace and experiment
* - Create Batch AI cluster that uses Azure file share to host the training data and scripts for the learning job
* - Create Microsoft Cognitive Toolkit job to run on the cluster
* - Wait for job to complete
* - Get output files
*
* Please note: in order to run this sample, please download and unzip sample package from <a href="https://batchaisamples.blob.core.windows.net/samples/BatchAIQuickStart.zip?st=2017-09-29T18%3A29%3A00Z&se=2099-12-31T08%3A00%3A00Z&sp=rl&sv=2016-05-31&sr=b&sig=hrAZfbZC%2BQ%2FKccFQZ7OC4b%2FXSzCF5Myi4Cj%2BW3sVZDo%3D">here</a>
* Export path to the content to $SAMPLE_DATA_PATH.
*/
public static void RunSample(IAzure azure)
{
string saName = SdkContext.RandomResourceName("sa", 10);
string rgName = SdkContext.RandomResourceName("rg", 10);
string workspaceName = SdkContext.RandomResourceName("ws", 10);
string experimentName = SdkContext.RandomResourceName("exp", 10);
string sampleDataPath = Environment.GetEnvironmentVariable("SAMPLE_DATA_PATH");
Region region = Region.USWest2;
string shareName = SdkContext.RandomResourceName("fs", 20);
string clusterName = SdkContext.RandomResourceName("cluster", 15);
string userName = Utilities.CreateUsername();
string sharePath = "mnistcntksample";
try
{
//=============================================================
// Create a new storage account and an Azure file share resource
Utilities.Log("Creating a storage account...");
IStorageAccount storageAccount = azure.StorageAccounts.Define(saName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.Create();
Utilities.Log("Created storage account.");
Utilities.PrintStorageAccount(storageAccount);
StorageAccountKey storageAccountKey = storageAccount.GetKeys().First();
Utilities.Log("Creating Azure File share...");
var cloudFileShare = CloudStorageAccount.Parse($"DefaultEndpointsProtocol=https;AccountName={saName};AccountKey={storageAccountKey.Value};EndpointSuffix=core.windows.net")
.CreateCloudFileClient()
.GetShareReference(shareName);
cloudFileShare.CreateAsync().GetAwaiter().GetResult();
Utilities.Log("Created Azure File share.");
//=============================================================
// Upload sample data to Azure file share
//Get a reference to the root directory for the share.
CloudFileDirectory rootDir = cloudFileShare.GetRootDirectoryReference();
//Get a reference to the sampledir directory
Utilities.Log("Creating directory and uploading data files...");
CloudFileDirectory sampleDir = rootDir.GetDirectoryReference(sharePath);
sampleDir.CreateAsync().GetAwaiter().GetResult();
rootDir.GetFileReference("Train-28x28_cntk_text.txt").UploadFromFileAsync(sampleDataPath + "/Train-28x28_cntk_text.txt").GetAwaiter().GetResult();
rootDir.GetFileReference("Test-28x28_cntk_text.txt").UploadFromFileAsync(sampleDataPath + "/Test-28x28_cntk_text.txt").GetAwaiter().GetResult();
rootDir.GetFileReference("ConvNet_MNIST.py").UploadFromFileAsync(sampleDataPath + "/ConvNet_MNIST.py").GetAwaiter().GetResult();
Utilities.Log("Data files uploaded.");
//=============================================================
// Create a workspace and experiment
IBatchAIWorkspace workspace = azure.BatchAIWorkspaces.Define(workspaceName)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.Create();
IBatchAIExperiment experiment = workspace.CreateExperiment(experimentName);
//=============================================================
// Create Batch AI cluster that uses Azure file share to host the training data and scripts for the learning job
Utilities.Log("Creating Batch AI cluster...");
IBatchAICluster cluster = workspace.Clusters.Define(clusterName)
.WithVMSize(VirtualMachineSizeTypes.StandardNC6.Value)
.WithUserName(userName)
.WithPassword("MyPassword")
.WithAutoScale(0, 2)
.DefineAzureFileShare()
.WithStorageAccountName(saName)
.WithAzureFileUrl(cloudFileShare.Uri.ToString())
.WithRelativeMountPath("azurefileshare")
.WithAccountKey(storageAccountKey.Value)
.Attach()
.Create();
Utilities.Log("Created Batch AI cluster.");
Utilities.Print(cluster);
// =============================================================
// Create Microsoft Cognitive Toolkit job to run on the cluster
Utilities.Log("Creating Batch AI job...");
IBatchAIJob job = experiment.Jobs.Define("myJob")
.WithExistingCluster(cluster)
.WithNodeCount(1)
.WithStdOutErrPathPrefix("$AZ_BATCHAI_MOUNT_ROOT/azurefileshare")
.DefineCognitiveToolkit()
.WithPythonScriptFile("$AZ_BATCHAI_MOUNT_ROOT/azurefileshare/ConvNet_MNIST.py")
.WithCommandLineArgs("$AZ_BATCHAI_MOUNT_ROOT/azurefileshare $AZ_BATCHAI_OUTPUT_MODEL")
.Attach()
.WithOutputDirectory("MODEL", "$AZ_BATCHAI_MOUNT_ROOT/azurefileshare/model")
.WithContainerImage("microsoft/cntk:2.1-gpu-python3.5-cuda8.0-cudnn6.0")
.Create();
Utilities.Log("Created Batch AI job.");
Utilities.Print(job);
// =============================================================
// Wait for job results
// Wait for job to start running
Utilities.Log("Waiting for Batch AI job to start running...");
while (ExecutionState.Queued.Equals(job.ExecutionState))
{
SdkContext.DelayProvider.Delay(5000);
job.Refresh();
}
// Wait for job to complete and job output to become available
Utilities.Log("Waiting for Batch AI job to complete...");
while (!(ExecutionState.Succeeded.Equals(job.ExecutionState) || ExecutionState.Failed.Equals(job.ExecutionState)))
{
SdkContext.DelayProvider.Delay(5000);
job.Refresh();
}
// =============================================================
// Get output files
// Print stdout and stderr
foreach (var outputFile in job.ListFiles("stdouterr"))
{
Utilities.Log(Utilities.CheckAddress(outputFile.DownloadUrl));
}
// List model output files
foreach (var outputFile in job.ListFiles("MODEL"))
{
Utilities.Log(outputFile.DownloadUrl);
}
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.BeginDeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (Exception)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
AzureCredentials credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception ex)
{
Utilities.Log(ex);
}
}
}
}