"tools/post_quant.py" did not exist on "dcc7bf4f1a243d90d6c4f7c51551cea3f256325f"
utils.ts 15.7 KB
Newer Older
Deshui Yu's avatar
Deshui Yu committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * Copyright (c) Microsoft Corporation
 * All rights reserved.
 *
 * MIT License
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
 * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

'use strict';

22
import * as assert from 'assert';
Deshui Yu's avatar
Deshui Yu committed
23
import { randomBytes } from 'crypto';
24
import * as cpp from 'child-process-promise';
25
26
import * as cp from 'child_process';
import { ChildProcess, spawn, StdioOptions } from 'child_process';
Deshui Yu's avatar
Deshui Yu committed
27
28
29
30
31
32
33
34
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { Deferred } from 'ts-deferred';
import { Container } from 'typescript-ioc';
import * as util from 'util';

import { Database, DataStore } from './datastore';
35
import { ExperimentStartupInfo, getExperimentId, getExperimentStartupInfo, setExperimentStartupInfo } from './experimentStartupInfo';
Deshui Yu's avatar
Deshui Yu committed
36
import { Manager } from './manager';
37
import { TrialConfig } from '../training_service/common/trialConfig';
QuanluZhang's avatar
QuanluZhang committed
38
import { HyperParameters, TrainingService, TrialJobStatus } from './trainingService';
39
import { getLogger } from './log';
Deshui Yu's avatar
Deshui Yu committed
40

41
function getExperimentRootDir(): string {
42
43
    return getExperimentStartupInfo()
            .getLogDir();
Deshui Yu's avatar
Deshui Yu committed
44
45
}

46
function getLogDir(): string {
Deshui Yu's avatar
Deshui Yu committed
47
48
49
    return path.join(getExperimentRootDir(), 'log');
}

50
function getLogLevel(): string {
51
52
53
54
    return getExperimentStartupInfo()
    .getLogLevel();
}

Deshui Yu's avatar
Deshui Yu committed
55
56
57
58
function getDefaultDatabaseDir(): string {
    return path.join(getExperimentRootDir(), 'db');
}

QuanluZhang's avatar
QuanluZhang committed
59
60
61
62
function getCheckpointDir(): string {
    return path.join(getExperimentRootDir(), 'checkpoint');
}

Deshui Yu's avatar
Deshui Yu committed
63
64
65
66
67
68
69
70
function mkDirP(dirPath: string): Promise<void> {
    const deferred: Deferred<void> = new Deferred<void>();
    fs.exists(dirPath, (exists: boolean) => {
        if (exists) {
            deferred.resolve();
        } else {
            const parent: string = path.dirname(dirPath);
            mkDirP(parent).then(() => {
71
                fs.mkdir(dirPath, (err: Error) => {
Deshui Yu's avatar
Deshui Yu committed
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
                    if (err) {
                        deferred.reject(err);
                    } else {
                        deferred.resolve();
                    }
                });
            }).catch((err: Error) => {
                deferred.reject(err);
            });
        }
    });

    return deferred.promise;
}

function mkDirPSync(dirPath: string): void {
    if (fs.existsSync(dirPath)) {
        return;
    }
    mkDirPSync(path.dirname(dirPath));
    fs.mkdirSync(dirPath);
}

const delay: (ms: number) => Promise<void> = util.promisify(setTimeout);

/**
 * Convert index to character
 * @param index index
 * @returns a mapping character
 */
function charMap(index: number): number {
    if (index < 26) {
        return index + 97;
    } else if (index < 52) {
        return index - 26 + 65;
    } else {
        return index - 52 + 48;
    }
}

/**
 * Generate a unique string by length
 * @param len length of string
 * @returns a unique string
 */
function uniqueString(len: number): string {
    if (len === 0) {
        return '';
    }
    const byteLength: number = Math.ceil((Math.log2(52) + Math.log2(62) * (len - 1)) / 8);
    let num: number = randomBytes(byteLength).reduce((a: number, b: number) => a * 256 + b, 0);
    const codes: number[] = [];
    codes.push(charMap(num % 52));
    num = Math.floor(num / 52);
    for (let i: number = 1; i < len; i++) {
        codes.push(charMap(num % 62));
        num = Math.floor(num / 62);
    }

    return String.fromCharCode(...codes);
}

