Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor TrainKeras,TensorPlotter to use session in the controller. Closes #1938 #1941

Merged
merged 3 commits into from
Oct 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 84 additions & 3 deletions src/visualizers/panels/TensorPlotter/TensorPlotterControl.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,99 @@
/*globals define */
/**
* Generated by VisualizerGenerator 1.7.0 from webgme on Mon May 04 2020 17:09:31 GMT-0500 (Central Daylight Time).
*/

define([
'panels/InteractiveExplorer/InteractiveExplorerControl',
'text!./explorer_helpers.py',
], function (
InteractiveExplorerControl,
HELPERS_PY,
) {

'use strict';

class TensorPlotterControl extends InteractiveExplorerControl {

initializeWidgetHandlers (widget) {
super.initializeWidgetHandlers(widget);
widget.getPoints = lineInfo => this.getPoints(lineInfo);
widget.getColorValues = lineInfo => this.getColorValues(lineInfo);
widget.getMetadata = desc => this.getMetadata(desc);
}

async onComputeInitialized (session) {
super.onComputeInitialized(session);
this._widget.artifactLoader.session = session;
const initCode = await this.getInitializationCode();
await session.addFile('utils/init.py', initCode);
await session.addFile('utils/explorer_helpers.py', HELPERS_PY);
}

async getPoints (lineInfo) {
const {data, dataSlice=''} = lineInfo;
const {pyImport, varName} = this.getImportCode(data);
const command = [
'import utils.init',
pyImport,
'from utils.explorer_helpers import print_points',
`print_points(${varName}${dataSlice})`
].join('\n');
const stdout = await this.execPy(command);
return JSON.parse(stdout);
}

async getColorValues (lineInfo) {
const {colorData, colorDataSlice='', startColor, endColor} = lineInfo;
const {pyImport, varName} = this.getImportCode(colorData);
const command = [
'import utils.init',
pyImport,
'from utils.explorer_helpers import print_colors',
`data = ${varName}${colorDataSlice}`,
`print_colors(data, "${startColor}", "${endColor}")`
].join('\n');
const stdout = await this.execPy(command);
return JSON.parse(stdout);
}

async getMetadata (desc) {
const {name} = desc;
const {pyImport, varName} = this.getImportCode(name);
const command = [
'import utils.init',
pyImport,
'from utils.explorer_helpers import print_metadata',
`print_metadata("${varName}", ${varName})`,
].join('\n');
const stdout = await this.execPy(command);
return JSON.parse(stdout);
}

getImportCode (artifactName) {
const pyName = artifactName.replace(/\..*$/, '');
const [modName, ...accessors] = pyName.split('[');
const pyImport = `from artifacts.${modName} import data as ${modName}`;
const accessor = accessors.length ? '[' + accessors.join('[') : '';
const varName = modName + accessor;
return {
pyImport, varName
};
}

async execPy(code) {
try {
const i = ++this.cmdCount;
await this.session.addFile(`cmd_${i}.py`, code);
const {stdout} = await this.session.exec(`python cmd_${i}.py`);
await this.session.removeFile(`cmd_${i}.py`);
return stdout;
} catch (err) {
const {stderr} = err.jobResult;
const wrappedError = new Error(err.message);
wrappedError.stderr = stderr;
wrappedError.code = code;
throw wrappedError;
}
}

getObjectDescriptor(nodeId) {
const desc = super.getObjectDescriptor(nodeId);

Expand Down
135 changes: 129 additions & 6 deletions src/visualizers/panels/TrainKeras/TrainKerasControl.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,58 @@
define([
'panels/InteractiveExplorer/InteractiveExplorerControl',
'deepforge/globals',
'deepforge/PromiseEvents',
'deepforge/compute/interactive/message',
'deepforge/CodeGenerator',
'plugin/GenerateJob/GenerateJob/templates/index',
'text!./Main.py',
'text!./TrainOperation.py',
'deepforge/OperationCode',
'./JSONImporter',
'deepforge/Constants',
'js/Constants',
'q',
'underscore',
], function (
InteractiveExplorerControl,
DeepForge,
PromiseEvents,
Message,
CodeGenerator,
JobTemplates,
MainCode,
TrainOperation,
OperationCode,
Importer,
CONSTANTS,
GME_CONSTANTS,
Q,
_,
) {

'use strict';

MainCode = _.template(MainCode);
const GetTrainCode = _.template(TrainOperation);
class TrainKerasControl extends InteractiveExplorerControl {

constructor() {
super(...arguments);
this.modelCount = 0;
}

initializeWidgetHandlers (widget) {
super.initializeWidgetHandlers(widget);
const self = this;
widget.getArchitectureCode = id => this.getArchitectureCode(id);
widget.saveModel = function() {return self.saveModel(...arguments);};
widget.getNodeSnapshot = id => this.getNodeSnapshot(id);
widget.stopCurrentTask = () => this.stopTask(this.currentTrainTask);
widget.train = config => this.train(config);
widget.isTrainingModel = () => this.isTrainingModel();
widget.getCurrentModelID = () => this.getCurrentModelID();
widget.createModelInfo = config => this.createModelInfo(config);
widget.addArtifact = (dataset, auth) => this.addArtifact(dataset, auth);
}

async getNodeSnapshot(id) {
Expand All @@ -41,14 +66,112 @@ define([
return state;
}

async saveModel(modelInfo, storage, session) {
const metadata = (await session.forkAndRun(
async onComputeInitialized(session) {
super.onComputeInitialized(session);
const initCode = await this.getInitializationCode();
await session.addFile('utils/init.py', initCode);
await session.addFile('plotly_backend.py', JobTemplates.MATPLOTLIB_BACKEND);
await session.setEnvVar('MPLBACKEND', 'module://plotly_backend');
}

async stopTask(task) {
await this.session.kill(task);
}

async addArtifact(dataset, auth) {
await this.session.addArtifact(dataset.name, dataset.dataInfo, dataset.type, auth);
}

async createModelInfo(config) {
this.modelCount++;
const saveName = this.getCurrentModelID();
const architecture = await this.getNodeSnapshot(config.architecture.id);
return {
id: saveName,
path: saveName,
name: saveName,
config,
architecture
};
}

getCurrentModelID() {
return `model_${this.modelCount}`;
}

train(modelInfo) {
const self = this;
return PromiseEvents.new(async function(resolve) {
this.emit('update', 'Generating Code');
await self.initTrainingCode(modelInfo);
this.emit('update', 'Training...');
const trainTask = self.session.spawn('python start_train.py');
self.currentTrainTask = trainTask;
self.currentTrainTask.on(Message.STDOUT, data => {
let line = data.toString();
if (line.startsWith(CONSTANTS.START_CMD)) {
line = line.substring(CONSTANTS.START_CMD.length + 1);
const splitIndex = line.indexOf(' ');
const cmd = line.substring(0, splitIndex);
const content = JSON.parse(line.substring(splitIndex + 1));
if (cmd === 'PLOT') {
this.emit('plot', content);
} else {
console.error('Unrecognized command:', cmd);
}
}
});
let stderr = '';
self.currentTrainTask.on(Message.STDERR, data => stderr += data.toString());
self.currentTrainTask.on(Message.COMPLETE, exitCode => {
if (exitCode) {
this.emit('error', stderr);
} else {
this.emit('end');
}
if (self.currentTrainTask === trainTask) {
self.currentTrainTask = null;
}
resolve();
});
});
}

async initTrainingCode(modelInfo) {
const {config} = modelInfo;
const {dataset, architecture, path, loss, optimizer} = config;
const archCode = await this.getArchitectureCode(architecture.id);
loss.arguments.concat(optimizer.arguments).forEach(arg => {
let pyValue = arg.value.toString();
if (arg.type === 'boolean') {
pyValue = arg.value ? 'True' : 'False';
} else if (arg.type === 'enum') {
pyValue = `"${arg.value}"`;
}
arg.pyValue = pyValue;
});
await this.session.addFile('start_train.py', MainCode({
dataset,
path,
archCode
}));
const trainPy = GetTrainCode(config);
await this.session.addFile('operations/train.py', trainPy);
}

isTrainingModel() {
return !!this.currentTrainTask;
}

async saveModel(modelInfo, storage) {
modelInfo.code = GetTrainCode(modelInfo.config);
const metadata = (await this.session.forkAndRun(
session => session.exec(`cat outputs/${modelInfo.path}/metadata.json`)
)).stdout;
const {type} = JSON.parse(metadata);
const projectId = this.client.getProjectInfo()._id;
const savePath = `${projectId}/artifacts/${modelInfo.name}`;
const dataInfo = await session.forkAndRun(
const dataInfo = await this.session.forkAndRun(
session => session.saveArtifact(
`outputs/${modelInfo.path}/data`,
savePath,
Expand Down Expand Up @@ -239,13 +362,13 @@ define([
.forEach(event => {
switch (event.etype) {

case CONSTANTS.TERRITORY_EVENT_LOAD:
case GME_CONSTANTS.TERRITORY_EVENT_LOAD:
this.onResourceLoad(event.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UPDATE:
case GME_CONSTANTS.TERRITORY_EVENT_UPDATE:
this.onResourceUpdate(event.eid);
break;
case CONSTANTS.TERRITORY_EVENT_UNLOAD:
case GME_CONSTANTS.TERRITORY_EVENT_UNLOAD:
this.onResourceUnload(event.eid);
break;
default:
Expand Down
Loading