nnimanager.ts 38 KB
Newer Older
liuzhe-lz's avatar
liuzhe-lz committed
1
2
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
Deshui Yu's avatar
Deshui Yu committed
3
4
5
6

'use strict';

import * as assert from 'assert';
chicm-ms's avatar
chicm-ms committed
7
import { ChildProcess, StdioOptions } from 'child_process';
Deshui Yu's avatar
Deshui Yu committed
8
9
10
import { Deferred } from 'ts-deferred';
import * as component from '../common/component';
import { DataStore, MetricDataRecord, MetricType, TrialJobInfo } from '../common/datastore';
11
import { NNIError } from '../common/errors';
12
import { getExperimentId, getDispatcherPipe } from '../common/experimentStartupInfo';
Deshui Yu's avatar
Deshui Yu committed
13
14
import { getLogger, Logger } from '../common/log';
import {
chicm-ms's avatar
chicm-ms committed
15
    ExperimentParams, ExperimentProfile, Manager, ExperimentStatus,
16
    NNIManagerStatus, ProfileUpdateType, TrialJobStatistics
Deshui Yu's avatar
Deshui Yu committed
17
} from '../common/manager';
18
import { ExperimentManager } from '../common/experimentManager';
J-shang's avatar
J-shang committed
19
import { TensorboardManager } from '../common/tensorboardManager';
Deshui Yu's avatar
Deshui Yu committed
20
import {
21
    TrainingService, TrialJobApplicationForm, TrialJobDetail, TrialJobMetric, TrialJobStatus, LogType
Deshui Yu's avatar
Deshui Yu committed
22
} from '../common/trainingService';
23
import { delay, getCheckpointDir, getExperimentRootDir, getLogDir, getMsgDispatcherCommand, mkDirP, getTunerProc, getLogLevel, isAlive, killPid } from '../common/utils';
Deshui Yu's avatar
Deshui Yu committed
24
import {
chicm-ms's avatar
chicm-ms committed
25
    INITIALIZE, INITIALIZED, KILL_TRIAL_JOB, NEW_TRIAL_JOB, NO_MORE_TRIAL_JOBS, PING,
26
    REPORT_METRIC_DATA, REQUEST_TRIAL_JOBS, SEND_TRIAL_JOB_PARAMETER, TERMINATE, TRIAL_END, UPDATE_SEARCH_SPACE, IMPORT_DATA
Deshui Yu's avatar
Deshui Yu committed
27
} from './commands';
28
import { createDispatcherInterface, createDispatcherPipeInterface, IpcInterface } from './ipcInterface';
29
import { NNIRestServer } from '../rest_server/nniRestServer';
Deshui Yu's avatar
Deshui Yu committed
30
31

/**
chicm-ms's avatar
chicm-ms committed
32
 * NNIManager which implements Manager interface
Deshui Yu's avatar
Deshui Yu committed
33
34
35
 */
class NNIManager implements Manager {
    private trainingService: TrainingService;
36
    private dispatcher: IpcInterface | undefined;
37
    private experimentManager: ExperimentManager;
38
    private currSubmittedTrialNum: number;  // need to be recovered
QuanluZhang's avatar
QuanluZhang committed
39
    private trialConcurrencyChange: number; // >0: increase, <0: decrease
Deshui Yu's avatar
Deshui Yu committed
40
41
42
    private log: Logger;
    private dataStore: DataStore;
    private experimentProfile: ExperimentProfile;
43
    private dispatcherPid: number;
44
    private status: NNIManagerStatus;
45
    private waitingTrials: TrialJobApplicationForm[];
QuanluZhang's avatar
QuanluZhang committed
46
    private trialJobs: Map<string, TrialJobDetail>;
47
    private trialDataForTuner: string;
SparkSnail's avatar
SparkSnail committed
48
    private readonly: boolean;
49

50
    private trialJobMetricListener: (metric: TrialJobMetric) => void;
51

Deshui Yu's avatar
Deshui Yu committed
52
53
    constructor() {
        this.currSubmittedTrialNum = 0;
QuanluZhang's avatar
QuanluZhang committed
54
        this.trialConcurrencyChange = 0;
Deshui Yu's avatar
Deshui Yu committed
55
        this.trainingService = component.get(TrainingService);
56
        this.experimentManager = component.get(ExperimentManager);
Deshui Yu's avatar
Deshui Yu committed
57
        assert(this.trainingService);
58
        this.dispatcherPid = 0;
QuanluZhang's avatar
QuanluZhang committed
59
60
        this.waitingTrials = [];
        this.trialJobs = new Map<string, TrialJobDetail>();
61
        this.trialDataForTuner = '';
SparkSnail's avatar
SparkSnail committed
62
        this.readonly = false;
Deshui Yu's avatar
Deshui Yu committed
63
64
65

        this.log = getLogger();
        this.dataStore = component.get(DataStore);
66
67
68
69
        this.experimentProfile = this.createEmptyExperimentProfile();
        this.status = {
            status: 'INITIALIZED',
            errors: []
Deshui Yu's avatar
Deshui Yu committed
70
        };
chicm-ms's avatar
chicm-ms committed
71
        this.trialJobMetricListener = (metric: TrialJobMetric): void => {
72
73
74
75
            this.onTrialJobMetrics(metric).catch((err: Error) => {
                this.criticalError(NNIError.FromError(err, 'Job metrics error: '));
            });
        };
76
77
78
79
80

        const pipe = getDispatcherPipe();
        if (pipe !== null) {
            this.dispatcher = createDispatcherPipeInterface(pipe);
        }
Deshui Yu's avatar
Deshui Yu committed
81
82
83
    }