134
135
136
137
138
139
function randomSelect<T>(a: T[]): T {
    assert(a !== undefined);

    // tslint:disable-next-line:insecure-random
    return a[Math.floor(Math.random() * a.length)];
}
Deshui Yu's avatar
Deshui Yu committed
140
141
142
143
144
145
146
147
148
149
150
151
function parseArg(names: string[]): string {
    if (process.argv.length >= 4) {
        for (let i: number = 2; i < process.argv.length - 1; i++) {
            if (names.includes(process.argv[i])) {
                return process.argv[i + 1];
            }
        }
    }

    return '';
}

152
function encodeCmdLineArgs(args: any): any {
153
154
155
156
157
158
159
160
    if(process.platform === 'win32'){
        return JSON.stringify(args);
    }
    else{
        return JSON.stringify(JSON.stringify(args));
    }
}

161
function getCmdPy(): string {
162
163
164
165
166
167
168
    let cmd = 'python3';
    if(process.platform === 'win32'){
        cmd = 'python';
    }
    return cmd;
}

169
/**
170
 * Generate command line to start automl algorithm(s),
QuanluZhang's avatar
QuanluZhang committed
171
 * either start advisor or start a process which runs tuner and assessor
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
 * @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
QuanluZhang's avatar
QuanluZhang committed
192
 * @param advisor: similar as tuner
193
194
 *
 */
QuanluZhang's avatar
QuanluZhang committed
195
196
197
198
199
200
201
function getMsgDispatcherCommand(tuner: any, assessor: any, advisor: any, multiPhase: boolean = false, multiThread: boolean = false): string {
    if ((tuner || assessor) && advisor) {
        throw new Error('Error: specify both tuner/assessor and advisor is not allowed');
    }
    if (!tuner && !advisor) {
        throw new Error('Error: specify neither tuner nor advisor is not allowed');
    }
202
    let command: string = `${getCmdPy()} -m nni`;
chicm-ms's avatar
chicm-ms committed
203
204
205
    if (multiPhase) {
        command += ' --multi_phase';
    }
206

chicm-ms's avatar
chicm-ms committed
207
208
209
210
    if (multiThread) {
        command += ' --multi_thread';
    }

QuanluZhang's avatar
QuanluZhang committed
211
212
213
    if (advisor) {
        command += ` --advisor_class_name ${advisor.className}`;
        if (advisor.classArgs !== undefined) {
214
            command += ` --advisor_args ${encodeCmdLineArgs(advisor.classArgs)}`;
215
        }
QuanluZhang's avatar
QuanluZhang committed
216
217
218
219
220
221
222
223
224
        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) {
225
            command += ` --tuner_args ${encodeCmdLineArgs(tuner.classArgs)}`;
QuanluZhang's avatar
QuanluZhang committed
226
227
228
229
230
231
        }
        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}`;
232
233
        }

QuanluZhang's avatar
QuanluZhang committed
234
235
236
        if (assessor !== undefined && assessor.className !== undefined) {
            command += ` --assessor_class_name ${assessor.className}`;
            if (assessor.classArgs !== undefined) {
237
                command += ` --assessor_args ${encodeCmdLineArgs(assessor.classArgs)}`;
QuanluZhang's avatar
QuanluZhang committed
238
239
240
241
242
243
244
            }
            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}`;
            }
245
246
247
248
249
250
        }
    }

    return command;
}

251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
/**
 * Generate parameter file name based on HyperParameters object
 * @param hyperParameters HyperParameters instance
 */
function generateParamFileName(hyperParameters : HyperParameters): string {
    assert(hyperParameters !== undefined);
    assert(hyperParameters.index >= 0);

    let paramFileName : string;
    if(hyperParameters.index == 0) {
        paramFileName = 'parameter.cfg';
    } else {
        paramFileName = `parameter_${hyperParameters.index}.cfg`
    }
    return paramFileName;
}