    public updateExperimentProfile(experimentProfile: ExperimentProfile, updateType: ProfileUpdateType): Promise<void> {
SparkSnail's avatar
SparkSnail committed
84
85
86
        if (this.readonly) {
            return Promise.reject(new Error('Error: can not update experiment profile in readonly mode!'));
        }
Deshui Yu's avatar
Deshui Yu committed
87
88
89
90
91
92
93
94
95
96
        switch (updateType) {
            case 'TRIAL_CONCURRENCY':
                this.updateTrialConcurrency(experimentProfile.params.trialConcurrency);
                break;
            case 'MAX_EXEC_DURATION':
                this.updateMaxExecDuration(experimentProfile.params.maxExecDuration);
                break;
            case 'SEARCH_SPACE':
                this.updateSearchSpace(experimentProfile.params.searchSpace);
                break;
QuanluZhang's avatar
QuanluZhang committed
97
98
99
            case 'MAX_TRIAL_NUM':
                this.updateMaxTrialNum(experimentProfile.params.maxTrialNum);
                break;
Deshui Yu's avatar
Deshui Yu committed
100
101
102
103
104
105
106
            default:
                throw new Error('Error: unrecognized updateType');
        }

        return this.storeExperimentProfile();
    }

107
    public importData(data: string): Promise<void> {
SparkSnail's avatar
SparkSnail committed
108
109
110
        if (this.readonly) {
            return Promise.reject(new Error('Error: can not import data in readonly mode!'));
        }
111
112
113
114
115
116
117
118
119
120
        if (this.dispatcher === undefined) {
            return Promise.reject(
                new Error('tuner has not been setup')
            );
        }
        this.dispatcher.sendCommand(IMPORT_DATA, data);

        return this.dataStore.storeTrialJobEvent('IMPORT_DATA', '', data);
    }

121
122
123
124
    public getImportedData(): Promise<string[]> {
        return this.dataStore.getImportedData();
    }

125
126
127
128
    public async exportData(): Promise<string> {
        return this.dataStore.exportTrialHpConfigs();
    }

129
    public addCustomizedTrialJob(hyperParams: string): Promise<number> {
SparkSnail's avatar
SparkSnail committed
130
131
132
        if (this.readonly) {
            return Promise.reject(new Error('Error: can not add customized trial job in readonly mode!'));
        }
Deshui Yu's avatar
Deshui Yu committed
133
        if (this.currSubmittedTrialNum >= this.experimentProfile.params.maxTrialNum) {
134
            return Promise.reject(new Error('reach maxTrialNum'));
Deshui Yu's avatar
Deshui Yu committed
135
        }
136
137
138

        // TODO: NNI manager should not peek tuner's internal protocol, let's refactor this later
        const packedParameter = {
chicm-ms's avatar
chicm-ms committed
139
140
            parameter_id: null, // eslint-disable-line @typescript-eslint/camelcase
            parameter_source: 'customized', // eslint-disable-line @typescript-eslint/camelcase
141
142
143
144
145
146
147
148
149
150
151
            parameters: JSON.parse(hyperParams)
        }

        const form: TrialJobApplicationForm = {
            sequenceId: this.experimentProfile.nextSequenceId++,
            hyperParameters: {
                value: JSON.stringify(packedParameter),
                index: 0
            }
        };
        this.waitingTrials.push(form);
Deshui Yu's avatar
Deshui Yu committed
152
153

        // trial id has not been generated yet, thus use '' instead
154
155
156
        this.dataStore.storeTrialJobEvent('ADD_CUSTOMIZED', '', hyperParams);

        return Promise.resolve(form.sequenceId);
Deshui Yu's avatar
Deshui Yu committed
157
158
159
    }

    public async cancelTrialJobByUser(trialJobId: string): Promise<void> {
SparkSnail's avatar
SparkSnail committed
160
161
162
        if (this.readonly) {
            return Promise.reject(new Error('Error: can not cancel trial job in readonly mode!'));
        }
chicm-ms's avatar
chicm-ms committed
163
        this.log.info(`User cancelTrialJob: ${trialJobId}`);
Deshui Yu's avatar
Deshui Yu committed
164
165
166
167
168
        await this.trainingService.cancelTrialJob(trialJobId);
        await this.dataStore.storeTrialJobEvent('USER_TO_CANCEL', trialJobId, '');
    }

    public async startExperiment(expParams: ExperimentParams): Promise<string> {
chicm-ms's avatar
chicm-ms committed
169
        this.log.info(`Starting experiment: ${this.experimentProfile.id}`);
Deshui Yu's avatar
Deshui Yu committed
170
171
172
        this.experimentProfile.params = expParams;
        await this.storeExperimentProfile();
        this.log.debug('Setup tuner...');
173

174
        // Set up multiphase config
175
        if (expParams.multiPhase && this.trainingService.isMultiPhaseJobSupported) {
176
177
            this.trainingService.setClusterMetadata('multiPhase', expParams.multiPhase.toString());
        }
178
179
180
181
        // Set up versionCheck config
        if (expParams.versionCheck !== undefined) {
            this.trainingService.setClusterMetadata('version_check', expParams.versionCheck.toString());
        }
SparkSnail's avatar
SparkSnail committed
182
183
184
185
        // Set up logCollection config
        if (expParams.logCollection !== undefined) {
            this.trainingService.setClusterMetadata('log_collection', expParams.logCollection.toString());
        }
186

chicm-ms's avatar
chicm-ms committed
187
        const dispatcherCommand: string = getMsgDispatcherCommand(expParams);
188
        this.log.debug(`dispatcher command: ${dispatcherCommand}`);
QuanluZhang's avatar
QuanluZhang committed
189
        const checkpointDir: string = await this.createCheckpointDir();
Deshui Yu's avatar
Deshui Yu committed
190
        this.setupTuner(
191
192
            dispatcherCommand,
            undefined,
Deshui Yu's avatar
Deshui Yu committed
193
            'start',
QuanluZhang's avatar
QuanluZhang committed
194
            checkpointDir);
Deshui Yu's avatar
Deshui Yu committed
195

196
        this.experimentProfile.startTime = Date.now();
chicm-ms's avatar
chicm-ms committed
197
        this.setStatus('RUNNING');
Deshui Yu's avatar
Deshui Yu committed
198
        await this.storeExperimentProfile();
199
200
        this.run().catch((err: Error) => {
            this.criticalError(err);
Deshui Yu's avatar
Deshui Yu committed
201
        });
202

Deshui Yu's avatar
Deshui Yu committed
203
204
205
        return this.experimentProfile.id;
    }

SparkSnail's avatar
SparkSnail committed
206
    public async resumeExperiment(readonly: boolean): Promise<void> {
chicm-ms's avatar
chicm-ms committed
207
        this.log.info(`Resuming experiment: ${this.experimentProfile.id}`);
Deshui Yu's avatar
Deshui Yu committed
208
209
210
        //Fetch back the experiment profile
        const experimentId: string = getExperimentId();
        this.experimentProfile = await this.dataStore.getExperimentProfile(experimentId);
SparkSnail's avatar
SparkSnail committed
211
212
213
214
        this.readonly = readonly;
        if (readonly) {
            return Promise.resolve();
        }
Deshui Yu's avatar
Deshui Yu committed
215
        const expParams: ExperimentParams = this.experimentProfile.params;
216

217
        // Set up multiphase config
218
        if (expParams.multiPhase && this.trainingService.isMultiPhaseJobSupported) {
219
220
221
            this.trainingService.setClusterMetadata('multiPhase', expParams.multiPhase.toString());
        }

222
223
        // Set up versionCheck config
        if (expParams.versionCheck !== undefined) {
SparkSnail's avatar
SparkSnail committed
224
            this.trainingService.setClusterMetadata('version_check', expParams.versionCheck.toString());
225
226
        }

chicm-ms's avatar
chicm-ms committed
227
        const dispatcherCommand: string = getMsgDispatcherCommand(expParams);
228
        this.log.debug(`dispatcher command: ${dispatcherCommand}`);
QuanluZhang's avatar
QuanluZhang committed
229
        const checkpointDir: string = await this.createCheckpointDir();
Deshui Yu's avatar
Deshui Yu committed
230
        this.setupTuner(
231
232
            dispatcherCommand,
            undefined,
Deshui Yu's avatar
Deshui Yu committed
233
            'resume',
QuanluZhang's avatar
QuanluZhang committed
234
            checkpointDir);
Deshui Yu's avatar
Deshui Yu committed
235
236
237
238
239
240
241
242
243

        const allTrialJobs: TrialJobInfo[] = await this.dataStore.listTrialJobs();

        // Resume currSubmittedTrialNum
        this.currSubmittedTrialNum = allTrialJobs.length;

        // Check the final status for WAITING and RUNNING jobs
        await Promise.all(allTrialJobs
            .filter((job: TrialJobInfo) => job.status === 'WAITING' || job.status === 'RUNNING')
J-shang's avatar
J-shang committed
244
            .map((job: TrialJobInfo) => this.dataStore.storeTrialJobEvent('FAILED', job.trialJobId)));
Deshui Yu's avatar
Deshui Yu committed
245

246
247
248
        // Collect generated trials and imported trials
        const finishedTrialData: string = await this.exportData();
        const importedData: string[] = await this.dataStore.getImportedData();
chicm-ms's avatar
chicm-ms committed
249
        let trialData: Record<string, any>[] = JSON.parse(finishedTrialData);
250
251
        for (const oneImportedData of importedData) {
            // do not deduplicate
chicm-ms's avatar
chicm-ms committed
252
            trialData = trialData.concat(<Record<string, any>[]>JSON.parse(oneImportedData));
253
254
255
        }
        this.trialDataForTuner = JSON.stringify(trialData);

chicm-ms's avatar
chicm-ms committed
256
257
258
259
260
        if (this.experimentProfile.execDuration < this.experimentProfile.params.maxExecDuration &&
            this.currSubmittedTrialNum < this.experimentProfile.params.maxTrialNum &&
            this.experimentProfile.endTime) {
            delete this.experimentProfile.endTime;
        }
chicm-ms's avatar
chicm-ms committed
261
        this.setStatus('RUNNING');
262

Deshui Yu's avatar
Deshui Yu committed
263
        // TO DO: update database record for resume event
264
265
266
        this.run().catch((err: Error) => {
            this.criticalError(err);
        });
Deshui Yu's avatar
Deshui Yu committed
267
268
    }

269
270
    public getTrialJob(trialJobId: string): Promise<TrialJobInfo> {
        return this.dataStore.getTrialJob(trialJobId);
Deshui Yu's avatar
Deshui Yu committed
271
272
273
    }

    public async setClusterMetadata(key: string, value: string): Promise<void> {
SparkSnail's avatar
SparkSnail committed
274
275
276
        if (this.readonly) {
            return Promise.reject(new Error('Error: can not set cluster metadata in readonly mode!'));
        }
chicm-ms's avatar
chicm-ms committed
277
        this.log.info(`NNIManager setClusterMetadata, key: ${key}, value: ${value}`);
Deshui Yu's avatar
Deshui Yu committed
278
279
280
281
        let timeoutId: NodeJS.Timer;
        // TO DO: move timeout value to constants file
        const delay1: Promise<{}> = new Promise((resolve: Function, reject: Function): void => {
            timeoutId = setTimeout(
282
                () => { reject(new Error('TrainingService setClusterMetadata timeout. Please check your config file.')); },
283
                30000);
Deshui Yu's avatar
Deshui Yu committed
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
        });
        await Promise.race([delay1, this.trainingService.setClusterMetadata(key, value)]).finally(() => {
            clearTimeout(timeoutId);
        });
    }

    public getClusterMetadata(key: string): Promise<string> {
        return Promise.resolve(
            this.trainingService.getClusterMetadata(key)
        );
    }

    public async getTrialJobStatistics(): Promise<TrialJobStatistics[]> {
        return this.dataStore.getTrialJobStatistics();
    }

300
    public async stopExperiment(): Promise<void> {
301
302
303
304
305
        await this.stopExperimentTopHalf();
        await this.stopExperimentBottomHalf();
    }

    public async stopExperimentTopHalf(): Promise<void> {
chicm-ms's avatar
chicm-ms committed
306
307
        this.setStatus('STOPPING');
        this.log.info('Stopping experiment, cleaning up ...');
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329

        if (this.dispatcher === undefined) {
            this.log.error('Tuner has not been setup');
            return;
        }

        this.trainingService.removeTrialJobMetricListener(this.trialJobMetricListener);
        if (this.dispatcherPid > 0) {
            this.dispatcher.sendCommand(TERMINATE);
            // gracefully terminate tuner and assessor here, wait at most 30 seconds.
            for (let i: number = 0; i < 30; i++) {
                if (!await isAlive(this.dispatcherPid)) {
                    break;
                }
                await delay(1000);
            }
            await killPid(this.dispatcherPid);
        }
        this.dispatcher = undefined;
    }