Deshui Yu's avatar
Deshui Yu committed
268
269
270
271
272
273
274
275
276
277
278
/**
 * Initialize a pseudo experiment environment for unit test.
 * Must be paired with `cleanupUnitTest()`.
 */
function prepareUnitTest(): void {
    Container.snapshot(ExperimentStartupInfo);
    Container.snapshot(Database);
    Container.snapshot(DataStore);
    Container.snapshot(TrainingService);
    Container.snapshot(Manager);

279
    setExperimentStartupInfo(true, 'unittest', 8080);
Deshui Yu's avatar
Deshui Yu committed
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
    mkDirPSync(getLogDir());

    const sqliteFile: string = path.join(getDefaultDatabaseDir(), 'nni.sqlite');
    try {
        fs.unlinkSync(sqliteFile);
    } catch (err) {
        // file not exists, good
    }
}

/**
 * Clean up unit test pseudo experiment.
 * Must be paired with `prepareUnitTest()`.
 */
function cleanupUnitTest(): void {
    Container.restore(Manager);
    Container.restore(TrainingService);
    Container.restore(DataStore);
    Container.restore(Database);
    Container.restore(ExperimentStartupInfo);
}

302
let cachedipv4Address : string = '';
303
304
305
306
/**
 * Get IPv4 address of current machine
 */
function getIPV4Address(): string {
307
308
309
    if (cachedipv4Address && cachedipv4Address.length > 0) {
        return cachedipv4Address;
    }
310

311
312
313
314
315
316
    if(os.networkInterfaces().eth0) {
        for(const item of os.networkInterfaces().eth0) {
            if(item.family === 'IPv4') {
                cachedipv4Address = item.address;
                return cachedipv4Address;
            }
317
        }
318
319
    } else {
        throw Error('getIPV4Address() failed because os.networkInterfaces().eth0 is undefined.');
320
    }
321
322

    throw Error('getIPV4Address() failed because no valid IPv4 address found.')
323
324
}

325
326
327
328
329
330
331
332
function getRemoteTmpDir(osType: string): string {
    if (osType == 'linux') {
        return '/tmp';
    } else {
        throw Error(`remote OS ${osType} not supported`);
    }
}

QuanluZhang's avatar
QuanluZhang committed
333
334
335
336
337
338
339
/**
 * Get the status of canceled jobs according to the hint isEarlyStopped
 */
function getJobCancelStatus(isEarlyStopped: boolean): TrialJobStatus {
    return isEarlyStopped ? 'EARLY_STOPPED' : 'USER_CANCELED';
}

340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
/**
 * Utility method to calculate file numbers under a directory, recursively
 * @param directory directory name
 */
function countFilesRecursively(directory: string, timeoutMilliSeconds?: number): Promise<number> {
    if(!fs.existsSync(directory)) {
        throw Error(`Direcotory ${directory} doesn't exist`);
    }

    const deferred: Deferred<number> = new Deferred<number>();

    let timeoutId : NodeJS.Timer
    const delayTimeout : Promise<number> = new Promise((resolve : Function, reject : Function) : void => {
        // Set timeout and reject the promise once reach timeout (5 seconds)
        timeoutId = setTimeout(() => {
            reject(new Error(`Timeout: path ${directory} has too many files`));
        }, 5000);
    });

    let fileCount: number = -1;
360
361
362
363
    let cmd: string;
    if(process.platform === "win32") {
        cmd = `powershell "Get-ChildItem -Path ${directory} -Recurse -File | Measure-Object | %{$_.Count}"`
    } else {
364
        cmd = `find ${directory} -type f | wc -l`;
365
366
    }
    cpp.exec(cmd).then((result) => {
367
        if(result.stdout && parseInt(result.stdout)) {
368
            fileCount = parseInt(result.stdout);
369
370
371
372
373
374
375
376
        }
        deferred.resolve(fileCount);
    });
    return Promise.race([deferred.promise, delayTimeout]).finally(() => {
        clearTimeout(timeoutId);
    });
}

377
function validateFileName(fileName: string): boolean {
378
    let pattern: string = '^[a-z0-9A-Z\._-]+$';
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
    const validateResult = fileName.match(pattern);
    if(validateResult) {
        return true;
    }
    return false;
}