    public async stopExperimentBottomHalf(): Promise<void> {
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        try {
            const trialJobList: TrialJobDetail[] = await this.trainingService.listTrialJobs();

            // DON'T try to make it in parallel, the training service may not handle it well.
            // If there is performance concern, consider to support batch cancellation on training service.
            for (const trialJob of trialJobList) {
                if (trialJob.status === 'RUNNING' ||
                    trialJob.status === 'WAITING') {
                    try {
                        this.log.info(`cancelTrialJob: ${trialJob.id}`);
                        await this.trainingService.cancelTrialJob(trialJob.id);
                    } catch (error) {
                        this.log.debug(`ignorable error on canceling trial ${trialJob.id}. ${error}`);
                    }
344
345
                }
            }
346
347
348
            await this.trainingService.cleanUp();
        } catch (err) {
            this.log.error(`${err.stack}`);
349
350
351
352
353
354
        }
        if (this.experimentProfile.endTime === undefined) {
            this.setEndtime();
        }
        await this.storeExperimentProfile();
        this.setStatus('STOPPED');
chicm-ms's avatar
chicm-ms committed
355
        this.log.info('Experiment stopped.');
356
357
358

        let hasError: boolean = false;
        try {
liuzhe-lz's avatar
liuzhe-lz committed
359
            await this.experimentManager.stop();
J-shang's avatar
J-shang committed
360
            await component.get<TensorboardManager>(TensorboardManager).stop();
liuzhe-lz's avatar
liuzhe-lz committed
361
            await this.dataStore.close();
362
363
364
365
366
367
368
369
            await component.get<NNIRestServer>(NNIRestServer).stop();
        } catch (err) {
            hasError = true;
            this.log.error(`${err.stack}`);
        } finally {
            this.log.close();
            process.exit(hasError ? 1 : 0);
        }
Deshui Yu's avatar
Deshui Yu committed
370
371
    }

372
    public async getMetricData(trialJobId?: string, metricType?: MetricType): Promise<MetricDataRecord[]> {
Deshui Yu's avatar
Deshui Yu committed
373
374
375
        return this.dataStore.getMetricData(trialJobId, metricType);
    }

376
377
378
379
380
381
    public async getMetricDataByRange(minSeqId: number, maxSeqId: number): Promise<MetricDataRecord[]> {
        const trialJobs = await this.dataStore.listTrialJobs();
        const targetTrials = trialJobs.filter(trial => (
            // FIXME: can this be undefined?
            trial.sequenceId !== undefined && minSeqId <= trial.sequenceId && trial.sequenceId <= maxSeqId
        ));
J-shang's avatar
J-shang committed
382
        const targetTrialIds = new Set(targetTrials.map(trial => trial.trialJobId));
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406

        const allMetrics = await this.dataStore.getMetricData();
        return allMetrics.filter(metric => targetTrialIds.has(metric.trialJobId));
    }

    public async getLatestMetricData(): Promise<MetricDataRecord[]> {
        // FIXME: this can take a long time
        const allMetrics: MetricDataRecord[] = await this.dataStore.getMetricData();
        const finals: MetricDataRecord[] = [];
        const latestIntermediates: Map<string, MetricDataRecord> = new Map<string, MetricDataRecord>();
        for (const metric of allMetrics) {
            if (metric.type !== 'PERIODICAL') {
                finals.push(metric);
            } else {
                const old: MetricDataRecord | undefined = latestIntermediates.get(metric.trialJobId);
                if (old === undefined || old.sequence <= metric.sequence) {
                    latestIntermediates.set(metric.trialJobId, metric);
                }
            }
        }
        return finals.concat(Array.from(latestIntermediates.values()));
        // FIXME: unit test
    }

407
408
409
410
    public async getTrialLog(trialJobId: string, logType: LogType): Promise<string> {
        return this.trainingService.getTrialLog(trialJobId, logType);
    }

Deshui Yu's avatar
Deshui Yu committed
411
412
413
414
415
416
417
418
    public getExperimentProfile(): Promise<ExperimentProfile> {
        // TO DO: using Promise.resolve()
        const deferred: Deferred<ExperimentProfile> = new Deferred<ExperimentProfile>();
        deferred.resolve(this.experimentProfile);

        return deferred.promise;
    }

419
420
421
422
    public getStatus(): NNIManagerStatus {
        return this.status;
    }

Deshui Yu's avatar
Deshui Yu committed
423
424
425
426
    public async listTrialJobs(status?: TrialJobStatus): Promise<TrialJobInfo[]> {
        return this.dataStore.listTrialJobs(status);
    }

427
428
    private setupTuner(command: string, cwd: string | undefined, mode: 'start' | 'resume', dataDirectory: string): void {
        if (this.dispatcher !== undefined) {
Deshui Yu's avatar
Deshui Yu committed
429
430
            return;
        }
goooxu's avatar
goooxu committed
431
        const stdio: StdioOptions = ['ignore', process.stdout, process.stderr, 'pipe', 'pipe'];
Deshui Yu's avatar
Deshui Yu committed
432
433
434
435
436
437
438
        let newCwd: string;
        if (cwd === undefined || cwd === '') {
            newCwd = getLogDir();
        } else {
            newCwd = cwd;
        }
        // TO DO: add CUDA_VISIBLE_DEVICES
439
440
441
442
443
        let includeIntermediateResultsEnv: boolean | undefined = false;
        if (this.experimentProfile.params.tuner !== undefined) {
            includeIntermediateResultsEnv = this.experimentProfile.params.tuner.includeIntermediateResults;
        }

chicm-ms's avatar
chicm-ms committed
444
        const nniEnv = {
chicm-ms's avatar
chicm-ms committed
445
            SDK_PROCESS: 'dispatcher',
Zejun Lin's avatar
Zejun Lin committed
446
447
            NNI_MODE: mode,
            NNI_CHECKPOINT_DIRECTORY: dataDirectory,
448
            NNI_LOG_DIRECTORY: getLogDir(),
449
            NNI_LOG_LEVEL: getLogLevel(),
450
451
            NNI_INCLUDE_INTERMEDIATE_RESULTS: includeIntermediateResultsEnv,
            CUDA_VISIBLE_DEVICES: this.getGpuEnvvarValue()
Zejun Lin's avatar
Zejun Lin committed
452
        };
chicm-ms's avatar
chicm-ms committed
453
        const newEnv = Object.assign({}, process.env, nniEnv);
454
        const tunerProc: ChildProcess = getTunerProc(command, stdio, newCwd, newEnv);
455
456
        this.dispatcherPid = tunerProc.pid;
        this.dispatcher = createDispatcherInterface(tunerProc);
Deshui Yu's avatar
Deshui Yu committed
457
458
459
460

        return;
    }

461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
    private getGpuEnvvarValue(): string {
        let cudaDevices: string | undefined;

        if (this.experimentProfile.params.advisor !== undefined) {
            cudaDevices = this.experimentProfile.params.advisor.gpuIndices;
        } else if (this.experimentProfile.params.tuner !== undefined) {
            cudaDevices = this.experimentProfile.params.tuner.gpuIndices;
        }

        if (cudaDevices === undefined) {
            return '';
        } else {
            return cudaDevices;
        }
    }

Deshui Yu's avatar
Deshui Yu committed
477
    private updateTrialConcurrency(trialConcurrency: number): void {
QuanluZhang's avatar
QuanluZhang committed
478
479
        // we assume trialConcurrency >= 0, which is checked by restserver
        this.trialConcurrencyChange += (trialConcurrency - this.experimentProfile.params.trialConcurrency);
Deshui Yu's avatar
Deshui Yu committed
480
481
482
483
484
485
486
487
488
489
490
491
        this.experimentProfile.params.trialConcurrency = trialConcurrency;

        return;
    }

    private updateMaxExecDuration(duration: number): void {
        this.experimentProfile.params.maxExecDuration = duration;

        return;
    }

    private updateSearchSpace(searchSpace: string): void {
492
        if (this.dispatcher === undefined) {
Deshui Yu's avatar
Deshui Yu committed
493
494
            throw new Error('Error: tuner has not been setup');
        }
495
        this.dispatcher.sendCommand(UPDATE_SEARCH_SPACE, searchSpace);
Deshui Yu's avatar
Deshui Yu committed
496
497
498
499
500
        this.experimentProfile.params.searchSpace = searchSpace;

        return;
    }

QuanluZhang's avatar
QuanluZhang committed
501
502
503
504
505
506
    private updateMaxTrialNum(maxTrialNum: number): void {
        this.experimentProfile.params.maxTrialNum = maxTrialNum;

        return;
    }

Deshui Yu's avatar
Deshui Yu committed
507
    private async periodicallyUpdateExecDuration(): Promise<void> {
508
        let count: number = 1;
509
        while (!['ERROR', 'STOPPING', 'STOPPED'].includes(this.status.status)) {
510
            await delay(1000 * 1); // 1 seconds
511
            if (['RUNNING', 'NO_MORE_TRIAL', 'TUNER_NO_MORE_TRIAL'].includes(this.status.status)) {
512
513
514
515
516
517
                this.experimentProfile.execDuration += 1;
                if (count % 10 === 0) {
                    await this.storeExperimentProfile();
                }
            }
            count += 1;
Deshui Yu's avatar
Deshui Yu committed
518
519
520
        }
    }

chicm-ms's avatar
chicm-ms committed
521
522
523
524
525
526
    private async pingDispatcher(): Promise<void> {
        if (this.dispatcher === undefined) {
            throw new Error('Error: tuner has not been setup');
        }
        while (!['ERROR', 'STOPPING', 'STOPPED'].includes(this.status.status)) {
            this.dispatcher.sendCommand(PING);
chicm-ms's avatar
chicm-ms committed
527
            await delay(1000 * 5);
chicm-ms's avatar
chicm-ms committed
528
529
530
        }
    }

QuanluZhang's avatar
QuanluZhang committed
531
532
    private async requestTrialJobsStatus(): Promise<number> {
        let finishedTrialJobNum: number = 0;
QuanluZhang's avatar
QuanluZhang committed
533
534
535
        if (this.dispatcher === undefined) {
            throw new Error('Error: tuner has not been setup');
        }
QuanluZhang's avatar
QuanluZhang committed
536
537
538
539
        for (const trialJobId of Array.from(this.trialJobs.keys())) {
            const trialJobDetail: TrialJobDetail = await this.trainingService.getTrialJob(trialJobId);
            const oldTrialJobDetail: TrialJobDetail | undefined = this.trialJobs.get(trialJobId);
            if (oldTrialJobDetail !== undefined && oldTrialJobDetail.status !== trialJobDetail.status) {
chicm-ms's avatar
chicm-ms committed
540
                this.log.info(`Trial job ${trialJobDetail.id} status changed from ${oldTrialJobDetail.status} to ${trialJobDetail.status}`);
QuanluZhang's avatar
QuanluZhang committed
541
                this.trialJobs.set(trialJobId, Object.assign({}, trialJobDetail));
542
                await this.dataStore.storeTrialJobEvent(trialJobDetail.status, trialJobDetail.id, undefined, trialJobDetail);
QuanluZhang's avatar
QuanluZhang committed
543
            }
544
545
546
547
            const newTrialJobDetail: TrialJobDetail | undefined = this.trialJobs.get(trialJobId);
            if (newTrialJobDetail !== undefined) {
                newTrialJobDetail.message = trialJobDetail.message;
            }
QuanluZhang's avatar
QuanluZhang committed
548
            let hyperParams: string | undefined = undefined;
QuanluZhang's avatar
QuanluZhang committed
549
550
551
            switch (trialJobDetail.status) {
                case 'SUCCEEDED':
                case 'USER_CANCELED':
QuanluZhang's avatar
QuanluZhang committed
552
                case 'EARLY_STOPPED':
QuanluZhang's avatar
QuanluZhang committed
553
554
                    this.trialJobs.delete(trialJobId);
                    finishedTrialJobNum++;
555
                    hyperParams = trialJobDetail.form.hyperParameters.value;
QuanluZhang's avatar
QuanluZhang committed
556
                    this.dispatcher.sendCommand(TRIAL_END, JSON.stringify({
chicm-ms's avatar
chicm-ms committed
557
                        trial_job_id: trialJobDetail.id, // eslint-disable-line @typescript-eslint/camelcase
QuanluZhang's avatar
QuanluZhang committed
558
                        event: trialJobDetail.status,
chicm-ms's avatar
chicm-ms committed
559
                        hyper_params: hyperParams // eslint-disable-line @typescript-eslint/camelcase
goooxu's avatar
goooxu committed
560
                    }));
QuanluZhang's avatar
QuanluZhang committed
561
562
563
564
565
566
567
                    break;
                case 'FAILED':
                case 'SYS_CANCELED':
                    // In the current version, we do not retry
                    // TO DO: push this job to queue for retry
                    this.trialJobs.delete(trialJobId);
                    finishedTrialJobNum++;
568
                    hyperParams = trialJobDetail.form.hyperParameters.value;
QuanluZhang's avatar
QuanluZhang committed
569
                    this.dispatcher.sendCommand(TRIAL_END, JSON.stringify({
chicm-ms's avatar
chicm-ms committed
570
                        trial_job_id: trialJobDetail.id, // eslint-disable-line @typescript-eslint/camelcase
QuanluZhang's avatar
QuanluZhang committed
571
                        event: trialJobDetail.status,
chicm-ms's avatar
chicm-ms committed
572
                        hyper_params: hyperParams // eslint-disable-line @typescript-eslint/camelcase
goooxu's avatar
goooxu committed
573
                    }));
QuanluZhang's avatar
QuanluZhang committed
574
575
576
577
578
579
580
581
582
583
                    break;
                case 'WAITING':
                case 'RUNNING':
                case 'UNKNOWN':
                    // Do nothing
                    break;
                default:
                // TO DO: add warning in log
            }
        }
goooxu's avatar
goooxu committed
584

Gems Guo's avatar
Gems Guo committed
585
        return finishedTrialJobNum;
QuanluZhang's avatar
QuanluZhang committed
586
587
588
589
590
591
    }