async function validateFileNameRecursively(directory: string): Promise<boolean> {
    if(!fs.existsSync(directory)) {
        throw Error(`Direcotory ${directory} doesn't exist`);
    }

    const fileNameArray: string[] = fs.readdirSync(directory);
    let result = true;
    for(var name of fileNameArray){
        const fullFilePath: string = path.join(directory, name);
        try {
            // validate file names and directory names
            result = validateFileName(name);
            if (fs.lstatSync(fullFilePath).isDirectory()) {
                result = result && await validateFileNameRecursively(fullFilePath);
            }
            if(!result) {
                return Promise.reject(new Error(`file name in ${fullFilePath} is not valid!`));
            }
        } catch(error) {
            return Promise.reject(error);
        }
    }
    return Promise.resolve(result);   
}

411
412
413
414
415
416
417
418
419
420
421
/**
 * get the version of current package
 */
async function getVersion(): Promise<string> {
    const deferred : Deferred<string> = new Deferred<string>();
    import(path.join(__dirname, '..', 'package.json')).then((pkg)=>{
        deferred.resolve(pkg.version);
    }).catch((error)=>{
        deferred.reject(error);
    });
    return deferred.promise;
422
}
423

424
425
426
/**
 * run command as ChildProcess
 */
427
function getTunerProc(command: string, stdio: StdioOptions, newCwd: string, newEnv: any): ChildProcess {
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
    let cmd: string = command;
    let arg: string[] = [];
    let newShell: boolean = true;
    if(process.platform === "win32"){
        cmd = command.split(" ", 1)[0];
        arg = command.substr(cmd.length+1).split(" ");
        newShell = false;
    }
    const tunerProc: ChildProcess = spawn(cmd, arg, {
        stdio,
        cwd: newCwd,
        env: newEnv,
        shell: newShell
    });
    return tunerProc;
}

/**
 * judge whether the process is alive
 */
448
async function isAlive(pid:any): Promise<boolean> {
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
    let deferred : Deferred<boolean> = new Deferred<boolean>();
    let alive: boolean = false;
    if(process.platform ==='win32'){
        try {
            const str = cp.execSync(`powershell.exe Get-Process -Id ${pid} -ErrorAction SilentlyContinue`).toString();
            if (str) {
                alive = true;
            }
        }
        catch (error) {
        }
    }
    else{
        try {
            await cpp.exec(`kill -0 ${pid}`);
            alive = true;
        } catch (error) {
            //ignore
        }
    }
    deferred.resolve(alive);
    return deferred.promise;
}

/**
474
 * kill process
475
 */
476
async function killPid(pid:any): Promise<void> {
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
    let deferred : Deferred<void> = new Deferred<void>();
    try {
        if (process.platform === "win32") {
            await cpp.exec(`cmd /c taskkill /PID ${pid} /F`);
        }
        else{
            await cpp.exec(`kill -9 ${pid}`);
        }
    } catch (error) {
        // pid does not exist, do nothing here
    }
    deferred.resolve();
    return deferred.promise;
}

492
function getNewLine(): string {
493
494
495
496
497
498
499
500
    if (process.platform === "win32") {
        return "\r\n";
    }
    else{
        return "\n";
    }
}

501
502
/**
 * Use '/' to join path instead of '\' for all kinds of platform
503
 * @param path
504
505
506
507
508
509
510
 */
function unixPathJoin(...paths: any[]): string {
    const dir: string = paths.filter((path: any) => path !== '').join('/');
    if (dir === '') return '.';
    return dir;
}

511
export {countFilesRecursively, validateFileNameRecursively, getRemoteTmpDir, generateParamFileName, getMsgDispatcherCommand, getCheckpointDir,
512
    getLogDir, getExperimentRootDir, getJobCancelStatus, getDefaultDatabaseDir, getIPV4Address, unixPathJoin,
513
    mkDirP, delay, prepareUnitTest, parseArg, cleanupUnitTest, uniqueString, randomSelect, getLogLevel, getVersion, getCmdPy, getTunerProc, isAlive, killPid, getNewLine };