    private async manageTrials(): Promise<void> {
        if (this.dispatcher === undefined) {
            throw new Error('Error: tuner has not been setup');
        }
QuanluZhang's avatar
QuanluZhang committed
592
        let allFinishedTrialJobNum: number = this.currSubmittedTrialNum;
QuanluZhang's avatar
QuanluZhang committed
593
        let waitSubmittedToFinish: number;
594
        while (!['ERROR', 'STOPPING', 'STOPPED'].includes(this.status.status)) {
QuanluZhang's avatar
QuanluZhang committed
595
596
597
598
599
600
601
            const finishedTrialJobNum: number = await this.requestTrialJobsStatus();
            allFinishedTrialJobNum += finishedTrialJobNum;

            // requestTrialNum is the number of trials that will be requested from tuner.
            // If trialConcurrency does not change, requestTrialNum equals finishedTrialJobNum.
            // If trialConcurrency changes, for example, trialConcurrency increases by 2 (trialConcurrencyChange=2), then
            // requestTrialNum equals 2 + finishedTrialJobNum and trialConcurrencyChange becomes 0.
602
            // If trialConcurrency changes, for example, trialConcurrency decreases by 4 (trialConcurrencyChange=-4) and
QuanluZhang's avatar
QuanluZhang committed
603
604
605
606
607
608
609
610
            // finishedTrialJobNum is 2, then requestTrialNum becomes -2. No trial will be requested from tuner,
            // and trialConcurrencyChange becomes -2.
            const requestTrialNum: number = this.trialConcurrencyChange + finishedTrialJobNum;
            if (requestTrialNum >= 0) {
                this.trialConcurrencyChange = 0;
            } else {
                this.trialConcurrencyChange = requestTrialNum;
            }
chicm-ms's avatar
chicm-ms committed
611

612
            this.requestTrialJobs(requestTrialNum);
chicm-ms's avatar
chicm-ms committed
613

QuanluZhang's avatar
QuanluZhang committed
614
            // check maxtrialnum and maxduration here
615
            // NO_MORE_TRIAL is more like a subset of RUNNING, because during RUNNING tuner
616
            // might tell nnimanager that this is no more trials. In NO_MORE_TRIAL state, the experiment is viewed
617
618
            // as still running. DONE could be transfered from RUNNING or NO_MORE_TRIAL.
            assert(this.status.status === 'RUNNING' ||
619
                this.status.status === 'DONE' ||
QuanluZhang's avatar
QuanluZhang committed
620
                this.status.status === 'NO_MORE_TRIAL' ||
621
                this.status.status === 'TUNER_NO_MORE_TRIAL', `Actual status: ${this.status.status}`);
622
            if (this.experimentProfile.execDuration > this.experimentProfile.params.maxExecDuration ||
QuanluZhang's avatar
QuanluZhang committed
623
                this.currSubmittedTrialNum >= this.experimentProfile.params.maxTrialNum) {
QuanluZhang's avatar
QuanluZhang committed
624
                if (this.status.status !== 'DONE') {
chicm-ms's avatar
chicm-ms committed
625
                    this.setStatus('NO_MORE_TRIAL');
QuanluZhang's avatar
QuanluZhang committed
626
627
628
629
                    waitSubmittedToFinish = this.currSubmittedTrialNum;

                    assert(allFinishedTrialJobNum <= waitSubmittedToFinish);
                    if (allFinishedTrialJobNum >= waitSubmittedToFinish) {
chicm-ms's avatar
chicm-ms committed
630
                        this.setStatus('DONE');
631
                        this.setEndtime();
QuanluZhang's avatar
QuanluZhang committed
632
633
634
635
                        await this.storeExperimentProfile();
                        // write this log for travis CI
                        this.log.info('Experiment done.');
                    }
QuanluZhang's avatar
QuanluZhang committed
636
637
638
                }
            } else {
                if (this.status.status === 'DONE') {
639
640
                    delete this.experimentProfile.endTime;
                    await this.storeExperimentProfile();
QuanluZhang's avatar
QuanluZhang committed
641
                }
QuanluZhang's avatar
QuanluZhang committed
642
                if (this.status.status !== 'TUNER_NO_MORE_TRIAL') {
chicm-ms's avatar
chicm-ms committed
643
                    this.setStatus('RUNNING');
644
                }
QuanluZhang's avatar
QuanluZhang committed
645
646
647
648
649
                for (let i: number = this.trialJobs.size; i < this.experimentProfile.params.trialConcurrency; i++) {
                    if (this.waitingTrials.length === 0 ||
                        this.currSubmittedTrialNum >= this.experimentProfile.params.maxTrialNum) {
                        break;
                    }
650
                    const form = this.waitingTrials.shift() as TrialJobApplicationForm;
QuanluZhang's avatar
QuanluZhang committed
651
                    this.currSubmittedTrialNum++;
652
653
                    this.log.info(`submitTrialJob: form: ${JSON.stringify(form)}`);
                    const trialJobDetail: TrialJobDetail = await this.trainingService.submitTrialJob(form);
654
                    const Snapshot: TrialJobDetail = Object.assign({}, trialJobDetail);
655
                    await this.storeExperimentProfile();
656
                    this.trialJobs.set(trialJobDetail.id, Snapshot);
QuanluZhang's avatar
QuanluZhang committed
657
658
659
                    const trialJobDetailSnapshot: TrialJobDetail | undefined = this.trialJobs.get(trialJobDetail.id);
                    if (trialJobDetailSnapshot != undefined) {
                        await this.dataStore.storeTrialJobEvent(
660
                            trialJobDetailSnapshot.status, trialJobDetailSnapshot.id, form.hyperParameters.value, trialJobDetailSnapshot);
QuanluZhang's avatar
QuanluZhang committed
661
662
663
664
665
666
667
668
669
                    } else {
                        assert(false, `undefined trialJobDetail in trialJobs: ${trialJobDetail.id}`);
                    }
                }
            }
            await delay(1000 * 5); // 5 seconds
        }
    }

Deshui Yu's avatar
Deshui Yu committed
670
671
672
673
674
675
    private storeExperimentProfile(): Promise<void> {
        this.experimentProfile.revision += 1;

        return this.dataStore.storeExperimentProfile(this.experimentProfile);
    }

676
    private async run(): Promise<void> {
QuanluZhang's avatar
QuanluZhang committed
677
        assert(this.dispatcher !== undefined);
678
679
680
681
682
683
684

        this.addEventListeners();

        this.sendInitTunerCommands();

        await Promise.all([
            this.periodicallyUpdateExecDuration(),
chicm-ms's avatar
chicm-ms committed
685
            this.pingDispatcher().catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
686
                throw NNIError.FromError(err, 'Dispatcher error: ');
chicm-ms's avatar
chicm-ms committed
687
            }),
688
            this.trainingService.run().catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
689
                throw NNIError.FromError(err, 'Training service error: ');
690
            }),
QuanluZhang's avatar
QuanluZhang committed
691
            this.manageTrials().catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
692
                throw NNIError.FromError(err, 'Job management error: ');
693
            })]);
694
695
    }

QuanluZhang's avatar
QuanluZhang committed
696
    private addEventListeners(): void {
chicm-ms's avatar
chicm-ms committed
697
        this.log.info('Add event listeners');
698
        // TO DO: cannot run this method more than once in one NNIManager instance
QuanluZhang's avatar
QuanluZhang committed
699
        if (this.dispatcher === undefined) {
700
701
            throw new Error('Error: tuner or job maintainer have not been setup');
        }
702
        this.trainingService.addTrialJobMetricListener(this.trialJobMetricListener);
703
704
705

        this.dispatcher.onCommand((commandType: string, content: string) => {
            this.onTunerCommand(commandType, content).catch((err: Error) => {
chicm-ms's avatar
chicm-ms committed
706
                this.criticalError(NNIError.FromError(err, 'Tuner command event error: '));
707
708
            });
        });
709
710
711
712
        this.dispatcher.onError((error: Error) => {
            this.log.error(`Dispatcher error: ${error.message}`);
            this.criticalError(new Error('Dispatcher stream error, tuner may have crashed.'));
        });
713
714
715
716
    }

    private sendInitTunerCommands(): void {
        if (this.dispatcher === undefined) {
717
            throw new Error('Dispatcher error: tuner has not been setup');
718
        }
chicm-ms's avatar
chicm-ms committed
719
720
721
        this.log.debug(`Send tuner command: INITIALIZE: ${this.experimentProfile.params.searchSpace}`);
        // Tuner need to be initialized with search space before generating any hyper parameters
        this.dispatcher.sendCommand(INITIALIZE, this.experimentProfile.params.searchSpace);
722
723
724
    }

    private async onTrialJobMetrics(metric: TrialJobMetric): Promise<void> {
725
        this.log.debug(`NNIManager received trial job metrics: ${JSON.stringify(metric)}`);
726
727
728
729
730
731
732
733
        if (this.trialJobs.has(metric.id)){
            await this.dataStore.storeMetricData(metric.id, metric.data);
            if (this.dispatcher === undefined) {
                throw new Error('Error: tuner has not been setup');
            }
            this.dispatcher.sendCommand(REPORT_METRIC_DATA, metric.data);
        } else {
            this.log.warning(`NNIManager received non-existent trial job metrics: ${metric}`);
734
735
736
        }
    }

chicm-ms's avatar
chicm-ms committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
    private requestTrialJobs(jobNum: number): void {
        if (jobNum < 1) {
            return;
        }
        if (this.dispatcher === undefined) {
            throw new Error('Dispatcher error: tuner has not been setup');
        }
        if (this.experimentProfile.params.multiThread) {
            // Send multiple requests to ensure multiple hyper parameters are generated in non-blocking way.
            // For a single REQUEST_TRIAL_JOBS request, hyper parameters are generated one by one
            // sequentially.
            for (let i: number = 0; i < jobNum; i++) {
                this.dispatcher.sendCommand(REQUEST_TRIAL_JOBS, '1');
            }
        } else {
            this.dispatcher.sendCommand(REQUEST_TRIAL_JOBS, String(jobNum));
        }
    }

756
    private async onTunerCommand(commandType: string, content: string): Promise<void> {
horizon365's avatar
horizon365 committed
757
        this.log.info(`NNIManager received command from dispatcher: ${commandType}, ${content}`);
758
        switch (commandType) {
chicm-ms's avatar
chicm-ms committed
759
            case INITIALIZED: {
chicm-ms's avatar
chicm-ms committed
760
                // Tuner is intialized, search space is set, request tuner to generate hyper parameters
761
762
763
764
765
766
                if (this.trialDataForTuner.length > 0) {
                    if (this.dispatcher === undefined) {
                        throw new Error('Dispatcher error: tuner has not been setup');
                    }
                    this.dispatcher.sendCommand(IMPORT_DATA, this.trialDataForTuner);
                }
chicm-ms's avatar
chicm-ms committed
767
768
                this.requestTrialJobs(this.experimentProfile.params.trialConcurrency);
                break;
chicm-ms's avatar
chicm-ms committed
769
770
            }
            case NEW_TRIAL_JOB: {
QuanluZhang's avatar
QuanluZhang committed
771
                if (this.status.status === 'TUNER_NO_MORE_TRIAL') {
772
                    this.log.warning('It is not supposed to receive more trials after NO_MORE_TRIAL is set');
chicm-ms's avatar
chicm-ms committed
773
                    this.setStatus('RUNNING');
774
                }
775
776
777
778
779
780
781
782
                const form: TrialJobApplicationForm = {
                    sequenceId: this.experimentProfile.nextSequenceId++,
                    hyperParameters: {
                        value: content,
                        index: 0
                    }
                };
                this.waitingTrials.push(form);
783
                break;
chicm-ms's avatar
chicm-ms committed
784
785
            }
            case SEND_TRIAL_JOB_PARAMETER: {
chicm-ms's avatar
chicm-ms committed
786
787
788
789
790
                const tunerCommand: any = JSON.parse(content);
                assert(tunerCommand.parameter_index >= 0);
                assert(tunerCommand.trial_job_id !== undefined);

                const trialJobForm: TrialJobApplicationForm = {
791
                    sequenceId: -1,  // FIXME: multi-phase tuner should use sequence ID instead of trial job ID
chicm-ms's avatar
chicm-ms committed
792
793
794
795
796
                    hyperParameters: {
                        value: content,
                        index: tunerCommand.parameter_index
                    }
                };
chicm-ms's avatar
chicm-ms committed
797
                this.log.info(`updateTrialJob: job id: ${tunerCommand.trial_job_id}, form: ${JSON.stringify(trialJobForm)}`);
chicm-ms's avatar
chicm-ms committed
798
                await this.trainingService.updateTrialJob(tunerCommand.trial_job_id, trialJobForm);
799
800
801
802
803
                if (tunerCommand['parameters'] !== null) {
                    // parameters field is set as empty string if no more hyper parameter can be generated by tuner.
                    await this.dataStore.storeTrialJobEvent(
                        'ADD_HYPERPARAMETER', tunerCommand.trial_job_id, content, undefined);
                }
chicm-ms's avatar
chicm-ms committed
804
                break;
chicm-ms's avatar
chicm-ms committed
805
806
            }
            case NO_MORE_TRIAL_JOBS: {
807
808
809
                if (!['ERROR', 'STOPPING', 'STOPPED'].includes(this.status.status)) {
                    this.setStatus('TUNER_NO_MORE_TRIAL');
                }
810
                break;
chicm-ms's avatar
chicm-ms committed
811
812
            }
            case KILL_TRIAL_JOB: {
chicm-ms's avatar
chicm-ms committed
813
                this.log.info(`cancelTrialJob: ${JSON.parse(content)}`);
QuanluZhang's avatar
QuanluZhang committed
814
                await this.trainingService.cancelTrialJob(JSON.parse(content), true);
815
                break;
chicm-ms's avatar
chicm-ms committed
816
            }
817
818
819
            default:
                throw new Error('Error: unsupported command type from tuner');
        }
Deshui Yu's avatar
Deshui Yu committed
820
821
    }

822
823
824
825
826
827
828
829
830
831
    private criticalError(err: Error): void {
        this.logError(err);
        console.error(err);
    }

    private logError(err: Error): void {
        if (err.stack !== undefined) {
            this.log.error(err.stack);
        }
        this.status.errors.push(err.message);
832
        this.setEndtime();
chicm-ms's avatar
chicm-ms committed
833
834
835
836
837
838
839
        this.setStatus('ERROR');
    }

    private setStatus(status: ExperimentStatus): void {
        if (status !== this.status.status) {
            this.log.info(`Change NNIManager status from: ${this.status.status} to: ${status}`);
            this.status.status = status;
840
            this.experimentManager.setExperimentInfo(this.experimentProfile.id, 'status', this.status.status);
chicm-ms's avatar
chicm-ms committed
841
        }
842
843
    }

844
845
846
847
848
    private setEndtime(): void {
        this.experimentProfile.endTime = Date.now();
        this.experimentManager.setExperimentInfo(this.experimentProfile.id, 'endTime', this.experimentProfile.endTime);
    }

849
850
851
852
853
    private createEmptyExperimentProfile(): ExperimentProfile {
        return {
            id: getExperimentId(),
            revision: 0,
            execDuration: 0,
854
            logDir: getExperimentRootDir(),
855
            nextSequenceId: 0,
856
857
858
859
860
861
            params: {
                authorName: '',
                experimentName: '',
                trialConcurrency: 0,
                maxExecDuration: 0, // unit: second
                maxTrialNum: 0, // maxTrialNum includes all the submitted trial jobs
862
                trainingServicePlatform: '',
QuanluZhang's avatar
QuanluZhang committed
863
                searchSpace: ''
864
865
            }
        };
Deshui Yu's avatar
Deshui Yu committed
866
    }
867

QuanluZhang's avatar
QuanluZhang committed
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
    private async createCheckpointDir(): Promise<string> {
        // TODO: test
        const chkpDir: string = getCheckpointDir();
        // create checkpoint directory
        await mkDirP(chkpDir);
        // assign this directory to exp profile's checkpointDir
        if (this.experimentProfile.params.advisor) {
            this.experimentProfile.params.advisor.checkpointDir = chkpDir;
        }
        if (this.experimentProfile.params.tuner) {
            this.experimentProfile.params.tuner.checkpointDir = chkpDir;
        }
        if (this.experimentProfile.params.assessor) {
            this.experimentProfile.params.assessor.checkpointDir = chkpDir;
        }

        return Promise.resolve(chkpDir);
    }
J-shang's avatar
J-shang committed
886
887
888
889
890
891
892
893

    public async getTrialOutputLocalPath(trialJobId: string): Promise<string> {
        return this.trainingService.getTrialOutputLocalPath(trialJobId);
    }

    public async fetchTrialOutput(trialJobId: string, subpath: string): Promise<void> {
        return this.trainingService.fetchTrialOutput(trialJobId, subpath);
    }
Deshui Yu's avatar
Deshui Yu committed
894
895
896
}

export { NNIManager };