Comparar commits

..

6 Commits

Autor SHA1 Mensagem Data
Brian Broll 708ef3f48a WIP Minor changes for GenArch 2016-11-26 14:26:07 -06:00
Brian Broll 4b14c74733 WIP Changed code content to use python 2016-11-26 12:11:14 -06:00
Brian Broll cf6e6dd4e5 WIP Updated code editors to use python for comments and content 2016-11-26 12:10:22 -06:00
Brian Broll 88a57a5af9 WIP Fixed the boolean values to use True/False 2016-11-26 11:42:30 -06:00
Brian Broll d30d990330 WIP Updated nn-parser and nn for pytorch layers 2016-11-26 11:12:02 -06:00
Brian Broll 96720c3140 WIP Added some basic layer parsing support
name, baseType, defaults, and types (for the defaults). Still need
to verify named args work though (and more of the types work)...
2016-11-25 16:22:53 -06:00
148 arquivos alterados com 2123 adições e 12471 exclusões
-1
Ver Arquivo
@@ -1 +0,0 @@
/node_modules
-3
Ver Arquivo
@@ -35,6 +35,3 @@ test-tmp/
blob-local-storage/
src/seeds/nn/hash.txt
src/seeds/pipeline/hash.txt
notes/
src/worker
-3
Ver Arquivo
@@ -38,6 +38,3 @@ src/seeds/pipeline/hash.txt
# docs
images/
notes/
src/worker
-24
Ver Arquivo
@@ -1,24 +0,0 @@
# Dockerfile for running the server itself
FROM node:6.10.1
MAINTAINER Brian Broll <brian.broll@gmail.com>
RUN echo '{"allow_root": true}' > /root/.bowerrc && mkdir -p /root/.config/configstore/ && \
echo '{}' > /root/.config/configstore/bower-github.json
RUN mkdir /deepforge
ADD . /deepforge
WORKDIR /deepforge
RUN cd $(npm root -g)/npm \
&& npm install fs-extra \
&& sed -i -e s/graceful-fs/fs-extra/ -e s/fs.rename/fs.move/ ./lib/utils/rename.js
RUN ln -s /deepforge/bin/deepforge /usr/local/bin
EXPOSE 8888
# Set up the data storage
RUN deepforge config blob.dir /data/blob && \
deepforge config mongo.dir /data/db
CMD ["deepforge", "start", "--server"]
-65
Ver Arquivo
@@ -1,65 +0,0 @@
# This has torch and cuda support
FROM kaixhin/cuda-torch
MAINTAINER Brian Broll <brian.broll@gmail.com>
# install nodejs v6
RUN groupadd --gid 1000 node \
&& useradd --uid 1000 --gid node --shell /bin/bash --create-home node
# gpg keys listed at https://github.com/nodejs/node#release-team
RUN set -ex \
&& for key in \
9554F04D7259F04124DE6B476D5A82AC7E37093B \
94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \
FD3A5288F042B6850C66B31F09FE44734EB7990E \
71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \
DD8F2338BAE7501E3DD5AC78C273792F7D83545D \
B9AE9905FFD7803F25714661B63B535A4C206CA9 \
C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \
56730D5401028683275BD23C23EFEFE93C4CFFFE \
; do \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key"; \
done
ENV NPM_CONFIG_LOGLEVEL info
ENV NODE_VERSION 6.10.1
RUN curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.xz" \
&& curl -SLO "https://nodejs.org/dist/v$NODE_VERSION/SHASUMS256.txt.asc" \
&& gpg --batch --decrypt --output SHASUMS256.txt SHASUMS256.txt.asc \
&& grep " node-v$NODE_VERSION-linux-x64.tar.xz\$" SHASUMS256.txt | sha256sum -c - \
&& tar -xJf "node-v$NODE_VERSION-linux-x64.tar.xz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-x64.tar.xz" SHASUMS256.txt.asc SHASUMS256.txt \
&& ln -s /usr/local/bin/node /usr/local/bin/nodejs
# install deepforge
RUN echo '{"allow_root": true}' > /root/.bowerrc && mkdir -p /root/.config/configstore/ && \
echo '{}' > /root/.config/configstore/bower-github.json
RUN mkdir /deepforge
ADD . /deepforge
WORKDIR /deepforge
RUN cd $(npm root -g)/npm \
&& npm install fs-extra \
&& sed -i -e s/graceful-fs/fs-extra/ -e s/fs.rename/fs.move/ ./lib/utils/rename.js
RUN ln -s /deepforge/bin/deepforge /usr/local/bin
# configure the worker
RUN deepforge config blob.dir /data/blob && \
deepforge config mongo.dir /data/db && \
deepforge config worker.cache.useBlob false && \
deepforge config worker.cache.dir /deepforge/worker-cache && \
deepforge config torch.dir /root/torch/ && \
git config --global user.email "deepforge-worker@deepforge.org" && \
git config --global user.name "deepforge-worker"
# Update torch
RUN apt-get update && apt-get install sudo wget && \
. /root/torch/install/bin/torch-activate && \
cd /root/torch/ && bash /root/torch/update.sh && \
deepforge update -t
ENTRYPOINT ["deepforge", "start", "--worker"]
CMD ["http://172.17.0.1:8888"]
+18 -22
Ver Arquivo
@@ -1,10 +1,11 @@
[![Release State](https://img.shields.io/badge/state-beta-yellow.svg)](https://img.shields.io/badge/state-beta-yellow.svg)
[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](./LICENSE)
[![Build Status](https://travis-ci.org/deepforge-dev/deepforge.svg?branch=master)](https://travis-ci.org/deepforge-dev/deepforge)
[![Join the chat at https://gitter.im/deepforge-dev/deepforge](https://badges.gitter.im/deepforge-dev/deepforge.svg)](https://gitter.im/deepforge-dev/deepforge?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Stories in Ready](https://badge.waffle.io/deepforge-dev/deepforge.png?label=ready&title=Ready)](https://waffle.io/deepforge-dev/deepforge)
[![Build Status](https://travis-ci.org/dfst/deepforge.svg?branch=master)](https://travis-ci.org/dfst/deepforge)
[![Join the chat at https://gitter.im/dfst/deepforge](https://badges.gitter.im/dfst/deepforge.svg)](https://gitter.im/dfst/deepforge?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Stories in Ready](https://badge.waffle.io/dfst/deepforge.png?label=ready&title=Ready)](https://waffle.io/dfst/deepforge)
**Notice**: DeepForge is still a work in progress and in beta! That being said, any contributions and/or feedback is greatly appreciated. If you have any questions, check out the [wiki](https://github.com/dfst/deepforge/wiki/) or drop me a line on the gitter!
Using DeepForge? [Let us know what you think!](https://goo.gl/forms/2pDdCPXoUvkQhVzQ2)
# DeepForge
DeepForge is an open-source visual development environment for deep learning providing end-to-end support for creating deep learning models. This is achieved through providing the ability to design **architectures**, create training **pipelines**, and then execute these pipelines over a cluster. Using a notebook-esque api, users can get real-time feedback about the status of any of their **executions** including compare them side-by-side in real-time.
@@ -21,30 +22,25 @@ Additional features include:
- Facilitates defining custom layers
## Quick Start
The easiest way to start deepforge is using [docker-compose](https://docs.docker.com/compose/). Using docker-compose, deepforge can be started with
Simply run the following command to install deepforge with its dependencies:
```
wget https://raw.githubusercontent.com/deepforge-dev/deepforge/master/docker-compose.yml
docker-compose up
curl -o- https://raw.githubusercontent.com/dfst/deepforge/master/install.sh | bash
```
Finally, navigate to [http://localhost:8888](http://localhost:8888) to start using DeepForge! For more detailed instructions and other installation options, check out the [docs](http://deepforge.readthedocs.io/en/latest/deployment/overview.html).
Or, if you already have NodeJS (v6) installed, simply run
## Additional Resources
- [Intro to DeepForge Slides](https://docs.google.com/presentation/d/10_y5O3gHXSATfjHVLJg7dOdrz-tAXNWjlxhJ5SlA0ic/edit?usp=sharing)
- [wiki](https://github.com/deepforge-dev/deepforge/wiki) containing overview, installation, configuration and developer information
- [Starter Kit](https://github.com/deepforge-dev/examples/tree/master/starterkit) containing example pipelines demonstrating various deepforge features
- [Examples](https://github.com/deepforge-dev/examples)
```
npm install -g deepforge
```
- [Datamodel Developer Slides](https://docs.google.com/presentation/d/1hd3IyUlzW_TIPnzCnE-1pdz00Pw8WaIxYiOW_Hyog-M/edit#slide=id.p)
Finally, start deepforge with `deepforge start`and navigate to [http://localhost:8888](http://localhost:8888) to start using DeepForge! For more, detailed instructions, check out the [wiki](https://github.com/dfst/deepforge/wiki/Installation-Guide).
**Note**: running deepforge w/ `deepforge start` will also require [MongoDB](https://www.mongodb.com/download-center?jmp=nav#community) to be installed locally.
Also, be sure to check out the other available features of the `deepforge` cli; it can be used to update, manage your torch installation, uninstall deepforge and run individual components!
## Interested in contributing?
Contributions are welcome! There are a couple different ways to contribute to DeepForge:
- Provide user feedback!
- on the [documentation](http://deepforge.readthedocs.io)
- on deepforge and its future development: https://goo.gl/forms/2pDdCPXoUvkQhVzQ2
- Contribute to the project directly by submitting some PR's!
If you have any questions, check out the [wiki](https://github.com/dfst/deepforge/wiki/) or drop me a line on the gitter!
Contributions are welcome! Either fork the project and submit some PR's or shoot me an email about getting more involved!
Sponsored by [Digital Reasoning](http://www.digitalreasoning.com/)
-1
Ver Arquivo
@@ -1 +0,0 @@
theme: jekyll-theme-cayman
+53 -87
Ver Arquivo
@@ -1,7 +1,6 @@
#!/usr/bin/env node
var Command = require('commander').Command,
tcpPortUsed = require('tcp-port-used'),
program = new Command(),
childProcess = require('child_process'),
rawSpawn = childProcess.spawn,
@@ -9,8 +8,7 @@ var Command = require('commander').Command,
execSync = childProcess.execSync,
path = require('path'),
fs = require('fs'),
pkgJson = require('../package.json'),
version = pkgJson.version,
version = require('../package.json').version,
exists = require('exists-file'),
DEFAULT_CONFIG = require('./config.json'),
merge = require('lodash.merge'),
@@ -119,35 +117,32 @@ var isLocalUri = function(protocol, uri) {
uri.indexOf(protocol + '://127.0.0.1') === 0;
};
var checkMongo = function(args, notSilent, mongoUri) {
var checkMongo = function(args, notSilent) {
// check the webgme config
var gmeConfig = require('../config');
mongoUri = mongoUri || gmeConfig.mongo.uri;
var gmeConfig = require('../config'),
mongoUri = gmeConfig.mongo.uri;
if (isLocalUri('mongodb', mongoUri)) {
var match = mongoUri.match(/:([0-9]+)/),
port = '80';
if (match) {
port = match[1];
}
// Make sure mongo is running locally (using pgrep)
try {
execSync('pgrep mongod').toString();
console.log('MongoDB is already running!');
} catch (e) { // no pIds
console.log('Starting MongoDB...');
var match = mongoUri.match(/:([0-9]+)/),
port = '80';
if (match) {
port = match[1];
}
startMongo(args, port, !notSilent);
}
return tcpPortUsed.waitUntilUsed(+port, 100, 1000);
} else if (notSilent) {
console.log(`Cannot start remote mongo locally: ${mongoUri}`);
} else {
console.log(`Using remote mongo: ${mongoUri}`);
}
return Q();
};
var startMongo = function(args, port, silent) {
@@ -213,34 +208,28 @@ var installTorch = function() {
args = `clone https://github.com/torch/distro.git ${tgtDir} --recursive`.split(' ');
return spawn('git', args)
.catch(result => {
var error = result.error || result.stderr ||
`Torch install failed with exit code ${result.code}`;
.then(code => {
if (code !== 0) {
if (code === 128) {
console.error(`${tgtDir} is not empty. ` +
'Please empty it or change the torch directory:\n' +
'\n deepforge config torch.dir NEW/TORCH/PATH\n');
if (result.stderr.includes('unable to access')) {
error = `Could not access the torch repository. Are you ` +
`connected to the internet?\n`;
} else if (result.code === 128) {
error = `${tgtDir} is not empty. ` +
'Please empty it or change the torch directory:\n' +
'\n deepforge config torch.dir NEW/TORCH/PATH\n';
}
throw `Torch install Failed with exit code ${code}`;
} else { // continue installation
process.chdir(tgtDir);
return spawn('bash', ['install-deps'])
.then(() => spawn('bash', ['install.sh'], true))
.then(() => {
storeConfig('torch.dir', tgtDir);
console.log('Installed torch. Please close and ' +
're-open your terminal to use DeepForge w/ ' +
'torch support!');
process.exit(0);
});
}
console.error(error);
process.exit(result.code);
})
.then((code, stderr) => {
process.chdir(tgtDir);
return spawn('bash', ['install-deps'])
.then(() => spawn('bash', ['install.sh'], true))
.then(() => {
storeConfig('torch.dir', tgtDir);
console.log('Installed torch. Please close and ' +
're-open your terminal to use DeepForge w/ ' +
'torch support!');
process.exit(0);
});
});
} else {
return Q();
@@ -253,32 +242,21 @@ var spawn = function(cmd, args, opts) {
spawnOpts = typeof opts === 'object' ? opts : null,
forwardStdin = opts === true,
isOpen = true,
stderr = '',
err;
args = args || [];
job = spawnOpts ? rawSpawn(cmd, args, spawnOpts) : rawSpawn(cmd, args);
job.stdout.on('data', data => process.stdout.write(data));
job.stderr.on('data', data => {
stderr += data;
process.stderr.write(data);
});
job.stderr.on('data', data => process.stderr.write(data));
job.on('close', code => {
isOpen = false;
if (err || code !== 0) {
deferred.reject({
code: code,
stderr: stderr,
error: err
});
if (err) {
deferred.reject(err, code);
} else {
deferred.resolve(code);
}
});
job.on('error', e => {
err = e;
});
job.on('error', e => err = e);
if (forwardStdin) {
process.stdin.on('data', data => {
@@ -298,49 +276,42 @@ program.command('start')
.option('-w, --worker [url]', 'start a worker and connect to given url. Defaults to local deepforge')
.option('-m, --mongo', 'start MongoDB')
.action(args => {
var main = path.join(__dirname, 'start-local.js'),
current = Q();
var main = path.join(__dirname, 'start-local.js');
if (args.port) {
process.env.PORT = args.port;
}
if (args.mongo) {
current = current.then(() => checkMongo(args, true));
}
if (args.server) {
current = current
.then(() => checkMongo(args))
.then(() => {
main = path.join(__dirname, '..', 'app.js');
return spawn('node', [main]);
});
checkMongo(args);
main = path.join(__dirname, '..', 'app.js');
spawn('node', [main]);
}
if (args.worker) {
if (hasTorch()) {
current
.then(() => installTorchExtras())
.then(() => {
main = path.join(__dirname, 'start-worker.js');
if (args.worker !== true) {
spawn('node', [main, args.worker]);
} else {
spawn('node', [main]);
}
});
installTorchExtras().then(() => {
main = path.join(__dirname, 'start-worker.js');
if (args.worker !== true) {
spawn('node', [main, args.worker]);
} else {
spawn('node', [main]);
}
});
} else {
installTorch();
}
}
if (args.mongo) {
checkMongo(args, true);
}
if (!args.server && !args.worker && !args.mongo) {
// Starting everything
current = current.then(() => checkMongo(args));
checkMongo(args);
if (hasTorch()) {
current.then(() => installTorchExtras())
.then(() => spawn('node', [main]));
installTorchExtras().then(() => spawn('node', [main]));
} else {
installTorch();
}
@@ -363,7 +334,7 @@ program
if (!args.torch || args.server) {
if (args.git) {
pkg = pkgJson.repository.url;
pkg = 'dfst/deepforge';
} else {
// Check the version
try {
@@ -476,17 +447,12 @@ program
}
});
// extensions
program
.command('extensions <command>', 'Manage deepforge extensions');
module.exports = function(cmd) {
var cmds = cmd.split(/\s+/).filter(w => !!w);
cmds.unshift('./bin/deepforge');
cmds.unshift('node');
program.parse(cmds);
};
module.exports.checkMongo = checkMongo;
if (require.main === module) {
program.parse(process.argv);
-67
Ver Arquivo
@@ -1,67 +0,0 @@
#!/usr/bin/env node
var Command = require('commander').Command,
program = new Command(),
extender = require('../utils/extender');
// Supported commands
// - add
// - remove
// - list
// - update
program
.command('add <project>')
.description('Add an extension to deepforge')
.option('-n, --name <name>', 'Project name (if different from <project>)')
.action(project => {
console.log('loading extension from: ' + project);
extender.install(project)
.then(extConfig =>
console.log(`The ${extConfig.name} extension has been added to deepforge.`))
.fail(err => {
console.error('Could not install extension:\n');
console.error(err);
process.exit(1);
});
});
program
.command('remove <name>').alias('rm')
.description('Remove an extension from deepforge')
.action(name => {
try {
extender.uninstall(name);
console.log(`${name} has been successfully removed!`);
} catch (e) {
console.error('Could not remove extension:');
console.error(e);
process.exit(1);
}
});
program
.command('list').alias('ls')
.description('List installed deepforge extensions')
.action(() => {
var allExtConfigs = extender.getExtensionsConfig(),
types = Object.keys(allExtConfigs),
hasContents = false,
names;
for (var i = types.length; i--;) {
names = Object.keys(allExtConfigs[types[i]]);
if (names.length) {
hasContents = true;
console.log(types[i]);
for (var j = names.length; j--;) {
console.log(` ${names[j]}`);
}
}
}
if (!hasContents) {
console.log('No installed extensions');
}
});
program.parse(process.argv);
+2 -2
Ver Arquivo
@@ -13,8 +13,8 @@ if (gmeConfig.blob.type === 'FS') {
}
process.env.NODE_ENV = 'local';
execJob = spawn('node', [
path.join(__dirname, '..', 'app.js')
execJob = spawn('npm', [
'start'
], env);
execJob.stdout.pipe(process.stdout);
execJob.stderr.pipe(process.stderr);
+15 -6
Ver Arquivo
@@ -6,7 +6,8 @@ var path = require('path'),
spawn = childProcess.spawn,
rm_rf = require('rimraf'),
projectConfig = require(__dirname + '/../config'),
executorSrc = path.join(__dirname, '..', 'node_modules', '.bin', 'webgme-executor-worker'),
executorSrc = path.join(__dirname, '..', 'node_modules', 'webgme', 'src',
'server', 'middleware', 'executor', 'worker'),
id = Date.now(),
workerRootPath = process.env.DEEPFORGE_WORKER_DIR || path.join(__dirname, '..', 'src', 'worker'),
workerPath = path.join(workerRootPath, `worker_${id}`),
@@ -36,6 +37,7 @@ try {
} catch (e) {
// Create dir
childProcess.spawnSync('ln', ['-s', `${__dirname}/../node_modules`, modules]);
return true;
}
// Check torch support
@@ -58,7 +60,7 @@ var startExecutor = function() {
// Start the executor
var execJob = spawn('node', [
executorSrc,
'node_worker.js',
workerConfigPath,
workerTmp
]);
@@ -72,13 +74,20 @@ var createConfigJson = function() {
if (process.argv.length > 2) {
address = process.argv[2];
if (!/^https?:\/\//.test(address)) {
address = 'http://' + address;
}
}
config[address] = {};
fs.writeFile(workerConfigPath, JSON.stringify(config), startExecutor);
};
fs.mkdir(workerTmp, createConfigJson);
process.chdir(executorSrc);
fs.mkdir(workerTmp, function() {
// npm install in this directory
var npmInstall = spawn('npm', ['install']);
npmInstall.stdout.pipe(process.stdout);
npmInstall.stderr.pipe(process.stderr);
npmInstall.on('close', function() {
createConfigJson();
});
});
+4
Ver Arquivo
@@ -48,6 +48,10 @@
"ImportTorch": {
"icon": "import_export",
"priority": -1
},
"GenerateExecFile": {
"icon": "play_for_work",
"priority": -1
}
}
},
-1
Ver Arquivo
@@ -8,7 +8,6 @@ require('dotenv').load({silent: true});
// Add/overwrite any additional settings here
config.server.port = +process.env.PORT || config.server.port;
config.server.timeout = 0;
config.mongo.uri = process.env.MONGO_URI || config.mongo.uri;
config.blob.fsDir = process.env.DEEPFORGE_BLOB_DIR || config.blob.fsDir;
-22
Ver Arquivo
@@ -1,22 +0,0 @@
---
services:
mongo:
image: mongo
volumes:
- "$HOME/.deepforge/data:/data/db"
server:
environment:
- "MONGO_URI=mongodb://mongo:27017/deepforge"
image: deepforge/server
ports:
- "8888:8888"
volumes:
- "$HOME/.deepforge/blob:/data/blob"
depends_on:
- mongo
worker:
command: "http://server:8888"
image: deepforge/worker
depends_on:
- server
version: "2"
-1
Ver Arquivo
@@ -1 +0,0 @@
_build
-20
Ver Arquivo
@@ -1,20 +0,0 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = deepforge
SOURCEDIR = .
BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
-159
Ver Arquivo
@@ -1,159 +0,0 @@
import sphinx_rtd_theme
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# deepforge documentation build configuration file, created by
# sphinx-quickstart on Mon Mar 13 18:56:27 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'DeepForge'
copyright = '2017, Brian Broll'
author = 'Brian Broll'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ''
# The full version, including alpha/beta/rc tags.
release = ''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# -- Options for HTMLHelp output ------------------------------------------
# Output file base name for HTML help builder.
htmlhelp_basename = 'deepforgedoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'deepforge.tex', 'deepforge Documentation',
'Brian Broll', 'manual'),
]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'deepforge', 'deepforge Documentation',
[author], 1)
]
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'deepforge', 'deepforge Documentation',
author, 'deepforge', 'One line description of project.',
'Miscellaneous'),
]
-45
Ver Arquivo
@@ -1,45 +0,0 @@
Dockerized Installation
-----------------------
Each of the components are also available as docker containers. This page outlines the running of each of the main components as docker containers and connecting them as necessary.
Database
~~~~~~~~
First, you can start the mongo container using:
.. code-block:: bash
docker run -d -v /abs/path/to/data:/data/db mongo
where :code:`/abs/path/to/data` is the path to the mongo data location on the host. If running the database in a container, you will need to get the ip address of the given container:
.. code-block:: bash
docker inspect <container id> | grep IPAddr
The :code:`<container id>` is the value returned from the original :code:`docker run` command.
When running mongo in a docker container, it is important to mount an external volume (using the :code:`-v` flag) to be used for the actual data (otherwise the data will be lost when the container is stopped).
Server
~~~~~~
The DeepForge server can be started with
.. code-block:: bash
docker run -d -v $HOME/.deepforge/blob:/data/blob \
-p 8888:8888 -e MONGO_URI=mongodb://172.17.0.2:27017/deepforge \
deepforge/server
where :code:`172.17.0.2` is the ip address of the mongo container and :code:`$HOME/.deepforge/blob` is the path to use for binary DeepForge data on the host. Of course, if the mongo instance is locating at a different location, :code:`MONGO_URI` can be set to this address as well. Also, the first port (:code:`8888`) can be replaced with the desired port to expose on the host.
Worker
~~~~~~
As workers may require GPU access, they will need to use the nvidia-docker plugin. Workers can be created using
.. code-block:: bash
nvidia-docker run -d deepforge/worker http://172.17.0.1:8888
where :code:`http://172.17.0.1:8888` is the location of the DeepForge server to which to connect.
**Note**: The :code:`deepforge/worker` image is packaged with cuda 7.5. Depending upon your hardware and nvidia version, you may need to build your own docker image or run the worker natively.
-130
Ver Arquivo
@@ -1,130 +0,0 @@
Native Installation
===================
Dependencies
------------
First, install `NodeJS <https://nodejs.org/en/>`_ (v6) and `MongoDB <https://www.mongodb.org/>`_. You may also need to install git if you haven't already.
Next, you can install DeepForge using npm:
.. code-block:: bash
npm install -g deepforge
Now, you can check that it installed correctly:
.. code-block:: bash
deepforge --version
DeepForge can now be started with:
.. code-block:: bash
deepforge start
However, the first time DeepForge is started, it will make sure that the deep learning framework is installed (if it isn't found on the host system). This may require you to start DeepForge a couple times; the first time it starts it will install Torch7 and require a terminal restart to update a couple environment variables (like `PATH`). The second time it starts it will install additional torch packages but will not require a terminal restart. Finally, DeepForge will start with all the required dependencies.
Database
~~~~~~~~
Download and install MongoDB from the `website <https://www.mongodb.org/>`_. If you are planning on running MongoDB locally on the same machine as DeepForge, simply start `mongod` and continue to setting up DeepForge.
If you are planning on running MongoDB remotely, set the environment variable "MONGO_URI" to the URI of the Mongo instance that DeepForge will be using:
.. code-block:: bash
MONGO_URI="mongodb://pathToMyMongo.com:27017/myCollection" deepforge start
Server
~~~~~~
The DeepForge server is included with the deepforge cli and can be started simply with
.. code-block:: bash
deepforge start --server
By default, DeepForge will start on `http://localhost:8888`. However, the port can be specified with the `--port` option. For example:
.. code-block:: bash
deepforge start --server --port 3000
Worker
~~~~~~
The DeepForge worker can be started with
.. code-block:: bash
deepforge start --worker
The worker will install dependencies the first time it is run (including torch, if it is not already installed).
To connect to a remote deepforge instance, add the url of the DeepForge server:
.. code-block:: bash
deepforge start --worker http://myaddress.com:1234
Updating
~~~~~~~~
DeepForge can be updated with the command line interface rather simply:
.. code-block:: bash
deepforge update
By default, this will update both DeepForge and the local torch installation. To only update DeepForge, add the `--server` flag:
.. code-block:: bash
deepforge update --server
For more update options, check out `deepforge update --help`!
Manual Installation (Development)
---------------------------------
Installing DeepForge for development is essentially cloning the repository and then using `npm` (node package manager) to run the various start, test, etc, commands (including starting the individual components). The deepforge cli can still be used but must be referenced from `./bin/deepforge`. That is, `deepforge start` becomes `./bin/deepforge start` (from the project root).
DeepForge Server
~~~~~~~~~~~~~~~~
First, clone the repository:
.. code-block:: bash
git clone https://github.com/dfst/deepforge.git
Then install the project dependencies:
.. code-block:: bash
npm install
To run all components locally start with
.. code-block:: bash
./bin/deepforge start
and navigate to `http://localhost:8888` to start using DeepForge!
Alternatively, if jobs are going to be executed on an external worker, run `./bin/deepforge start -s` locally and navigate to `http://localhost:8888`.
DeepForge Worker
~~~~~~~~~~~~~~~~
If you are using `./bin/deepforge start -s` you will need to set up a DeepForge worker (`./bin/deepforge start` starts a local worker for you!). DeepForge workers are slave machines connected to DeepForge which execute the provided jobs. This allows the jobs to access the GPU, etc, and provides a number of benefits over trying to perform deep learning tasks in the browser.
Once DeepForge is installed on the worker, start it with
.. code-block:: bash
./bin/deepforge start -w
Note: If you are running the worker on a different machine, put the address of the DeepForge server as an argument to the command. For example:
.. code-block:: bash
./bin/deepforge start -w http://myaddress.com:1234
Updating
~~~~~~~~
Updating can be done the same as any other git project; that is, by running `git pull` from the project root. Sometimes, the dependencies need to be updated so it is recommended to run `npm install` following `git pull`.
-26
Ver Arquivo
@@ -1,26 +0,0 @@
Overview
========
DeepForge Component Overview
----------------------------
DeepForge is composed of four main elements:
- *Server*: Main component hosting all the project information and is connected to by the clients
- *Database*: MongoDB database containing DeepForge, job queue for the workers, etc
- *Worker*: Slave machine performing the actual machine learning computation
- *Client*: The connected browsers working on DeepForge projects.
Of course, only the *Server*, *Database* (MongoDB) and *Worker* need to be installed. If you are not going to execute any machine learning pipelines, installing the *Worker* can be skipped.
Component Dependencies
----------------------
The following dependencies are required for each component:
- *Server* (NodeJS v6.2.1)
- *Database* (MongoDB v3.0.7)
- *Worker*: NodeJS v6.2.1 (used for job management logic) and `Torch <http://torch.ch/docs/getting-started.html#>`_ (this will be installed automatically by the cli when needed)
- *Client*: We recommend using Google Chrome and are not supporting other browsers (for now). In other words, other browsers can be used at your own risk.
Configuration
-------------
After installing DeepForge, it can be helpful to check out `configuring DeepForge <getting_started/configuration.rst>`_
Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 37 KiB

-13
Ver Arquivo
@@ -1,13 +0,0 @@
Custom Data Types
=================
As operation inputs and outputs are strongly typed, DeepForge supports the creation of custom data types to promote flexibility when designing complex pipelines and operations. DeepForge data types can be either primitive types or custom classes. Custom DeepForge primitive types are relatively straight-forward; they can inherit from other types and must implement a serialization and deserialization methods (which may be as simple as :code:`torch.save` and :code:`torch.load`). Custom classes are also relatively simple to define but actually contain their own methods along with serialization and deserialization functions.
New data types can be defined from the operation editor from the dialog for selecting input or output data for the operation. After defining a new class, this class is available from within any of the operations in the DeepForge project.
.. figure:: model_data_editor.png
:align: center
:scale: 55 %
Editing the serialization and deserialization for the "model" type
-87
Ver Arquivo
@@ -1,87 +0,0 @@
Custom Layers
=============
DeepForge supports the creation of custom neural network layers using Torch7 and the easy usage of these layers in the visual architecture editor. Before creating custom layers, it is recommended to read about `creating custom layers in Torch7 <http://torch.ch/docs/developer-docs.html>`_.
A new custom layer can be created from the "add layer dialog" in the architecture editor. When creating a layer, DeepForge provides a code editor for creating custom neural network layers prepopulated with a basic template for defining the custom layer.
After defining the layer in the layer editor, DeepForge will provide this layer in the architecture editor and expose any configurable attributes for the layer. These attributes are parsed from the layer definition.
Best Practices
--------------
Here are a couple best practices to keep in mind when defining custom neural network layers:
- Use type assertions for layer, boolean attributes
- Return :code:`self` when defining setter functions
**Type assertions** should be used when defining layer attributes (ie, constructor arguments or arguments to a setter function). For example, consider the following layer definition for :code:`RecurrentAttention` which accepts an :code:`action` layer argument to its constructor.
.. code-block:: lua
local RecurrentAttention, parent = torch.class("nn.RecurrentAttention", "nn.AbstractSequencer")
function RecurrentAttention:__init(rnn, action, nStep, hiddenSize)
parent.__init(self)
assert(torch.isTypeOf(action, 'nn.Module'))
assert(torch.type(nStep) == 'number')
assert(torch.type(hiddenSize) == 'table')
assert(torch.type(hiddenSize[1]) == 'number', "Does not support table hidden layers" )
self.rnn = rnn
-- we can decorate the module with a Recursor to make it AbstractRecurrent
self.rnn = (not torch.isTypeOf(rnn, 'nn.AbstractRecurrent')) and nn.Recursor(rnn) or rnn
-- samples an x,y actions for each example
self.action = (not torch.isTypeOf(action, 'nn.AbstractRecurrent')) and nn.Recursor(action) or action
self.hiddenSize = hiddenSize
self.nStep = nStep
self.modules = {self.rnn, self.action}
self.output = {} -- rnn output
self.actions = {} -- action output
self.forwardActions = false
self.gradHidden = {}
end
In this example, :code:`assert(torch.isTypeOf(action, 'nn.Module'))` enforces that the :code:`action` variable is another neural network layer. After defining the layer, DeepForge will parse the layer definition and create a visual representation for use in the architecture editor. As this assertion enforces that :code:`action` is a neural network layer, DeepForge will update itself accordingly; in this case, editing the attribute will allow the user to hierarchically create nested neural network architectures to be passed as the :code:`action` argument to the constructor.
.. figure:: recurrent_attention.png
:align: center
:scale: 85 %
RecurrentAttention has attributes for each of the constructor arguments
An example of the generated visual model for the :code:`RecurrentAttention` is provided above. This layer has attributes for each of the constructor arguments defined in its definition. Clicking on the :code:`<none>` value for the :code:`action` attribute will then allow the user to provide layer inputs as shown below.
.. figure:: action_layer.png
:align: center
:scale: 55 %
Creating layer inputs for the "action" variable
The second best practice is to make sure to **return self in any setter functions**. An example of this can be found in the setters in the :code:`SpatialMaxPooling` layer shown below:
.. code-block:: lua
function SpatialMaxPooling:ceil()
self.ceil_mode = true
return self
end
function SpatialMaxPooling:floor()
self.ceil_mode = false
return self
end
Returning :code:`self` in setter functions is a good convention when defining neural network layers in Torch7 as it promotes simple and legible code such as
.. code-block:: lua
net:add(nn.SpatialMaxPooling(5, 5, 2, 2):ceil())
where :code:`net` is a container like a :code:`Sequential` layer. DeepForge enforces this convention and, if it finds a setter function (which also returns :code:`self`) in the layer definition will expose the internal variable (in this case :code:`ceil_mode`) to the user in the visual editor.
-69
Ver Arquivo
@@ -1,69 +0,0 @@
Custom Operations
=================
In this document we will outline the basics of custom operations including the operation editor and operation feedback utilities.
The Basics
----------
Operations are used in pipelines and have named, typed inputs and outputs. When creating a pipeline, if you don't currently find an operation for the given task, you can easily create your own by selecting the `New Operation...` operation from the add operation dialog. This will create a new operation definition and open it in the operation editor. The operation editor has two main parts, the interface editor and the implementation editor.
.. figure:: operation_editor.png
:align: center
:scale: 45 %
Editing the "train" operation provided in the "First Steps" section
The interface editor is provided on the left and presents the interface as a diagram showing the input data and output data as objects flowing into or out of the given operation. Selecting the operation node in the operation interface editor will expand the node and allow the user to add or edit attributes for the given operation. These attributes are exposed when using this operation in a pipeline and can be set at design time - that is, these are set when creating the given pipeline. The interface diagram may also contain light blue nodes flowing into the operation. These nodes represent "references" that the operation accepts as input before running. When using the operation, references will appear alongside the attributes but will allow the user to select from a list of all possible targets when clicked.
.. figure:: operation_interface.png
:align: center
:scale: 85 %
The train operation accepts training data, an architecture and criterion and returns a trained model
On the right of the operation editor is the implementation editor. The implementation editor is a code editor specially tailored for programming the implementations of operations in DeepForge. This includes some autocomplete support for common globals in this context like the :code:`deepforge` and :code:`torch` globals. It also is synchronized with the interface editor and will provide input to the interface editor about unused variables, etc. These errors will present themselves as error or warning highlights on the data in the interface editor. A section of the implementation is shown below:
.. code:: lua
trainer = nn.StochasticGradient(net, criterion)
trainer.learningRate = attributes.learningRate
trainer.maxIteration = attributes.maxIterations
print('training for ' .. tostring(attributes.maxIterations) .. ' iterations (max)')
print('learning rate is ' .. tostring(attributes.learningRate))
print(trainer)
-- Adding the error graph
graph = deepforge.Graph('Training Error') -- creating graph feedback
errLine = graph:line('error')
trainer.hookIteration = function(t, iter, currentErr)
errLine:add(iter, currentErr) -- reporting the current error (will update in real time in DeepForge)
end
trainer:train(trainset)
return {
net = net
}
The "train" operation uses the :code:`StochasticGradient` functionality from the :code:`nn` package to perform stochastic gradient descent. This operation sets all the parameters using values provided to the operation as either attributes or references. In the implementation, attributes are provided by the :code:`attributes` variable and provides access to the user defined attributes from within the implementation. References are treated similarly to operation inputs and are defined in variables of the same name. This can be seen with the :code:`net` and :code:`criterion` variables in the first line. Finally, operations return a table of their named outputs; in this example, it returns a single output named :code:`net`, that is, the trained neural network.
After defining the interface and implementation, we can now use the "train" operation in our pipelines! An example is shown below.
.. figure:: train_operation.png
:align: center
:scale: 85 %
Using the custom "train" operation in a pipeline
Operation feedback
------------------
Operations in DeepForge can generate metadata about its execution. This metadata is generated during the execution and provided back to the user in real-time. An example of this includes providing real-time plotting feedback of the loss function of a model while training. When implementing an operation in DeepForge, this metadata can be created using the :code:`deepforge` global.
.. figure:: graph_example.png
:align: center
:scale: 75 %
An example graph of the loss function while training a neural network
Detailed information about the available operation metadata types can be found in the `reference <reference/feedback_mechanisms.rst>`_.
Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 39 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 51 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 108 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 16 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 8.8 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 12 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 35 KiB

-32
Ver Arquivo
@@ -1,32 +0,0 @@
Getting Started
===============
.. _Torch: http://torch.ch
What is DeepForge?
------------------
Deep learning is a very promising, yet complex, area of machine learning. This complexity can both create a barrier to entry for those wanting to get involved in deep learning as well as slow the development of those already comfortable in deep learning.
DeepForge is a development environment for deep learning focused on alleviating these problems. Leveraging the flexibility of Torch_, DeepForge is able to reduce the complexity of using deep learning while still providing advanced features such as defining custom layers.
Design Goals
------------
As mentioned above, DeepForge focuses on two main goals:
1. **Improving the efficiency** of experienced data scientists/researchers in deep learning
2. **Lowering the barrier to entry** for newcomers to deep learning
It is important to highlight that although one of the goals is focused on lowering the barrier to entry, DeepForge is intended to be more than simply an educational tool; that is, it is important not to compromise on flexibility and effectiveness as a research/industry tool in order to provide an easier experience for beginners (that's what forks are for!).
Overview and Features
---------------------
DeepForge provides a collaborative, distributed development environment for deep learning. The development environment is a hybrid visual and textual programming environment. Higher levels of abstraction, such as creating architectures, use visual environments to capture the overall structure of the task while lower levels of abstraction, such as defining custom layers, utilize text environments to maintain the flexibility provided by torch.
Concepts and Terminology
~~~~~~~~~~~~~~~~~~~~~~~~
- *Architecture* - neural network architecture composed of torch defined layers
- *Operation* - essentially a function written in torch (such as `SGD`)
- *Pipeline* - directed acyclic graph composed of operations
- eg, a training pipeline may retrieve and normalize data, train an architecture and return the trained model
- *Execution* - when a pipeline is run, an "execution" is created and reports the status of each operation as it is run (distributed over a number of worker machines)
- *Artifact* - an artifact represents some data (either user uploaded or created during an execution)
-63
Ver Arquivo
@@ -1,63 +0,0 @@
First Steps
===========
DeepForge provides an example project for creating a classifier using the `CIFAR10 <https://www.kaggle.com/c/cifar-10>`_ dataset.
When first opening DeepForge in your browser (at `http://localhost:8888` if following the instructions from the `quick start <getting_started/installation.rst>`_), you will be prompted with a list of projects to open and provided the option to create a new project. For this example, let's click "Create new..." and name our project "hello_cifar".
.. figure:: create_project.png
:align: center
:scale: 65 %
Creating our "hello_cifar" example project
Clicking "Create" will bring us to a prompt for the "seed" for our project. Select "cifar10" from the dropdown and click "Create". This will now create our new project based on the cifar10 example provided with DeepForge.
.. figure:: set_seed.png
:align: center
:scale: 75 %
Selecting the "cifar10" example seed
In this example, we have three main pipelines: :code:`download-normalize`, :code:`train` and :code:`test`. :code:`download-normalize` downloads and prepares our data. The :code:`train` pipeline trains a neural network model on the cifar10 dataset and the :code:`test` pipeline tests our trained model on our test set from the cifar10 dataset.
.. figure:: pipelines.png
:align: center
:scale: 65 %
Three main pipelines in the cifar10 example project
First, we will have to retrieve and prepare the data by running the :code:`download-normalize` pipeline. This can be done by opening the given pipeline then selecting the `Execute Pipeline` option from the action button in the lower right. As soon as that pipeline finishes, we can now use this data to train a neural network.
Next, we can open the :code:`train` pipeline. Before we execute the pipeline we have to set the input training data that we will be using. This is done by selecting the :code:`Input` operation then clicking the value for the :code:`artifact` field. This will provide all the possible options for the input data; for this example, we will want to select the "trainingdata" artifact. After setting the input, we can click on the :code:`train` operation to inspect the hyperparameters we are using and the architecture we are training. Selecting the :code:`Output` operation will allow you to change the name of the resulting artifact of this operation (in this case, a trained model). Finally, we can execute this pipeline like before to train the model.
.. figure:: select_train_data.png
:align: center
:scale: 65 %
Selecting the training data for the input to the training pipeline
As this operation trains, we can view the status by viewing the running execution. The easiest way to view the running execution is by clicking the given execution from the execution tray in the bottom left when viewing the originating pipeline.
.. figure:: training_execution.png
:align: center
:scale: 65 %
Viewing the execution of the training pipeline
Once the model has been trained, we can test the given model using the :code:`test` pipeline. In this pipeline, we have a few more inputs to set: "testing data", "model to test" and the "human-readable class labels". If you aren't clear which operation provides which input, you can simply hover over it's connected port on the :code:`test` operation. This will provide a tooltip with the full name of the input.
.. figure:: test_pipeline.png
:align: center
:scale: 65 %
Viewing the execution of the testing pipeline
After setting the inputs for the :code:`test` pipeline (using the trained model and data from the first two pipelines), we can simply execute this pipeline to test our model. After executing the :code:`test` pipeline, we can view the execution and open the :code:`test` job to view the stdout for the given job. In the :code:`test` operation, this will allow us to view the printed accuracies of the model over each class.
.. figure:: test_results.png
:align: center
:scale: 65 %
Viewing the results of the testing operation
And that's it! We have just trained and tested our first neural network model using DeepForge. Although there are still a lot more advanced features that can be used, this should at least familiarize us with some of the core concepts in DeepForge.
Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 47 KiB

-19
Ver Arquivo
@@ -1,19 +0,0 @@
Quick Start
===========
The easiest way to get started quickly with DeepForge is using docker-compose. First, install `docker <https://docs.docker.com/engine/installation/>`_ and `docker-compose <https://docs.docker.com/compose/install/>`_.
Next, download the docker-compose file for DeepForge:
.. code-block:: bash
wget https://raw.githubusercontent.com/deepforge-dev/deepforge/master/docker-compose.yml
Then start DeepForge using docker-compose:
.. code-block:: bash
docker-compose up
and now DeepForge can be used by opening a browser to `http://localhost:8888 <http://localhost:8888>`_!
For detailed instructions about deployment installations, check out our `deployment installation instructions <getting_started/configuration.rst>`_
Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 6.7 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 17 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 44 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 55 KiB

Arquivo binário não exibido.

Antes

Largura:  |  Altura:  |  Tamanho: 46 KiB

-40
Ver Arquivo
@@ -1,40 +0,0 @@
.. DeepForge documentation master file, created by
sphinx-quickstart on Mon Mar 13 18:56:27 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to DeepForge's documentation!
=====================================
.. toctree::
:maxdepth: 1
:caption: Getting Started
getting_started/getting_started.rst
getting_started/quick_start.rst
getting_started/hello_cifar.rst
.. toctree::
:maxdepth: 1
:caption: Fundamentals
fundamentals/custom_operations.rst
fundamentals/custom_layers.rst
fundamentals/custom_data_types.rst
.. toctree::
:maxdepth: 1
:caption: Deployment
deployment/overview.rst
deployment/native.rst
deployment/dockerized.rst
.. toctree::
:maxdepth: 1
:caption: Reference
reference/cli.rst
reference/configuration.rst
reference/operation_feedback.rst
reference/extensions.rst
-91
Ver Arquivo
@@ -1,91 +0,0 @@
Command Line Interface
======================
This document outlines the functionality of the deepforge command line interface (provided after installing deepforge with :code:`npm install -g deepforge`).
- Installation Configuration
- Starting DeepForge or Components
- Installing and Upgrading Torch
- Update or Uninstall DeepForge
- Managing Extensions
Installation Configuration
--------------------------
Installation configuration including the installation location of Torch7 and data storage locations. These can be edited using the :code:`deepforge config` command as shown in the following examples:
Printing all the configuration settings:
.. code-block:: bash
deepforge config
Printing the value of a configuration setting:
.. code-block:: bash
deepforge config torch.dir
Setting a configuration option, such as :code:`torch.dir` can be done with:
.. code-block:: bash
deepforge config torch.dir /some/new/directory
For more information about the configuration settings, check out the `configuration <configuration.rst>`_ page.
Starting DeepForge Components
-----------------------------
DeepForge components, such as the server or the workers, can be started with the :code:`deepforge start` command. By default, this command will start all the necessary components to run including the server, a mongo database (if applicable) and a worker.
The server can be started by itself using
.. code-block:: bash
deepforge start --server
The worker can be started by itself using
.. code-block:: bash
deepforge start --worker http://154.95.87.1:7543
where `http://154.95.87.1:7543` is the url of the deepforge server.
Installing and Upgrading Torch7
-------------------------------
Torch7 is lazily installed when starting a worker (if torch isn't already installed) with the rnn package. This installation can be manually updated as described in the update and installation section.
Update/Uninstall DeepForge
--------------------------
DeepForge can be updated or uninstalled using
.. code-block:: bash
deepforge update
The torch installation can be updated using
.. code-block:: bash
deepforge update --torch
DeepForge can be uninstalled using :code:`deepforge uninstall`
Managing Extensions
-------------------
DeepForge extensions can be installed and removed using the :code:`deepforge extensions` subcommand. Extensions can be added, removed and listed as shown below
.. code-block:: bash
deepforge extensions add https://github.com/example/some-extension
deepforge extensions remove some-extension
deepforge extensions list
-77
Ver Arquivo
@@ -1,77 +0,0 @@
Configuration
=============
Configuration of deepforge is done through the `deepforge config` command from the command line interface. To see all config options, simply run `deepforge config` with no additional arguments. This will print a JSON representation of the configuration settings similar to:
.. code-block:: bash
Current config:
{
"torch": {
"dir": "/home/irishninja/.deepforge/torch"
},
"blob": {
"dir": "/home/irishninja/.deepforge/blob"
},
"worker": {
"cache": {
"useBlob": true,
"dir": "~/.deepforge/worker/cache"
},
"dir": "~/.deepforge/worker"
},
"mongo": {
"dir": "~/.deepforge/data"
}
}
Setting an attribute, say `worker.cache.dir`, is done as follows
.. code-block:: bash
deepforge config worker.cache.dir /tmp
Environment Variables
---------------------
Most settings have a corresponding environment variable which can be used to override the value set in the cli's configuration. This allows the values to be temporarily set for a single run. For example, starting a worker with a different cache than set in `worker.cache.dir` can be done with:
.. code-block:: bash
DEEPFORGE_WORKER_CACHE=/tmp deepforge start -w
The complete list of the environment variable overrides for the configuration options can be found `here <https://github.com/deepforge-dev/deepforge/blob/master/bin/envConfig.json>`_.
Settings
--------
torch.dir
~~~~~~~~~
The path to the local installation of torch to be used by the deepforge worker. This is used when installing, upgrading and removing the local torch installation
blob.dir
~~~~~~~~
The path to the blob (large file storage containing models, datasets, etc) to be used by the deepforge server.
This can be overridden with the `DEEPFORGE_BLOB_DIR` environment variable.
worker.dir
~~~~~~~~~~
The path to the directory used for worker executions. The workers will run the executions from this directory.
This can be overridden with the `DEEPFORGE_WORKER_DIR` environment variable.
mongo.dir
~~~~~~~~~
The path to use for the `--dbpath` option of mongo if starting mongo using the command line interface. That is, if the MONGO_URI is set to a local uri and the cli is starting the deepforge server, the cli will check to verify that an instance of mongo is running locally. If not, it will start it on the given port and use this setting for the `--dbpath` setting of mongod.
worker.cache.dir
~~~~~~~~~~~~~~~~
The path to the worker cache directory.
This can be overridden with the `DEEPFORGE_WORKER_CACHE` environment variable.
worker.cache.useBlob
~~~~~~~~~~~~~~~~~~~~
When running the worker on the same machine as the server, this allows the worker to use the blob as a cache and simply create symbolic links to the data (eg, training data, models) to prevent having to even perform a copy of the data on the given machine.
This can be overridden with the `DEEPFORGE_WORKER_USE_BLOB` environment variable.
-53
Ver Arquivo
@@ -1,53 +0,0 @@
Operation Feedback
==================
DeepForge provides the `deepforge` global object in operation implementations for providing feedback during the execution. The various types of metadata are provided and discussed below.
Graphs
------
Real-time graphs can be created using the graph constructor:
.. code-block:: lua
local graph = deepforge.Graph('My Graph') -- created a new graph called "My Graph"
After creating a graph, lines can be added similarly.
.. code-block:: lua
local line1 = graph:line('first line') -- created a new line called "first line"
local line2 = graph:line('second line') -- created a second line called "second line"
Finally, points can be added to the lines by calling the `:add` method on the line and passing the x and y values for the given point.
.. code-block:: lua
line1:add(1, 3) -- adding point (1, 3) to line1
line2:add(1, 4) -- adding point (1, 4) to line2
line1:add(2, 5) -- adding point (2, 5) to line1
line2:add(2, 6) -- adding point (2, 6) to line2
Graphs can then label their axis as follows:
.. code-block:: lua
graph:xlabel('x axis') -- label the x axis "x axis"
graph:ylabel('y axis') -- label the y axis "y axis"
Images
------
Images can be created using:
.. code-block:: lua
local image = deepforge.Image('My Example Image', imageTensor)
The first argument is the title of the image and the second argument is the tensor for the image (optional). Both the title and the tensor can be updated during execution as follows.
.. code-block:: lua
image:title('My New Title') -- updating the image title
image:update(newTensor) -- updating the displayed image
-4626
Ver Arquivo
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
+7 -15
Ver Arquivo
@@ -1,48 +1,40 @@
{
"name": "deepforge",
"repository": {
"type": "git",
"url": "https://github.com/deepforge-dev/deepforge.git"
},
"bin": {
"deepforge": "./bin/deepforge"
},
"scripts": {
"start": "./bin/deepforge start",
"postinstall": "node utils/reinstall-extensions.js",
"start": "node app.js",
"start-dev": "NODE_ENV=dev node app.js",
"local": "node ./bin/start-local.js",
"worker": "node ./bin/start-worker.js",
"test": "mkdir ./test-tmp; mocha --recursive test",
"watch-test": "nodemon --exec 'mocha --recursive test'",
"test": "mkdir ./test-tmp; node ./node_modules/mocha/bin/mocha --recursive test",
"watch-test": "./node_modules/nodemon/bin/nodemon.js --exec 'node ./node_modules/mocha/bin/mocha --recursive test'",
"build-nn": "node ./utils/nn-parser.js"
},
"version": "1.4.1",
"version": "0.19.0",
"dependencies": {
"commander": "^2.9.0",
"dotenv": "^2.0.0",
"exists-file": "^2.1.0",
"express": "^4.14.0",
"graceful-fs": "^4.1.10",
"lodash.difference": "^4.1.2",
"graceful-fs": "^4.1.10",
"lodash.merge": "^4.5.1",
"lodash.template": "^4.4.0",
"mongodb": "^2.2.10",
"nodemon": "^1.9.2",
"npm": "^4.0.5",
"q": "1.4.1",
"rimraf": "^2.4.0",
"tcp-port-used": "^0.1.2",
"webgme": "^2.7.1",
"webgme": "^2.6.0",
"webgme-autoviz": "^2.2.0",
"webgme-breadcrumbheader": "^2.1.1",
"webgme-chflayout": "^2.0.0",
"webgme-easydag": "dfst/webgme-easydag",
"webgme-executor-worker": "^1.0.1",
"webgme-fab": "dfst/webgme-fab",
"webgme-simple-nodes": "^2.1.0"
},
"devDependencies": {
"brython": "^3.2.7",
"chai": "^3.0.0",
"jszip": "^2.5.0",
"mocha": "^2.2.5",
-5
Ver Arquivo
@@ -15,7 +15,6 @@
CONTAINED_LAYER_INDEX: 'index',
LINE_OFFSET: 'lineOffset',
DISPLAY_COLOR: 'displayColor',
// DeepForge metadata creation in dist execution
START_CMD: 'deepforge-cmd',
@@ -31,10 +30,6 @@
GRAPH_CREATE: 'GRAPH',
GRAPH_PLOT: 'PLOT',
GRAPH_CREATE_LINE: 'LINE',
GRAPH_LABEL_AXIS: {
X: 'X',
Y: 'Y'
},
// Code Generation Constants
CTOR_ARGS_ATTR: 'ctor_arg_order',
+97 -348
Ver Arquivo
@@ -1,378 +1,127 @@
/* globals define*/
(function(root, factory){
if(typeof define === 'function' && define.amd) {
define(['./lua'], function(luajs){
return (root.LayerParser = factory(luajs));
// TODO: Load the brython script
define(['./lua'], function(brython){
return (root.LayerParser = factory(brython, console.assert));
});
} else if(typeof module === 'object' && module.exports) {
var luajs = require('./lua');
module.exports = (root.LayerParser = factory(luajs));
var brython = require('./node-brython'),
assert = require('assert');
module.exports = (root.LayerParser = factory(brython, assert));
}
}(this, function(luajs) {
}(this, function(brython, assert) {
var LayerParser = {};
//////////////////////// Setters ////////////////////////
var returnsSelf = function(fnNode){
var stats = fnNode.block.stats,
last = stats[stats.length-1];
function build_ast(src) {
brython.$py_module_path['__main__']='./'
return brython.py2js(src,'__main__', '__main__', '__builtins__')
}
if (last.type === 'stat.return') {
return last.nret[0].type === 'variable' && last.nret[0].val === 'self';
}
return false;
};
var isAttrSetter = function(node){
if (node.type === 'stat.assignment' && node.lefts.length === 1) {
var left = node.lefts[0];
return left.type === 'expr.index' && left.self.val === 'self';
}
return false;
};
var getSettingAttrName = function(node){
if (isAttrSetter(node)) {
var left = node.lefts[0];
return left.key.val;
}
return null;
};
var getSettingAttrValue = function(node){
if (isAttrSetter(node)) {
return node.right;
}
return null;
};
var isSetterMethod = function(curr, parent, className){
if (parent && parent.type === 'stat.method') {
// is it a fn w/ two statements (stats)
if (parent.self.val === className && curr.type === 'function' &&
curr.block.stats.length === 2) {
// Is the first statement setting a value?
return returnsSelf(curr) && getSettingAttrName(curr.block.stats[0]); // does it return itself?
// The provided tree gives us contexts which can have associated 'C'
function traverse(node, fn) {
var i;
if (node.children) {
for (i = node.children.length; i--;) {
traverse(node.children[i], fn);
fn(node.children[i]);
}
}
return false;
};
var isFnArg = function(method, name) {
return method.args.indexOf(name) !== -1;
};
var getSetterSchema = function(node, method) {
var setterType,
setterFn,
value = getSettingAttrValue(node);
if (value[0].type === 'variable' && isFnArg(method.func, value[0].val)) {
setterType = 'arg';
setterFn = method.key.val;
} else {
setterType = 'const';
setterFn = {};
setterFn[value[0].val] = method.key.val;
}
return {
setterType,
setterFn
};
};
//////////////////////// Setters END ////////////////////////
var isInitFn = function(node, className) {
if (node.type === 'stat.method' && node.self.val === className) {
return node.key.val === '__init';
}
return false;
};
var getClassAttrDefs = function(method) {
var fn = method.func,
dict = {},
attr,
right,
value;
luajs.codegen.traverse(curr => {
if (isAttrSetter(curr)) {
// Store the value if it is set to a constant
attr = curr.lefts[0].key.val;
right = curr.right[0];
if (right.type.indexOf('const.') !== -1) {
value = right.val;
if (right.type === 'const.nil') {
value = null;
}
dict[attr] = value;
}
}
})(fn);
return dict;
};
var getAttrsAndVals = function(method) {
// Given a method, get the 'self' attributes and the default values
var fn = method.func,
dict = {},
varName,
value,
varUsageCnt = {};
// Get the variables that are used only once (or updating themselves)
luajs.codegen.traverse(curr => {
if (curr.type === 'variable') {
varUsageCnt[curr.val] = varUsageCnt[curr.val] ?
varUsageCnt[curr.val] + 1 : 1;
}
})(method);
luajs.codegen.traverse(curr => {
// If the variable is only used once and is 'or'-ed w/ a constant
// during this use, we can infer that this is the default value
if (curr.type === 'expr.op' && curr.op === 'op.or' &&
curr.left.type === 'variable' && curr.right.type.indexOf('const') !== -1) {
varName = curr.left.val;
if (varUsageCnt[varName] === 1) {
value = curr.right.type === 'const.nil' ? null : curr.right;
dict[varName] = value;
}
}
})(fn);
return dict;
};
var copyNodeValues = function(attrs, from, to) {
var value;
for (var i = attrs.length; i--;) {
value = from[attrs[i]] || null;
if (value) {
value = (value && value.hasOwnProperty('val')) ? value.val : value;
to[attrs[i]] = value;
if (node.C && node.C.tree) {
for (i = node.C.tree.length; i--;) {
traverse(node.C.tree[i], fn);
fn(node.C.tree[i]);
}
}
return to;
};
}
var getTypeCheckInfo = function(cond) {
var caller,
method,
target,
expType;
var types = {},
layers = [],
pCtx,
classNode,
params;
// Check for torch.isTypeOf:
if (cond.type === 'expr.call' && cond.func.type === 'expr.index') {
caller = cond.func.self.val;
method = cond.func.key.val;
function isClass(node) {
return node.type === 'class';
}
if (cond.type === 'expr.call' && caller === 'torch') {
target = cond.args[0].val;
if (method === 'isTypeOf' && target) {
expType = cond.args[1].val;
return {
target,
type: expType
};
}
}
} else if (cond.type === 'expr.op') { // torch.type() === ''
// Check right side, too!
var sides = [cond.left, cond.right],
side,
otherSide;
function isInitFn(node) {
return node.type === 'def' && node.name === '__init__';
}
for (var i = sides.length; i--;) {
side = sides[i];
otherSide = sides[(i+1)%2];
if (side.type === 'expr.call' && side.func.type === 'expr.index') {
// Is it torch?
caller = side.func.self.val;
method = side.func.key.val;
if (caller === 'torch' && method === 'type') {
if (side.args[0].type === 'variable') {
target = side.args[0].val;
if (otherSide.type === 'const.string') {
expType = otherSide.val;
function getBaseClass(node) {
assert(node.type === 'class');
return node.args.tree[0].tree[0].tree[0].value;
}
return {
target: target,
type: expType
};
function findTorchLayers(root) {
var defaults = {},
layers = [],
defTypes,
args,
def;
traverse(root, node => {
// Get the class for the given function
if (isInitFn(node)) {
// TODO: What if there is no constructor? Is this a potential problem?
pCtx = node.parent.node.parent;
classNode = pCtx.C.tree[0];
if (isClass(classNode)) {
// remove the 'self' variable
// TODO: May need to update this for kwargs
// (use positional_list)
args = node.tree[1].tree;
defaults = {};
params = node.args.slice(1);
defTypes = {};
for (var i = args.length; i--;) {
if (args[i].tree[0]) {
def = args[i].tree[0].tree[0];
if (def.type === 'int') {
defaults[params[i-1]] = parseInt.apply(null, def.value.reverse());
} else {
defaults[params[i-1]] = def.value;
}
if (/^(True|False)$/.test(defaults[params[i-1]])) {
defTypes[params[i-1]] = 'boolean';
} else {
defTypes[params[i-1]] = def.type;
}
}
}
layers.push({
name: classNode.name,
baseType: getBaseClass(classNode),
//doc: classNode.doc_string || '',
defaults: defaults,
types: defTypes,
setters: {},
params: params
});
}
}
return null;
}
};
var isError = function(stat) {
var fn;
if (stat.type === 'stat.expr' && stat.expr.type === 'expr.call') {
fn = stat.expr.func.val;
return fn === 'error';
}
return false;
};
var inferParamTypes = function(node, paramDefs) {
var types = {},
check,
cond;
// Infer from assertions
luajs.codegen.traverse(curr => {
// check for 'assert's that check type
if (curr.type === 'expr.call' && curr.func.val === 'assert') {
cond = curr.args[0];
check = getTypeCheckInfo(cond);
if (check) {
types[check.target] = check.type;
}
} else if (curr.type === 'stat.if' && curr.cond.op === 'uop.not') {
// if statements throwing errors on type mismatch
cond = curr.cond.operand; // non-negated version
// Check that it throws an error on true
if (curr.tblock.stats.some(isError)) {
check = getTypeCheckInfo(cond);
if (check) {
types[check.target] = check.type;
}
}
}
})(node);
// Infer from defaults
Object.keys(paramDefs).forEach(param => {
var val = paramDefs[param];
if (val) { // initialized to 'null' doesn't help us...
types[param] = val.type.replace('const.', '');
}
});
return types;
};
return layers;
}
var findTorchClass = function(ast){
var torchClassArgs, // args for `torch.class(...)`
name = '',
alias,
baseType,
params,
setters = {},
defaults = {},
paramDefs,
attrDefs;
if(ast.type == 'function'){
ast.block.stats.forEach(function(func){
if(func.type == 'stat.local' && func.right && func.right[0] &&
func.right[0].func && func.right[0].func.self &&
func.right[0].func.self.val == 'torch' &&
func.right[0].func.key.val == 'class'){
torchClassArgs = func.right[0].args.map(arg => arg.val);
name = torchClassArgs[0];
if(name !== ''){
name = name.replace('nn.', '');
alias = func.names[0] || name;
if (torchClassArgs.length > 1) {
baseType = torchClassArgs[1].replace('nn.', '');
}
}
}
});
}
// Get the setters, defaults and type info (inferred)
var setterNames,
schema,
types,
values;
luajs.codegen.traverse((curr, parent) => {
var firstLine,
attrName;
// Record the setter functions
if (isSetterMethod(curr, parent, alias)) {
firstLine = curr.block.stats[0];
// just use the attribute attrName for now...
attrName = getSettingAttrName(firstLine);
// merge schemas
schema = getSetterSchema(firstLine, parent);
if (setters[attrName] && setters[attrName].setterType === 'const') { // merge
for (var val in schema.setterFn) {
setters[attrName].setterFn[val] = schema.setterFn[val];
}
} else {
setters[attrName] = schema;
}
} else if (isInitFn(curr, alias)) { // Record the defaults
paramDefs = getAttrsAndVals(curr);
attrDefs = getClassAttrDefs(curr);
types = inferParamTypes(curr, paramDefs);
// get ctor args
params = curr.func.args;
if(params.length === 0 && curr.func.varargs){
params.push('params');
}
}
})(ast);
// Get the defaults for the params from defs
if (paramDefs && params) {
copyNodeValues(params, paramDefs, defaults);
}
// Get the defaults for the setters from attrDefs
if (attrDefs) {
setterNames = Object.keys(setters);
copyNodeValues(setterNames, attrDefs, defaults);
}
// Remove any const setters w/ only one value and no default
setterNames = Object.keys(setters);
for (var i = setterNames.length; i--;) {
schema = setters[setterNames[i]];
if (schema.setterType === 'const') {
values = Object.keys(schema.setterFn);
if (values.length === 1 &&
// boolean setters can have the default value inferred
values[0] !== 'true' && values[0] !== 'false' &&
!defaults[setterNames[i]]) {
delete setters[setterNames[i]];
}
}
}
return {
name,
baseType,
params,
setters,
types,
defaults
};
};
LayerParser.parse = function(text) {
// Try to find the class definitions...
//
// Need to create:
//
// setters: (I don't think these are used in pytorch!
// types:
// type:
//////////////////////// Setters ////////////////////////
LayerParser.parse = function(src) {
try {
var ast = luajs.parser.parse(text);
return findTorchClass(ast);
brython.$py_module_path['__main__']='./';
var ast = brython.py2js(src,'__main__', '__main__', '__builtins__');
var layers = findTorchLayers(ast);
return layers;
} catch (e) {
return null;
}
+7 -12
Ver Arquivo
@@ -83,9 +83,7 @@ define([
exists = {},
i = 2;
children
.filter(child => child !== null)
.forEach(child => exists[child.getAttribute('name')] = true);
children.forEach(child => exists[child.getAttribute('name')] = true);
while (exists[name]) {
name = basename + '_' + i;
@@ -193,7 +191,7 @@ define([
.getId();
// Look up the parent container
return DeepForge.places[placeName]().then(parentId => {
DeepForge.places[placeName]().then(parentId => {
client.startTransaction(msg);
newId = createNamedNode(baseId, parentId, !!metasheetName);
@@ -271,8 +269,10 @@ define([
.filter(n => !n.getRegistry('isAbstract'))
.map(node => node.getAttribute('name'));
// Add the target type to the pluginMetadata...
var metadata = WebGMEGlobal.allPluginsMetadata[UPLOAD_PLUGIN],
//this.logger.info(`Found ${dataTypes.length} data types`);
// Add the target type to the pluginMetadata... hacky :/
var metadata = WebGMEGlobal.allPluginsMetadata[UPLOAD_PLUGIN],
config = metadata.configStructure
.find(opt => opt.name === DATA_TYPE_CONFIG.name);
@@ -297,8 +297,7 @@ define([
};
DeepForge.last = {};
DeepForge.create = {};
DeepForge.register = {};
DeepForge.create = {};
instances.forEach(type => {
DeepForge.create[type] = function() {
return createNew.call(null, type);
@@ -309,10 +308,6 @@ define([
DeepForge.create[type] = function() {
return createNew.call(null, type, type);
};
DeepForge.register[type] = function(id) {
// Add the given element to the metasheet!
return addToMetaSheet(id, type);
};
});
DeepForge.create.Layer = createCustomLayer;
+1 -1
Ver Arquivo
@@ -2565,7 +2565,7 @@ function LuaContext(){
case 'number':
return c;
case 'string':
return parseInt(c) || dummy0;
return parseInt(s) || dummy0;
default:
if (c == dummy0){
return c;
+176
Ver Arquivo
@@ -0,0 +1,176 @@
/*
Author: Billy Earney
Date: 04/19/2013
License: MIT
Description: This file can work as a "bridge" between nodejs and brython
so that client side brython code can be executed on the server side.
Will brython replace Cython one day? Only time will tell.
:)
*/
var fs = require('fs'),
path = require('path'),
brythonSrcPath = path.join(__dirname, '..', '..', 'node_modules', 'brython', 'www', 'src', 'brython.js');
document={};
document.getElementsByTagName = () => [{src: ''}];
window={};
window.location = {href: ''};
window.navigator={}
window.confirm = () => true;
window.console = console;
document.$py_src = {}
document.$debug = 0
self={};
__BRYTHON__={}
__BRYTHON__.$py_module_path = {}
__BRYTHON__.$py_module_alias = {}
__BRYTHON__.$py_next_hash = -Math.pow(2,53)
__BRYTHON__.exception_stack = []
__BRYTHON__.scope = {}
__BRYTHON__.modules = {}
// Read and eval library
jscode = fs.readFileSync(brythonSrcPath, 'utf8');
eval(jscode);
//function node_import(module,alias,names) {
function $import_single(module) {
var search_path=['../src/libs', '../src/Lib'];
var ext=['.js', '.py'];
var mods=[module, module+'/__init__'];
for(var i=0, _len_i = search_path.length; i < _len_i; i++) {
for (var j=0, _len_j = ext.length; j < _len_j; j++) {
for (var k=0, _len_k = mods.length; k < _len_k; k++) {
var path=search_path[i]+'/'+mods[k]+ext[j]
//console.log("searching for " + path);
var module_contents;
try {
module_contents=fs.readFileSync(path, 'utf8')
} catch(err) {}
if (module_contents !== undefined) {
console.log("imported " + module)
//console.log(module_contents);
if (ext[j] == '.js') {
return $import_js_module(module,alias,names,path,module_contents)
}
return $import_py_module(module,alias,names,path,module_contents)
}
}
}
}
console.log("error time!");
res = Error()
res.name = 'NotFoundError'
res.message = "No module named '"+module+"'"
throw res
}
$compile_python=function(module_contents,module) {
var root = __BRYTHON__.py2js(module_contents,module)
var body = root.children
root.children = []
// use the module pattern : module name returns the results of an anonymous function
var mod_node = new $Node('expression')
//if(names!==undefined){alias='$module'}
new $NodeJSCtx(mod_node,'$module=(function()')
root.insert(0,mod_node)
mod_node.children = body
// search for module-level names : functions, classes and variables
var mod_names = []
for(var i=0, _len_i = mod_node.children.length; i < _len_i;i++){
var node = mod_node.children[i]
// use function get_ctx()
// because attribute 'context' is renamed by make_dist...
var ctx = node.get_ctx().tree[0]
if(ctx.type==='def'||ctx.type==='class'){
if(mod_names.indexOf(ctx.name)===-1){mod_names.push(ctx.name)}
} else if(ctx.type==='from') {
for (var j=0, _len_j = ctx.names.length; j < _len_j; j++) {
var name=ctx.names[j];
if (name === '*') {
// just pass, we don't want to include '*'
} else if (ctx.aliases[name] !== undefined) {
if (mod_names.indexOf(ctx.aliases[name])===-1){
mod_names.push(ctx.aliases[name])
}
} else {
if (mod_names.indexOf(ctx.names[j])===-1){
mod_names.push(ctx.names[j])
}
}
}
}else if(ctx.type==='assign'){
var left = ctx.tree[0]
if(left.type==='expr'&&left.tree[0].type==='id'&&left.tree[0].tree.length===0){
var id_name = left.tree[0].value
if(mod_names.indexOf(id_name)===-1){mod_names.push(id_name)}
}
}
}
// create the object that will be returned when the anonymous function is run
var ret_code = 'return {'
for(var i=0, _len_i = mod_names.length; i < _len_i;i++){
ret_code += mod_names[i]+':'+mod_names[i]+','
}
ret_code += '__getattr__:function(attr){return this[attr]},'
ret_code += '__setattr__:function(attr,value){this[attr]=value}'
ret_code += '}'
var ret_node = new $Node('expression')
new $NodeJSCtx(ret_node,ret_code)
mod_node.add(ret_node)
// add parenthesis for anonymous function execution
var ex_node = new $Node('expression')
new $NodeJSCtx(ex_node,')()')
root.add(ex_node)
try{
var js = root.to_js()
return js;
}catch(err){
eval('throw '+err.name+'(err.message)')
}
return undefined;
}
function build_ast(src) {
__BRYTHON__.$py_module_path['__main__']='./'
return __BRYTHON__.py2js(src,'__main__', '__main__', '__builtins__')
}
function execute_python_script(filename) {
_py_src=fs.readFileSync(filename, 'utf8')
var root = build_ast(_py_src)
var js = root.to_js()
//eval(js);
}
//console.log("try to execute compile script");
__BRYTHON__.$py_module_path = __BRYTHON__.$py_module_path || {}
__BRYTHON__.$py_module_alias = __BRYTHON__.$py_module_alias || {}
__BRYTHON__.exception_stack = __BRYTHON__.exception_stack || []
__BRYTHON__.scope = __BRYTHON__.scope || {}
__BRYTHON__.imported = __BRYTHON__.imported || {}
__BRYTHON__.modules = __BRYTHON__.modules || {}
__BRYTHON__.compile_python=$compile_python
__BRYTHON__.debug = 0
__BRYTHON__.$options = {}
__BRYTHON__.$options.debug = 0
// other import algs don't work in node
//import_funcs=[node_import]
if (!module.parent) {
var filename=process.argv[2];
execute_python_script(filename)
}
module.exports = __BRYTHON__;
-35
Ver Arquivo
@@ -1,35 +0,0 @@
/*globals define */
// This is a mixin containing helpers for working with operation nodes
define([],function() {
var OperationOps = function() {
};
OperationOps.prototype.getOutputs = function (node) {
return this.getOperationData(node, this.META.Outputs);
};
OperationOps.prototype.getInputs = function (node) {
return this.getOperationData(node, this.META.Inputs);
};
OperationOps.prototype.getOperationData = function (node, metaType) {
// Load the children and the output's children
return this.core.loadChildren(node)
.then(containers => {
var outputs = containers.find(c => this.core.isTypeOf(c, metaType));
return outputs ? this.core.loadChildren(outputs) : [];
})
.then(outputs => {
var bases = outputs.map(node => this.core.getMetaType(node));
// return [[arg1, Type1, node1], [arg2, Type2, node2]]
return outputs.map((node, i) => [
this.getAttribute(node, 'name'),
this.getAttribute(bases[i], 'name'),
node
]);
});
};
return OperationOps;
});
+13 -51
Ver Arquivo
@@ -6,64 +6,27 @@ define([
PluginUtils,
Q
) {
var CodeGen = {
Operation: {
pluginId: 'GenerateJob',
namespace: 'pipeline'
}
};
var PtrCodeGen = function() {
};
PtrCodeGen.prototype.getCodeGenPluginIdFor = function(node) {
var base = this.core.getBase(node),
name = this.core.getAttribute(node, 'name'),
namespace = this.core.getNamespace(node),
pluginId;
//this.logger.debug(`loaded pointer target of ${ptrId}: ${ptrNode}`);
pluginId = (this.core.getOwnRegistry(node, 'validPlugins') || '').split(' ').shift();
//this.logger.info(`generating code for ${this.core.getAttribute(ptrNode, 'name')} using ${pluginId}`);
if (this.core.isMetaNode(node) && CodeGen[name]) {
pluginId = CodeGen[name].pluginId || CodeGen[name];
namespace = CodeGen[name].namespace;
}
if (pluginId) {
return {
namespace: namespace,
pluginId: pluginId
};
} else if (base) {
return this.getCodeGenPluginIdFor(base);
} else {
return null;
}
};
PtrCodeGen.prototype.getPtrCodeHash = function(ptrId) {
return this.core.loadByPath(this.rootNode, ptrId)
.then(ptrNode => {
// Look up the plugin to use
var genInfo = this.getCodeGenPluginIdFor(ptrNode);
var metanode = this.core.getMetaType(ptrNode),
pluginId;
if (genInfo.pluginId) {
var context = {
namespace: genInfo.namespace,
activeNode: this.core.getPath(ptrNode)
};
this.logger.debug(`loaded pointer target of ${ptrId}: ${ptrNode}`);
pluginId = this.core.getRegistry(ptrNode, 'validPlugins').split(' ').shift();
this.logger.info(`generating code for ${this.core.getAttribute(ptrNode, 'name')} using ${pluginId}`);
// Load and run the plugin
return this.executePlugin(genInfo.pluginId, context);
} else {
var metanode = this.core.getMetaType(ptrNode),
type = this.core.getAttribute(metanode, 'name');
this.logger.warn(`Could not find plugin for ${type}. Will try to proceed anyway`);
return null;
}
var context = {
namespace: this.core.getNamespace(metanode),
activeNode: this.core.getPath(ptrNode)
};
// Load and run the plugin
return this.executePlugin(pluginId, context);
})
.then(hashes => hashes[0]); // Grab the first asset for now
};
@@ -93,13 +56,12 @@ define([
return PluginUtils.loadNodesAtCommitHash(
this.project,
this.core,
this.currentHash,
this.commitHash,
this.logger,
opts
).then(config => {
plugin.initialize(logger, this.blobClient, this.gmeConfig);
config.core = this.core;
config.project = this.project;
plugin.configure(config);
return plugin;
});
+1 -73
Ver Arquivo
@@ -1,10 +1,8 @@
/*globals define, WebGMEGlobal*/
define([
'deepforge/globals',
'widgets/EasyDAG/Buttons',
'widgets/EasyDAG/Icons'
], function(
DeepForge,
EasyDAGButtons,
Icons
) {
@@ -59,79 +57,9 @@ define([
return n && n.getBaseId();
};
var CloneAndEdit = function(params) {
GoToBase.call(this, params);
};
CloneAndEdit.prototype = Object.create(GoToBase.prototype);
CloneAndEdit.prototype.BTN_CLASS = 'clone-and-edit';
CloneAndEdit.prototype._render = function() {
var lineRadius = GoToBase.SIZE - GoToBase.BORDER,
btnColor = '#a5d6a7';
if (this.disabled) {
btnColor = '#e0e0e0';
}
this.$el
.append('circle')
.attr('r', GoToBase.SIZE)
.attr('fill', btnColor);
// Show the 'code' icon
Icons.addIcon('code', this.$el, {
radius: lineRadius
});
};
CloneAndEdit.prototype._onClick = function(item) {
var node = client.getNode(item.id),
baseId = node && node.getBaseId(),
base = baseId && client.getNode(baseId),
typeId = base && base.getBaseId(),
type = typeId && client.getNode(typeId),
ctrName,
typeName,
name,
newId;
// Clone the given node's base and change to it
if (type) {
typeName = type.getAttribute('name');
ctrName = `My${typeName}s`;
if (DeepForge.places[ctrName]) {
DeepForge.places[ctrName]().then(ctrId => {
type = base.getAttribute('name');
client.startTransaction(`Creating new ${typeName} from ${item.name}`);
newId = client.copyNode(baseId, ctrId);
name = node.getAttribute('name');
client.setAttribute(newId, 'name', 'Copy of ' + name);
DeepForge.register[typeName](newId);
client.completeTransaction();
WebGMEGlobal.State.registerActiveObject(newId);
});
}
} else {
this._logger.warn('Could not find the base node!');
}
};
var Insert = function(params) {
EasyDAGButtons.ButtonBase.call(this, params);
};
Insert.prototype = Object.create(EasyDAGButtons.Add.prototype);
Insert.prototype._onClick = function(item) {
this.onInsertButtonClicked(item);
};
return {
DeleteOne: EasyDAGButtons.DeleteOne,
GoToBase: GoToBase,
CloneAndEdit: CloneAndEdit,
Insert: Insert
GoToBase: GoToBase
};
});
-4
Ver Arquivo
@@ -4,11 +4,9 @@
// adding a "plus" button for creating new objects in line
define([
'deepforge/Constants',
'q',
'css!./NodePrompter.css'
], function(
Constants,
Q
) {
@@ -273,14 +271,12 @@ define([
};
var Container = function(svg, node) { // used for positioning
var colorAttr = node.attributes[Constants.DISPLAY_COLOR];
this.$el = svg.append('g');
this.x = 0;
this.y = 0;
this.node = node;
this.decorator = new node.Decorator({
node: node,
color: colorAttr && colorAttr.value,
parentEl: this.$el
});
};
-4
Ver Arquivo
@@ -103,10 +103,6 @@ define([
delete desc.attributes.code;
}
// Handle the display color
desc.displayColor = desc.attributes[CONSTANTS.DISPLAY_COLOR].value;
delete desc.attributes[CONSTANTS.DISPLAY_COLOR];
} else if (desc.isConnection) {
// Set src, dst to siblings and add srcPort, dstPort
desc.srcPort = desc.src;
@@ -40,40 +40,10 @@ define([
ArtifactOpDecorator.prototype.DECORATOR_ID = DECORATOR_ID;
ArtifactOpDecorator.prototype.getTargetFilterFnFor = function() {
var currentNode,
pId,
peerIds,
currentDataId,
targetTypeIds = [];
// Get all connections from this node's data
if (this._node.outputs[0]) {
currentNode = this.client.getNode(this._node.id);
pId = currentNode.getParentId();
peerIds = this.client.getNode(pId).getChildrenIds();
currentDataId = this._node.outputs[0].id;
targetTypeIds = peerIds.map(id => this.client.getNode(id))
.filter(node => {
var ptr = node.getPointer('src');
return ptr.to === currentDataId;
})
// Get the target data types
.map(node => this.client.getNode(node.getPointer('dst').to).getMetaTypeId());
}
return id => {
var node = this.client.getNode(id),
isMetaTgt = node.getId() === node.getMetaTypeId(),
isValidType = true;
// make sure it is a type of the target types
isValidType = targetTypeIds.reduce((passing, typeId) => {
return passing && node.isTypeOf(typeId);
}, true);
return isValidType && isMetaTgt === this.castOpts.metaTgt;
isMetaTgt = node.getId() === node.getMetaTypeId();
return isMetaTgt === this.castOpts.metaTgt;
};
};
@@ -42,8 +42,8 @@ define([
embedded: true,
widget: this.widget
});
this.control._onUnload = id => {
ArchEditor.prototype._onUnload.call(this.control, id);
this.control._onUnload = () => {
ArchEditor.prototype._onUnload.apply(this.control, arguments);
// If it was the last node, remove it
var node = this.control._client.getNode(this.id);
if (node.getChildrenIds().length === 0) {
@@ -34,13 +34,7 @@ define([
this.enableTooltip(this._node.baseName, 'dark');
}
DecoratorBase.prototype.initialize.call(this);
this.$name.on('click', () => {
// Operations must already be selected. Otherwise, they will animate
// after the edit name box is created and it will be placed incorrectly
if (this.expanded || !this.isOperation()) {
this.editName();
}
});
this.$name.on('dblclick', this.editName.bind(this));
};
OpIntDecorator.prototype.AttributeField = AttributeField;
@@ -2,11 +2,9 @@
/*jshint browser: true, camelcase: false*/
define([
'deepforge/Constants',
'decorators/EllipseDecorator/EasyDAG/EllipseDecorator.EasyDAGWidget',
'css!./OperationDecorator.EasyDAGWidget.css'
], function (
CONSTANTS,
DecoratorBase
) {
@@ -15,7 +13,6 @@ define([
var OperationDecorator,
NAME_MARGIN = 25,
DECORATOR_ID = 'OperationDecorator',
OPERATION_COLORS = {},
PORT_TOOLTIP_OPTS = {
tipJoint: 'left',
removeElementsOnHide: true,
@@ -27,10 +24,8 @@ define([
// - highlight ports
// - unhighlight ports
// - report the location of specific ports
OPERATION_COLORS[CONSTANTS.OP.OUTPUT] = '#b0bec5';
OPERATION_COLORS[CONSTANTS.OP.INPUT] = '#b0bec5';
OperationDecorator = function (options) {
options.color = OPERATION_COLORS[options.node.name] || options.color || '#78909c';
options.color = options.color || '#78909c';
DecoratorBase.call(this, options);
this.id = this._node.id;
-5
Ver Arquivo
@@ -48,10 +48,5 @@ define([
}
};
SidebarLayout.prototype._onCenterResize = function() {
var width = this._centerPanel.width() - this._sidebarPanel.width();
this._canvas.setSize(width, this._centerPanel.height());
};
return SidebarLayout;
});
+1 -4
Ver Arquivo
@@ -173,10 +173,7 @@ define([
name,
i = 2;
basename = basename
.replace(/^\s*/, '')
.replace(/\s*$/, '')
.replace(/[^\da-zA-Z_]/g, '_');
basename = basename.replace(/[^\da-zA-Z_]/g, '_');
name = basename;
// Get a unique name wrt the tags and the other executions
+9 -3
Ver Arquivo
@@ -205,9 +205,10 @@ define([
};
// Some helper methods w/ attribute handling
var LUA_TO_GME = {
var PYTHON_TO_GME = {
boolean: 'boolean',
number: 'float',
float: 'float',
int: 'integer',
string: 'string'
};
@@ -301,7 +302,7 @@ define([
attrs.forEach(name => {
desc = {};
defVal = defaults.hasOwnProperty(name) ? defaults[name] : '';
type = LUA_TO_GME[types[name]];
type = PYTHON_TO_GME[types[name]];
if (type) {
desc.type = type;
}
@@ -376,6 +377,11 @@ define([
// Set the min, max
schema.max = +schema.max;
}
// Add the enum for booleans so we use python style True/False
if (schema.type === 'boolean') {
schema.enum = ['True', 'False'];
schema.type = 'string';
}
// Create the attribute and set the schema
this.core.setAttributeMeta(node, name, schema);
-1
Ver Arquivo
@@ -17,7 +17,6 @@
"value": "all",
"valueItems": [
"nn",
"rnn",
"all"
],
"valueType": "string",
+3 -6
Ver Arquivo
@@ -1,13 +1,10 @@
/*globals define*/
define([
'text!./nn.json',
'text!./rnn.json'
'text!./nn.json'
], function(
nn,
rnn
nn
) {
return {
nn: nn,
rnn: rnn
nn: nn
};
});
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
-178
Ver Arquivo
@@ -1,178 +0,0 @@
[
{
"name": "CopyGrad",
"baseType": "Identity",
"setters": {},
"defaults": {},
"type": "RNN"
},
{
"name": "FastLSTM",
"baseType": "LSTM",
"params": [
"inputSize",
"outputSize",
"rho",
"eps",
"momentum",
"affine"
],
"setters": {},
"types": {
"eps": "number",
"momentum": "number"
},
"defaults": {
"momentum": 0.1,
"eps": 0.1
},
"type": "RNN"
},
{
"name": "LSTM",
"baseType": "AbstractRecurrent",
"params": [
"inputSize",
"outputSize",
"rho",
"cell2gate"
],
"setters": {},
"types": {
"rho": "number"
},
"defaults": {
"rho": 9999
},
"type": "RNN"
},
{
"name": "LinearNoBias",
"baseType": "Linear",
"params": [
"inputSize",
"outputSize"
],
"setters": {},
"types": {},
"defaults": {},
"type": "Simple"
},
{
"name": "LookupTableMaskZero",
"baseType": "LookupTable",
"params": [
"nIndex",
"nOutput"
],
"setters": {},
"types": {},
"defaults": {},
"type": "RNN"
},
{
"name": "NormStabilizer",
"baseType": "AbstractRecurrent",
"params": [
"beta"
],
"setters": {},
"defaults": {},
"type": "RNN"
},
{
"name": "Recurrent",
"baseType": "AbstractRecurrent",
"params": [
"start",
"input",
"feedback",
"transfer",
"rho",
"merge"
],
"setters": {},
"types": {
"start": "nn.Module",
"transfer": "nn.Module",
"feedback": "nn.Module",
"input": "nn.Module"
},
"defaults": {},
"type": "RNN"
},
{
"name": "SAdd",
"baseType": "Module",
"params": [
"addend",
"negate"
],
"setters": {},
"types": {},
"defaults": {},
"type": "RNN"
},
{
"name": "SeqBRNN",
"baseType": "Container",
"params": [
"inputDim",
"hiddenDim",
"batchFirst"
],
"setters": {},
"types": {},
"defaults": {},
"type": "RNN"
},
{
"name": "SeqGRU",
"baseType": "Module",
"params": [
"inputSize",
"outputSize"
],
"setters": {},
"types": {},
"defaults": {},
"type": "RNN"
},
{
"name": "SeqLSTM",
"baseType": "Module",
"params": [
"inputsize",
"hiddensize",
"outputsize"
],
"setters": {},
"types": {},
"defaults": {},
"type": "RNN"
},
{
"name": "SeqLSTMP",
"baseType": "SeqLSTM",
"params": [
"inputsize",
"hiddensize",
"outputsize"
],
"setters": {},
"types": {},
"defaults": {},
"type": "RNN"
},
{
"name": "SeqReverseSequence",
"baseType": "Module",
"params": [
"dim"
],
"setters": {},
"types": {},
"defaults": {},
"type": "RNN"
}
]
@@ -1,212 +1,20 @@
/*globals define*/
/*jshint node:true, browser:true*/
define([
'./templates/index',
'q',
'underscore',
'deepforge/Constants',
'deepforge/plugin/Operation',
'deepforge/plugin/PtrCodeGen',
'text!./metadata.json',
'plugin/PluginBase'
], function (
'deepforge/Constants'
], function(
Templates,
Q,
_,
CONSTANTS,
OperationHelpers,
PtrCodeGen,
pluginMetadata,
PluginBase
CONSTANTS
) {
'use strict';
pluginMetadata = JSON.parse(pluginMetadata);
var OUTPUT_INTERVAL = 1500,
STDOUT_FILE = 'job_stdout.txt',
SKIP_ATTRIBUTES = [
'code',
'stdout',
'execFiles',
'jobId',
'secret',
CONSTANTS.LINE_OFFSET,
CONSTANTS.DISPLAY_COLOR
];
/**
* Initializes a new instance of GenerateJob.
* @class
* @augments {PluginBase}
* @classdesc This class represents the plugin GenerateJob.
* @constructor
*/
var GenerateJob = function () {
// Call base class' constructor.
PluginBase.call(this);
this.pluginMetadata = pluginMetadata;
var ExecuteJob = function() {
};
/**
* Metadata associated with the plugin. Contains id, name, version, description, icon, configStructue etc.
* This is also available at the instance at this.pluginMetadata.
* @type {object}
*/
GenerateJob.metadata = pluginMetadata;
// Prototypical inheritance from PluginBase.
GenerateJob.prototype = Object.create(PluginBase.prototype);
GenerateJob.prototype.constructor = GenerateJob;
/**
* Main function for the plugin to execute. This will perform the execution.
* Notes:
* - Always log with the provided logger.[error,warning,info,debug].
* - Do NOT put any user interaction logic UI, etc. inside this method.
* - callback always has to be called even if error happened.
*
* @param {function(string, plugin.PluginResult)} callback - the result callback
*/
GenerateJob.prototype.main = function (callback) {
var files,
artifactName,
artifact,
data = {},
inputs,
name,
opId;
name = this.getAttribute(this.activeNode, 'name');
opId = this.core.getPath(this.activeNode);
return this.createOperationFiles(this.activeNode)
.then(results => {
this.logger.info('Created operation files!');
files = results;
artifactName = `${name}_${opId.replace(/\//g, '_')}-execution-files`;
artifact = this.blobClient.createArtifact(artifactName);
// Add the input assets
// - get the metadata (name)
// - add the given inputs
inputs = Object.keys(files.inputAssets);
return Q.all(
inputs.map(input => { // Get the metadata for each input
var hash = files.inputAssets[input];
// data asset for "input"
return this.blobClient.getMetadata(hash)
.fail(() => {
throw Error(`BLOB_FETCH_FAILED:${input}`);
});
})
);
})
.then(mds => {
// Record the large files
var inputData = {},
runsh = '# Bash script to download data files and run job\n' +
'if [ -z "$DEEPFORGE_URL" ]; then\n echo "Please set DEEPFORGE_URL and' +
' re-run:"\n echo "" \n echo " DEEPFORGE_URL=http://my.' +
'deepforge.server.com:8080 bash run.sh"\n echo ""\n exit 1\nfi\n';
mds.forEach((metadata, i) => {
// add the hashes for each input
var input = inputs[i],
hash = files.inputAssets[input],
dataPath = 'inputs/' + input + '/data',
url = this.blobClient.getRelativeDownloadURL(hash);
inputData[dataPath] = {
req: hash,
cache: metadata.content
};
// Add to the run.sh file
runsh += `wget $DEEPFORGE_URL${url} -O ${dataPath}\n`;
});
delete files.inputAssets;
files['input-data.json'] = JSON.stringify(inputData, null, 2);
runsh += 'th init.lua';
files['run.sh'] = runsh;
// Add pointer assets
Object.keys(files.ptrAssets)
.forEach(path => data[path] = files.ptrAssets[path]);
// Add the executor config
return this.getOutputs(this.activeNode);
})
.then(outputArgs => {
var config,
outputs,
fileList,
ptrFiles = Object.keys(files.ptrAssets),
file;
delete files.ptrAssets;
fileList = Object.keys(files).concat(ptrFiles);
outputs = outputArgs.map(pair => pair[0])
.map(name => {
return {
name: name,
resultPatterns: [`outputs/${name}`]
};
});
outputs.push(
{
name: 'stdout',
resultPatterns: [STDOUT_FILE]
},
{
name: name + '-all-files',
resultPatterns: fileList
}
);
config = {
cmd: 'node',
args: ['start.js'],
outputInterval: OUTPUT_INTERVAL,
resultArtifacts: outputs
};
files['executor_config.json'] = JSON.stringify(config, null, 4);
// Save the artifact
// Remove empty hashes
for (file in data) {
if (!data[file]) {
this.logger.warn(`Empty data hash has been found for file "${file}". Removing it...`);
delete data[file];
}
}
return artifact.addObjectHashes(data);
})
.then(() => {
this.logger.info(`Added ptr/input data hashes for "${artifactName}"`);
return artifact.addFiles(files);
})
.then(() => {
this.logger.info(`Added execution files for "${artifactName}"`);
return artifact.save();
})
.then(hash => {
this.result.setSuccess(true);
this.result.addArtifact(hash);
callback(null, this.result);
})
.fail(err => {
this.result.setSuccess(false);
callback(err, this.result);
});
};
GenerateJob.prototype.createOperationFiles = function (node) {
ExecuteJob.prototype.createOperationFiles = function (node) {
var files = {};
// For each operation, generate the output files:
// inputs/<arg-name>/init.lua (respective data deserializer)
@@ -230,14 +38,10 @@ define([
.then(() => {
this.createAttributeFile(node, files);
return Q.ninvoke(this, 'createPointers', node, files);
})
.fail(err => {
this.logger.error(err);
throw err;
});
};
GenerateJob.prototype.createEntryFile = function (node, files) {
ExecuteJob.prototype.createEntryFile = function (node, files) {
this.logger.info('Creating entry files...');
return this.getOutputs(node)
.then(outputs => {
@@ -255,7 +59,7 @@ define([
});
};
GenerateJob.prototype.createClasses = function (node, files) {
ExecuteJob.prototype.createClasses = function (node, files) {
var metaDict = this.core.getAllMetaNodes(this.rootNode),
isClass,
metanodes,
@@ -269,17 +73,17 @@ define([
classNodes = metanodes.filter(node => {
var base = this.core.getBase(node),
baseId,
baseId = this.core.getPath(base),
count = 1;
// Count the sets back to a class node
while (base) {
baseId = this.core.getPath(base);
if (isClass[baseId]) {
inheritanceLvl[this.core.getPath(node)] = count;
return true;
}
base = this.core.getBase(base);
baseId = this.core.getPath(base);
count++;
}
@@ -307,7 +111,7 @@ define([
files['classes/init.lua'] = code;
};
GenerateJob.prototype.getTypeDictFor = function (name, metanodes) {
ExecuteJob.prototype.getTypeDictFor = function (name, metanodes) {
var isType = {};
// Get all the custom layers
for (var i = metanodes.length; i--;) {
@@ -318,7 +122,7 @@ define([
return isType;
};
GenerateJob.prototype.createCustomLayers = function (node, files) {
ExecuteJob.prototype.createCustomLayers = function (node, files) {
var metaDict = this.core.getAllMetaNodes(this.rootNode),
isCustomLayer,
metanodes,
@@ -340,29 +144,7 @@ define([
files['custom-layers.lua'] = code;
};
GenerateJob.prototype.getConnectionContainer = function () {
var container = this.core.getParent(this.activeNode);
if (this.isMetaTypeOf(container, this.META.Job)) {
container = this.core.getParent(container);
}
return container;
};
GenerateJob.prototype.getInputPortsFor = function (nodeId) {
var container = this.getConnectionContainer();
// Get the connections to this node
return this.core.loadChildren(container)
.then(children => {
return children.filter(child =>
this.core.getPointerPath(child, 'dst') === nodeId)
.map(conn => this.core.getPointerPath(conn, 'src'))[0];
});
};
GenerateJob.prototype.createInputs = function (node, files) {
ExecuteJob.prototype.createInputs = function (node, files) {
var tplContents,
inputs;
@@ -383,13 +165,15 @@ define([
return Q.all(inputs.map(pair => {
var name = pair[0],
node = pair[2],
nodeId = this.core.getPath(node);
nodeId = this.core.getPath(node),
fromNodeId;
// Get the deserialize function. First, try to get it from
// the source method (this guarantees that the correct
// deserialize method is used despite any auto-upcasting
return this.getInputPortsFor(nodeId)
.then(fromNodeId => this.core.loadByPath(this.rootNode, fromNodeId || nodeId))
fromNodeId = this.inputPortsFor[nodeId][0] || nodeId;
return this.core.loadByPath(this.rootNode, fromNodeId)
.then(fromNode => {
var deserFn,
base,
@@ -425,9 +209,7 @@ define([
return Q.all(hashes.map(pair =>
this.blobClient.getMetadata(pair.hash)
.fail(() => {
throw Error(`BLOB_FETCH_FAILED:${pair.name}`);
})));
.fail(err => this.onBlobRetrievalFail(node, pair.name, err))));
})
.then(metadatas => {
// Create the deserializer
@@ -440,7 +222,7 @@ define([
});
};
GenerateJob.prototype.createOutputs = function (node, files) {
ExecuteJob.prototype.createOutputs = function (node, files) {
// For each of the output types, grab their serialization functions and
// create the `outputs/init.lua` file
this.logger.info('Creating outputs/init.lua...');
@@ -465,7 +247,7 @@ define([
});
};
GenerateJob.prototype.createMainFile = function (node, files) {
ExecuteJob.prototype.createMainFile = function (node, files) {
this.logger.info('Creating main file...');
return this.getInputs(node)
.then(inputs => {
@@ -495,26 +277,27 @@ define([
});
};
GenerateJob.prototype.getLineOffset = function (main, snippet) {
ExecuteJob.prototype.getLineOffset = function (main, snippet) {
var i = main.indexOf(snippet),
lines = main.substring(0, i).match(/\n/g);
return lines ? lines.length : 0;
};
GenerateJob.prototype.createAttributeFile = function (node, files) {
var numOrBool = /^(-?\d+\.?\d*((e|e-)\d+)?|(true|false))$/,
ExecuteJob.prototype.createAttributeFile = function (node, files) {
var skip = ['code', 'stdout', 'execFiles', 'jobId', 'secret'],
numOrBool = /^(-?\d+\.?\d*((e|e-)\d+)?|(true|false))$/,
table;
this.logger.info('Creating attributes file...');
table = '{\n\t' + this.core.getAttributeNames(node)
.filter(attr => SKIP_ATTRIBUTES.indexOf(attr) === -1)
.filter(attr => skip.indexOf(attr) === -1)
.map(name => {
var value = this.getAttribute(node, name);
if (!numOrBool.test(value)) {
value = `"${value}"`;
}
return [`['${name}']`, value];
return [name, value];
})
.map(pair => pair.join(' = '))
.join(',\n\t') + '\n}';
@@ -522,7 +305,7 @@ define([
files['attributes.lua'] = `-- attributes of ${this.getAttribute(node, 'name')}\nreturn ${table}`;
};
GenerateJob.prototype.createPointers = function (node, files, cb) {
ExecuteJob.prototype.createPointers = function (node, files, cb) {
var pointers,
nIds;
@@ -550,19 +333,6 @@ define([
});
};
GenerateJob.prototype.getAttribute = function (node, attr) {
return this.core.getAttribute(node, attr);
};
GenerateJob.prototype.setAttribute = function (node, attr, value) {
return this.core.setAttribute(node, attr, value);
};
_.extend(
GenerateJob.prototype,
OperationHelpers.prototype,
PtrCodeGen.prototype
);
return GenerateJob;
return ExecuteJob;
});
@@ -30,30 +30,6 @@ define([
this._metadata[id] = graph;
};
ExecuteJob.prototype[CONSTANTS.GRAPH_LABEL_AXIS.X] = function (job, id) {
var name = Array.prototype.slice.call(arguments, 2).join(' '),
jobId = this.core.getPath(job),
graph;
id = jobId + '/' + id;
this.logger.info(`Labeling the x-axis of ${id}: ${name}`);
graph = this._metadata[id];
this.setAttribute(graph, 'xlabel', name);
};
ExecuteJob.prototype[CONSTANTS.GRAPH_LABEL_AXIS.Y] = function (job, id) {
var name = Array.prototype.slice.call(arguments, 2).join(' '),
jobId = this.core.getPath(job),
graph;
id = jobId + '/' + id;
this.logger.info(`Labeling the y-axis of ${id}: ${name}`);
graph = this._metadata[id];
this.setAttribute(graph, 'ylabel', name);
};
ExecuteJob.prototype[CONSTANTS.GRAPH_PLOT] = function (job, id, x, y) {
var jobId = this.core.getPath(job),
nonNum = /[^\d-\.]*/g,
+160 -24
Ver Arquivo
@@ -8,10 +8,10 @@ define([
'plugin/PluginBase',
'deepforge/plugin/LocalExecutor',
'deepforge/plugin/PtrCodeGen',
'deepforge/plugin/Operation',
'deepforge/api/JobLogsClient',
'deepforge/api/JobOriginClient',
'deepforge/api/ExecPulseClient',
'./ExecuteJob.Files',
'./ExecuteJob.Metadata',
'./ExecuteJob.SafeSave',
'deepforge/Constants',
@@ -26,11 +26,11 @@ define([
PluginBase,
LocalExecutor, // DeepForge operation primitives
PtrCodeGen,
OperationPlugin,
JobLogsClient,
JobOriginClient,
ExecPulseClient,
ExecuteJobFiles,
ExecuteJobMetadata,
ExecuteJobSafeSave,
@@ -44,7 +44,8 @@ define([
pluginMetadata = JSON.parse(pluginMetadata);
var STDOUT_FILE = 'job_stdout.txt';
var OUTPUT_INTERVAL = 1500,
STDOUT_FILE = 'job_stdout.txt';
/**
* Initializes a new instance of ExecuteJob.
@@ -452,10 +453,9 @@ define([
children.find(child => this.isMetaTypeOf(child, this.META.Operation)));
};
// Handle the blob retrieval failed error
ExecuteJob.prototype.onBlobRetrievalFail = function (node, input) {
ExecuteJob.prototype.onBlobRetrievalFail = function (node, input, err) {
var job = this.core.getParent(node),
e = `Failed to retrieve "${input}" (BLOB_FETCH_FAILED)`,
e = `Failed to retrieve "${input}" (${err})`,
consoleErr = `Failed to execute operation: ${e}`;
consoleErr += [
@@ -473,8 +473,14 @@ define([
ExecuteJob.prototype.executeJob = function (job) {
return this.getOperation(job).then(node => {
var name = this.getAttribute(node, 'name'),
localTypeId = this.getLocalOperationType(node);
var jobId = this.core.getPath(job),
name = this.getAttribute(node, 'name'),
localTypeId = this.getLocalOperationType(node),
artifact,
artifactName,
files,
data = {},
inputs;
// Execute any special operation types here - not on an executor
this.logger.debug(`Executing operation "${name}"`);
@@ -482,22 +488,126 @@ define([
return this.executeLocalOperation(localTypeId, node);
} else {
// Generate all execution files
return this.getPtrCodeHash(this.core.getPath(node))
.fail(err => {
this.logger.error(`Could not generate files: ${err}`);
if (err.message.indexOf('BLOB_FETCH_FAILED') > -1) {
this.onBlobRetrievalFail(node, err.message.split(':')[1]);
}
throw err;
})
.then(hash => {
this.logger.info(`Saved execution files`);
this.result.addArtifact(hash); // Probably only need this for debugging...
this.executeDistOperation(job, node, hash);
})
.fail(e => {
this.onOperationFail(node, `Distributed operation "${name}" failed ${e}`);
return this.createOperationFiles(node).then(results => {
this.logger.info('Created operation files!');
files = results;
artifactName = `${name}_${jobId.replace(/\//g, '_')}-execution-files`;
artifact = this.blobClient.createArtifact(artifactName);
// Add the input assets
// - get the metadata (name)
// - add the given inputs
inputs = Object.keys(files.inputAssets);
return Q.all(
inputs.map(input => { // Get the metadata for each input
var hash = files.inputAssets[input];
// data asset for "input"
return this.blobClient.getMetadata(hash)
.fail(err => this.onBlobRetrievalFail(job, input, err));
})
);
})
.then(mds => {
// Record the large files
var inputData = {},
runsh = '# Bash script to download data files and run job\n' +
'if [ -z "$DEEPFORGE_URL" ]; then\n echo "Please set DEEPFORGE_URL and' +
' re-run:"\n echo "" \n echo " DEEPFORGE_URL=http://my.' +
'deepforge.server.com:8080 bash run.sh"\n echo ""\n exit 1\nfi\n';
mds.forEach((metadata, i) => {
// add the hashes for each input
var input = inputs[i],
hash = files.inputAssets[input],
dataPath = 'inputs/' + input + '/data',
url = this.blobClient.getRelativeDownloadURL(hash);
inputData[dataPath] = {
req: hash,
cache: metadata.content
};
// Add to the run.sh file
runsh += `wget $DEEPFORGE_URL${url} -O ${dataPath}\n`;
});
delete files.inputAssets;
files['input-data.json'] = JSON.stringify(inputData, null, 2);
runsh += 'th init.lua';
files['run.sh'] = runsh;
// Add pointer assets
Object.keys(files.ptrAssets)
.forEach(path => data[path] = files.ptrAssets[path]);
// Add the executor config
return this.getOutputs(node);
})
.then(outputArgs => {
var config,
outputs,
fileList,
ptrFiles = Object.keys(files.ptrAssets),
file;
delete files.ptrAssets;
fileList = Object.keys(files).concat(ptrFiles);
outputs = outputArgs.map(pair => pair[0])
.map(name => {
return {
name: name,
resultPatterns: [`outputs/${name}`]
};
});
outputs.push(
{
name: 'stdout',
resultPatterns: [STDOUT_FILE]
},
{
name: name + '-all-files',
resultPatterns: fileList
}
);
config = {
cmd: 'node',
args: ['start.js'],
outputInterval: OUTPUT_INTERVAL,
resultArtifacts: outputs
};
files['executor_config.json'] = JSON.stringify(config, null, 4);
// Save the artifact
// Remove empty hashes
for (file in data) {
if (!data[file]) {
this.logger.warn(`Empty data hash has been found for file "${file}". Removing it...`);
delete data[file];
}
}
return artifact.addObjectHashes(data);
})
.then(() => {
this.logger.info(`Added ptr/input data hashes for "${artifactName}"`);
return artifact.addFiles(files);
})
.then(() => {
this.logger.info(`Added execution files for "${artifactName}"`);
return artifact.save();
})
.then(hash => {
this.logger.info(`Saved execution files "${artifactName}"`);
this.result.addArtifact(hash); // Probably only need this for debugging...
this.executeDistOperation(job, node, hash);
})
.fail(e => {
this.onOperationFail(node, `Distributed operation "${name}" failed ${e}`);
});
}
});
};
@@ -771,6 +881,32 @@ define([
.fail(e => this.onOperationFail(node, `Operation ${nodeId} failed: ${e}`));
};
ExecuteJob.prototype.getOutputs = function (node) {
return this.getOperationData(node, this.META.Outputs);
};
ExecuteJob.prototype.getInputs = function (node) {
return this.getOperationData(node, this.META.Inputs);
};
ExecuteJob.prototype.getOperationData = function (node, metaType) {
// Load the children and the output's children
return this.core.loadChildren(node)
.then(containers => {
var outputs = containers.find(c => this.core.isTypeOf(c, metaType));
return outputs ? this.core.loadChildren(outputs) : [];
})
.then(outputs => {
var bases = outputs.map(node => this.core.getMetaType(node));
// return [[arg1, Type1, node1], [arg2, Type2, node2]]
return outputs.map((node, i) => [
this.getAttribute(node, 'name'),
this.getAttribute(bases[i], 'name'),
node
]);
});
};
//////////////////////////// Special Operations ////////////////////////////
ExecuteJob.prototype.executeLocalOperation = function (type, node) {
// Retrieve the given LOCAL_OP type
@@ -784,7 +920,7 @@ define([
_.extend(
ExecuteJob.prototype,
OperationPlugin.prototype,
ExecuteJobFiles.prototype,
ExecuteJobMetadata.prototype,
ExecuteJobSafeSave.prototype,
PtrCodeGen.prototype,
@@ -52,14 +52,6 @@ function Graph:line(name, opts)
return deepforge._Line(self.id, name, opts)
end
function Graph:xlabel(name)
deepforge._cmd('<%= GRAPH_LABEL_AXIS.X %>', self.id, name)
end
function Graph:ylabel(name)
deepforge._cmd('<%= GRAPH_LABEL_AXIS.Y %>', self.id, name)
end
-- Image support
local function saveImage(name, tensor)
require 'image'
@@ -74,7 +74,7 @@ requirejs([
var checkFinished = () => {
if (exitCode !== null && remainingImageCount === 0) {
log('finished!');
cleanup();
process.exit(exitCode);
}
};
@@ -201,45 +201,14 @@ requirejs([
// Download the large files
var inputData = JSON.parse(fs.readFileSync('./input-data.json')),
inputPaths = Object.keys(inputData),
pid,
job,
cleanup;
// Make sure to kill the spawned process group on exit
cleanup = function() {
if (job) {
pid = job.pid;
job = null;
log(`killing process group: ${pid}`);
process.kill(-pid, 'SIGTERM');
}
if (exitCode !== null) {
log(`exiting w/ code ${exitCode}`);
process.exit(exitCode);
}
};
process.on('exit', () => {
log('received "exit" event')
cleanup();
});
process.on('SIGINT', function() {
log('received "SIGINT" event')
cleanup();
process.exit(130);
});
process.on('uncaughtException', () => {
log('received "uncaughtException" event')
cleanup();
});
inputPaths = Object.keys(inputData);
// Request the data from the blob
prepareCache()
.then(() => Q.all(inputPaths.map(ipath => getData(ipath, inputData[ipath]))))
.then(() => {
// Run 'th init.lua' and merge the stdout, stderr
job = spawn('th', ['init.lua'], {detached: true});
var job = spawn('th', ['init.lua']);
job.stdout.on('data', onStdout);
job.stderr.on('data', onStderr);
job.on('close', code => {
+1 -5
Ver Arquivo
@@ -175,7 +175,6 @@ define([
ExecutePipeline.prototype.resumePipeline = function () {
var nodes = Object.keys(this.nodes).map(id => this.nodes[id]),
allJobs = nodes.filter(node => this.core.isTypeOf(node, this.META.Job)),
name = this.getAttribute(this.activeNode, 'name'),
status,
jobs = {
success: [],
@@ -209,7 +208,6 @@ define([
return Q.all(allJobs.map(job => this.recordOldMetadata(job, true)))
.then(() => Q.all(jobs.success.map(job => this.getOperation(job))))
.then(ops => ops.forEach(op => this.updateJobCompletionRecords(op)))
.then(() => this.save(`Resuming pipeline execution: ${name}`))
.then(() => {
if (jobs.running.length) { // Resume all running jobs
@@ -533,12 +531,10 @@ define([
this.logger.info(`Setting ${jobId} status to "success"`);
this.logger.info(`There are now ${this.runningJobs} running jobs`);
this.logger.debug(`Making a commit from ${this.currentHash}`);
counts = this.updateJobCompletionRecords(opNode);
this.save(`Operation "${name}" in ${this.pipelineName} completed successfully`)
.then(() => {
counts = this.updateJobCompletionRecords(opNode);
hasReadyOps = counts.indexOf(0) > -1;
this.logger.debug(`Operation "${name}" completed. ` +
-925
Ver Arquivo
@@ -1,925 +0,0 @@
/*globals define */
/*jshint node:true, browser:true*/
define([
'text!./metadata.json',
'text!./deepforge.ejs',
'./format',
'plugin/PluginBase',
'deepforge/plugin/PtrCodeGen',
'deepforge/Constants',
'blob/BlobConfig',
'underscore',
'q'
], function (
pluginMetadata,
DeepForgeBaseCode,
FORMATS,
PluginBase,
PtrCodeGen,
CONSTANTS,
BlobConfig,
_,
Q
) {
'use strict';
pluginMetadata = JSON.parse(pluginMetadata);
var HEADER_LENGTH = 60,
SKIP_ATTRS = {
lineOffset: true,
code: true
},
RESERVED = /^(and|break|do|else|elseifend|false|for|function|if|in|local|nil|not|orrepeat|return|then|true|until|while|print)$/,
DeepForgeTpl = _.template(DeepForgeBaseCode);
/**
* Initializes a new instance of Export.
* @class
* @augments {PluginBase}
* @classdesc This class represents the plugin Export.
* @constructor
*/
var Export = function () {
// Call base class' constructor.
PluginBase.call(this);
this.initRecords();
};
/**
* Metadata associated with the plugin. Contains id, name, version, description, icon, configStructue etc.
* This is also available at the instance at this.pluginMetadata.
* @type {object}
*/
Export.metadata = pluginMetadata;
// Prototypical inheritance from PluginBase.
Export.prototype = Object.create(PluginBase.prototype);
Export.prototype.constructor = Export;
Export.prototype.initRecords = function() {
this.pluginMetadata = pluginMetadata;
this._srcIdFor = {}; // input path -> output data node path
this._nameFor = {}; // input path -> opname
this._outputNames = {};
this._baseNameFor = {};
this._dataNameFor = {};
this._instanceNames = {};
this._opBaseNames = {};
this._fnNameFor = {};
this._functions = {}; // function definitions for the operations
// topo sort stuff
this._nextOps = {};
this._incomingCnts = {};
this._operations = {};
this.activeNodeId = null;
this.activeNodeDepth = null;
this.isInputOp = {};
this._portCache = {};
this.inputNode = {};
this.outputDataToOpId = {};
this.isOutputOp = {};
};
/**
* Main function for the plugin to execute. This will perform the execution.
* Notes:
* - Always log with the provided logger.[error,warning,info,debug].
* - Do NOT put any user interaction logic UI, etc. inside this method.
* - callback always has to be called even if error happened.
*
* @param {function(string, plugin.PluginResult)} callback - the result callback
*/
Export.prototype.main = function (callback) {
this.initRecords();
// Get all the children and call generate exec file
this.activeNodeId = this.core.getPath(this.activeNode);
this.activeNodeDepth = this.activeNodeId.split('/').length + 1;
if (this.isMetaTypeOf(this.activeNode, this.META.Execution)) {
this.activeNodeDepth++;
}
return this.core.loadChildren(this.activeNode)
.then(nodes => this.generateOutputFiles(nodes))
.catch(err => callback(err))
.then(hash => {
this.result.addArtifact(hash);
this.result.setSuccess(true);
callback(null, this.result);
})
.fail(err => callback(err));
};
Export.prototype.getCurrentConfig = function () {
var config = PluginBase.prototype.getCurrentConfig.call(this);
config.staticInputs = config.staticInputs || [];
return config;
};
Export.prototype.getExporterFor = function (name) {
var Exporter = function() {},
format = FORMATS[name],
exporter;
Exporter.prototype = this;
exporter = new Exporter();
if (typeof format === 'function') {
exporter.main = format;
} else {
_.extend(exporter, format);
}
return exporter;
};
Export.prototype.generateOutputFiles = function (children) {
var name = this.core.getAttribute(this.activeNode, 'name');
return this.createCodeSections(children)
.then(sections => {
// Get the selected format
var config = this.getCurrentConfig(),
format = config.format || 'Basic CLI',
exporter,
staticInputs,
files;
this.logger.info(`About to retrieve ${config.format} exporter`);
exporter = this.getExporterFor(format);
staticInputs = config.staticInputs.map(id => {
var opId = id.split('/').splice(0, this.activeNodeDepth).join('/'),
port = this._portCache[id];
return {
portId: id,
id: opId,
hash: this.core.getAttribute(port, 'data'),
name: this._nameFor[opId]
};
});
this.logger.info('Invoking exporter "main" function...');
try {
files = exporter.main(sections, staticInputs, config.extensionConfig);
} catch (e) {
this.logger.error(`Exporter failed: ${e.toString()}`);
throw e;
}
// If it returns a string, just put a single file
if (typeof files === 'string') {
return this.blobClient.putFile(`${name}.lua`, files);
} else { // filename -> content
var artifact = this.blobClient.createArtifact(name),
objects = {};
Object.keys(files).forEach(key => {
if (BlobConfig.hashRegex.test(files[key])) {
objects[key] = files[key];
delete files[key];
}
});
return artifact.addFiles(files)
.then(() => artifact.addObjectHashes(objects))
.then(() => artifact.save());
}
});
};
Export.prototype.createCodeSections = function (children) {
// Convert opNodes' jobs to the nested operations
var opNodes,
nodes;
return this.unpackJobs(children)
.then(_nodes => {
nodes = _nodes;
opNodes = nodes
.filter(node => this.isMetaTypeOf(node, this.META.Operation));
// Sort the connections to come first
nodes
.map(node => [
node,
this.isMetaTypeOf(node, this.META.Transporter) ? -1 : 1
])
.sort((a, b) => a[1] < b[1] ? -1 : 1);
return Q.all(nodes.map(node => this.registerNode(node)));
})
.then(() => Q.all(opNodes
.filter(n => {
var id = this.core.getPath(n);
return !this.isInputOp[id];
})
.map(node => this.createOperation(node)))
)
.then(operations => {
var opDict = {},
firstOpIds;
firstOpIds = opNodes.map(n => this.core.getPath(n))
.filter(id => !this._incomingCnts[id]);
operations.forEach(op => opDict[op.id] = op);
// Toposort!
return this.sortOperations(opDict, firstOpIds);
})
.then(operations => this.generateCodeSections(operations))
.fail(err => this.logger.error(err));
};
Export.prototype.unpackJobs = function (nodes) {
return Q.all(
nodes.map(node => {
if (!this.isMetaTypeOf(node, this.META.Job)) {
return node;
}
return this.core.loadChildren(node)
.then(children =>
children.find(c => this.isMetaTypeOf(c, this.META.Operation))
);
})
);
};
Export.prototype.sortOperations = function (operationDict, opIds) {
var nextIds = [],
sorted = opIds,
dstIds,
id;
if (!opIds.length) {
return [];
}
// Decrement all next ops
dstIds = opIds.map(id => this._nextOps[id])
.reduce((l1, l2) => l1.concat(l2), []);
for (var i = dstIds.length; i--;) {
id = dstIds[i];
if (--this._incomingCnts[id] === 0) {
nextIds.push(id);
}
}
// append
return sorted
.map(id => operationDict[id])
.filter(op => !!op)
.concat(this.sortOperations(operationDict, nextIds));
};
Export.prototype.generateCodeSections = function(sortedOps) {
// Create the code sections:
// - operation definitions
// - pipeline definition
// - main
var code = {},
baseIds = [],
outputOps = [],
mainOps = [];
// Define the operation functions...
code.operations = {};
for (var i = 0; i < sortedOps.length; i++) {
if (this.isInputOp[sortedOps[i].id]) {
continue;
}
if (!this.isOutputOp[sortedOps[i].id]) {
if (!baseIds.includes(sortedOps[i].baseId)) { // new definition
code.operations[sortedOps[i].basename] = this.defineOperationFn(sortedOps[i]);
baseIds.push(sortedOps[i].baseId);
}
mainOps.push(sortedOps[i]);
} else {
outputOps.push(sortedOps[i]);
}
}
// Define the pipeline function
code.pipelines = this.definePipelineFn(mainOps, outputOps);
// Define the serializers/deserializers
this.addCodeSerializers(code);
// Define the main input names
code.pipelineName = Object.keys(code.pipelines)[0];
code.pipelineInputNames = Object.keys(this.isInputOp).map(id => this._nameFor[id]);
// Add custom class definitions
this.addCustomClasses(code);
// Add custom layer definitions
this.addCustomLayers(code);
return code;
};
// expose this utility function to format extensions
var indent = Export.prototype.indent = function(text, spaces) {
spaces = spaces || 3;
return text.replace(/^/mg, new Array(spaces+1).join(' '));
};
Export.prototype.defineOperationFn = function(operation) {
var lines = [],
args = operation.inputNames || [];
// Create the function definition
args.unshift('attributes');
// Add the refs to the end
args = args.concat(operation.refNames);
args = args.join(', ');
lines.push(`local function ${operation.basename}(${args})`);
lines.push(indent(operation.code));
lines.push('end');
return lines.join('\n');
};
Export.prototype.definePipelineFn = function(sortedOps, outputOps) {
var inputArgs = Object.keys(this.isInputOp).map(id => this._nameFor[id]),
name = this.core.getAttribute(this.activeNode, 'name'),
safename = getUniqueName(name, this._opBaseNames),
results = [],
result = {},
returnStat,
fnbody;
// Call each function in order, with the respective attributes, etc
fnbody = sortedOps.map(op => this.getOpInvocation(op)).join('\n');
// Create the return statement
results.push('\n\nresults = {}');
outputOps.map(op => this.getOutputPair(op))
.forEach(pair => results.push(`results['${pair[0]}'] = ${pair[1]}`));
results.push('return results');
returnStat = results.join('\n');
// Merge the fnbody, return statement and the function def
result[safename] = `local function ${safename} (${inputArgs.join(', ')})\n` +
`${indent(fnbody + returnStat)}\nend`;
return result;
};
Export.prototype.getOutputPair = function(operation) {
var input = operation.inputValues[0].slice(),
value;
// Get the src operation name and data value name
input[0] += '_results';
value = input.join('.');
return [this._nameFor[operation.id], value];
};
Export.prototype.addCodeSerializers = function(sections) {
var loadNodes = {},
saveNodes = {};
// Add the serializer fn names for each input
sections.serializerFor = {};
sections.deserializerFor = {};
Object.keys(this.isOutputOp).map(id => {
var name = this._nameFor[id];
sections.serializerFor[name] = `__save['${name}']`;
});
// Add the serializer definitions
Object.keys(this.isInputOp).forEach(id => {
var node = this.inputNode[id],
name = this._nameFor[id];
loadNodes[id] = node;
sections.deserializerFor[name] = `__load['${this._nameFor[id]}']`;
});
sections.deserializers = this.createTorchFnDict(
'__load',
loadNodes,
'deserialize',
'path'
);
// Add the deserializer definitions
Object.keys(this.outputDataToOpId).forEach(dataId => {
var opId = this.outputDataToOpId[dataId];
// The key is used for the output name resolution. The
// value is used for the serialization fn look-up. So,
// the key is the output operation id and the value is
// the data port connected to the output operation
saveNodes[opId] = this._portCache[this._srcIdFor[dataId]];
});
sections.serializers = this.createTorchFnDict(
'__save',
saveNodes,
'serialize',
'path, data'
);
// Add a saveOutputs method for convenience
sections.serializeOutputsDef = [
'local function __saveOutputs(data)',
indent(Object.keys(this.isOutputOp).map(id => {
var name = this._nameFor[id];
return [
`print('saving ${name}...')`,
`${sections.serializerFor[name]}('${name}', data['${name}'])`
].join('\n');
}).join('\n')),
'end'
].join('\n');
sections.serializeOutputs = '__saveOutputs(outputs)';
};
Export.prototype.createTorchFnDict = function(name, nodeDict, attr, args) {
return [
`local ${name} = {}`,
Object.keys(nodeDict).map(id => {
var node = nodeDict[id];
return [
`${name}['${this._nameFor[id]}'] = function(${args})`,
indent(this.core.getAttribute(node, attr)),
'end'
].join('\n');
}).join('\n')
].join('\n');
};
Export.prototype.addCustomClasses = function(sections) {
var metaDict = this.core.getAllMetaNodes(this.rootNode),
isClass,
metanodes,
classNodes,
inheritanceLvl = {};
this.logger.info('Creating custom layer file...');
metanodes = Object.keys(metaDict).map(id => metaDict[id]);
isClass = this.getTypeDictFor('Complex', metanodes);
// Store the dependencies for each class
sections.classDependencies = {};
classNodes = metanodes.filter(node => {
var base = this.core.getBase(node),
baseId,
deps = [],
name,
count = 1;
// Count the sets back to a class node
while (base) {
deps.push(this.core.getAttribute(base, 'name'));
baseId = this.core.getPath(base);
if (isClass[baseId]) {
inheritanceLvl[this.core.getPath(node)] = count;
name = this.core.getAttribute(node, 'name');
sections.classDependencies[name] = deps;
return true;
}
base = this.core.getBase(base);
count++;
}
return false;
});
// Get the code definitions for each
sections.classes = {};
classNodes
.sort((a, b) => {
var aId = this.core.getPath(a),
bId = this.core.getPath(b);
return inheritanceLvl[aId] > inheritanceLvl[bId];
})
.forEach(node => {
var name = this.core.getAttribute(node, 'name'),
code = this.core.getAttribute(node, 'code');
sections.classes[name] = code;
});
// order classes by dependency
sections.orderedClasses = Object.keys(sections.classes)
.sort((a, b) => {
// if a depends on b, switch them (return 1)
if (sections.classDependencies[a].includes(b)) {
return 1;
}
return -1;
});
};
Export.prototype.addCustomLayers = function(sections) {
var metaDict = this.core.getAllMetaNodes(this.rootNode),
isCustomLayer,
metanodes,
customLayers;
this.logger.info('Creating custom layer file...');
metanodes = Object.keys(metaDict).map(id => metaDict[id]);
isCustomLayer = this.getTypeDictFor('CustomLayer', metanodes);
customLayers = metanodes.filter(node =>
this.core.getMixinPaths(node).some(id => isCustomLayer[id]));
// Get the code definitions for each
sections.layers = {};
customLayers
.map(layer => [
this.core.getAttribute(layer, 'name'),
this.core.getAttribute(layer, 'code')
])
.forEach(pair => sections.layers[pair[0]] = pair[1]);
};
Export.prototype.getTypeDictFor = function (name, metanodes) {
var isType = {};
// Get all the custom layers
for (var i = metanodes.length; i--;) {
if (this.core.getAttribute(metanodes[i], 'name') === name) {
isType[this.core.getPath(metanodes[i])] = true;
}
}
return isType;
};
var toAttrString = function(attr) {
if (/^\d+\.?\d*$/.test(attr) || /^(true|false|nil)$/.test(attr)) {
return attr;
}
return `"${attr}"`;
};
Export.prototype.getOpInvocation = function(op) {
var lines = [],
attrs,
refInits = [],
args;
attrs = '{' +
Object.keys(op.attributes).map(key => `${key}=${toAttrString(op.attributes[key])}`)
.join(',') +
'}';
lines.push(`local ${op.name}_attrs = ${attrs}`);
args = (op.inputValues || [])
.map(val => val instanceof Array ? `${val[0]}_results.${val[1]}` : val);
args.unshift(op.name + '_attrs');
// Create the ref init functions
refInits = op.refs.map((code, index) => {
return [
`local function create_${op.refNames[index]}()`,
indent(code),
'end'
].join('\n');
});
lines = lines.concat(refInits);
args = args.concat(op.refNames.map(name => `create_${name}()`));
args = args.join(', ');
lines.push(`local ${op.name}_results = ${op.basename}(${args})`);
return lines.join('\n');
};
Export.prototype.getOutputName = function(node) {
var basename = this.core.getAttribute(node, 'saveName');
return getUniqueName(basename, this._outputNames, true);
};
Export.prototype.getVariableName = function (/*node*/) {
var c = Object.keys(this.isInputOp).length;
if (c !== 1) {
return `input${c}`;
}
return 'input';
};
Export.prototype.registerNode = function (node) {
if (this.isMetaTypeOf(node, this.META.Operation)) {
return this.registerOperation(node);
} else if (this.isMetaTypeOf(node, this.META.Transporter)) {
return this.registerTransporter(node);
}
};
var getUniqueName = function(namebase, takenDict, unsafeAllowed) {
var name,
i = 2,
isUnsafe = function(name) {
return !unsafeAllowed && RESERVED.test(name);
};
if (!unsafeAllowed) {
namebase = namebase.replace(/[^A-Za-z\d]/g, '_');
}
name = namebase;
// Get a unique operation name
while (takenDict[name] || isUnsafe(name)) {
name = namebase + '_' + i;
i++;
}
takenDict[name] = true;
return name;
};
Export.prototype.registerOperation = function (node) {
var name = this.core.getAttribute(node, 'name'),
id = this.core.getPath(node),
base = this.core.getBase(node),
baseId = this.core.getPath(base),
baseName = this.core.getAttribute(base, 'name');
// If it is an Input/Output operation, assign it a variable name
if (baseName === CONSTANTS.OP.INPUT) {
this.isInputOp[id] = node;
name = this.getVariableName(node);
} else if (baseName === CONSTANTS.OP.OUTPUT) {
this.isOutputOp[id] = node;
name = this.getOutputName(node);
} else {
// get a unique operation instance name
name = getUniqueName(name, this._instanceNames);
}
this._nameFor[id] = name;
// get a unique operation base name
if (!this._fnNameFor[baseId]) {
name = this.core.getAttribute(base, 'name');
name = getUniqueName(name, this._opBaseNames);
this._fnNameFor[baseId] = name;
}
// For operations, register all output data node names by path
return this.core.loadChildren(node)
.then(cntrs => {
var outputs = cntrs.find(n => this.isMetaTypeOf(n, this.META.Outputs)),
inputs = cntrs.find(n => this.isMetaTypeOf(n, this.META.Inputs));
return Q.all([inputs, outputs].map(cntr => this.core.loadChildren(cntr)));
})
.then(data => {
var inputs = data[0],
outputs = data[1];
// Get the input type
outputs.forEach(output => {
var dataId = this.core.getPath(output);
name = this.core.getAttribute(output, 'name');
this._dataNameFor[dataId] = name;
this._portCache[dataId] = output;
});
inputs.forEach(input =>
this._portCache[this.core.getPath(input)] = input
);
// Extra recording for input/output nodes in the pipeline
if (this.isInputOp[id]) {
this.inputNode[id] = outputs[0];
} else if (this.isOutputOp[id]) {
this.outputDataToOpId[this.core.getPath(inputs[0])] = id;
}
});
};
Export.prototype.registerTransporter = function (node) {
var outputData = this.core.getPointerPath(node, 'src'),
inputData = this.core.getPointerPath(node, 'dst'),
srcOpId = this.getOpIdFor(outputData),
dstOpId = this.getOpIdFor(inputData);
this._srcIdFor[inputData] = outputData;
// Store the next operation ids for the op id
if (!this._nextOps[srcOpId]) {
this._nextOps[srcOpId] = [];
}
this._nextOps[srcOpId].push(dstOpId);
// Increment the incoming counts for each dst op
this._incomingCnts[dstOpId] = this._incomingCnts[dstOpId] || 0;
this._incomingCnts[dstOpId]++;
};
Export.prototype.getOpIdFor = function (dataId) {
var ids = dataId.split('/'),
depth = ids.length;
ids.splice(this.activeNodeDepth - depth);
return ids.join('/');
};
// For each operation...
// - unpack the inputs from prev ops
// - add the attributes table (if used)
// - check for '\<attributes\>' in code
// - add the references
// - generate the code
// - replace the `return <thing>` w/ `<ref-name> = <thing>`
Export.prototype.createOperation = function (node) {
var id = this.core.getPath(node),
baseId = this.core.getPath(this.core.getBase(node)),
attrNames = this.core.getValidAttributeNames(node),
operation = {};
operation.name = this._nameFor[id];
operation.basename = this._fnNameFor[baseId];
operation.baseId = baseId;
operation.id = id;
operation.code = this.core.getAttribute(node, 'code');
operation.attributes = {};
for (var i = attrNames.length; i--;) {
if (!SKIP_ATTRS[attrNames[i]]) {
operation.attributes[attrNames[i]] = this.core.getAttribute(node, attrNames[i]);
}
}
// Get all the input names (and sources)
return this.core.loadChildren(node)
.then(containers => {
var inputs;
inputs = containers
.find(cntr => this.isMetaTypeOf(cntr, this.META.Inputs));
this.logger.info(`${operation.name} has ${containers.length} cntrs`);
return this.core.loadChildren(inputs);
})
.then(data => {
// Get the input names and sources
var inputNames = data.map(d => this.core.getAttribute(d, 'name')),
ids = data.map(d => this.core.getPath(d)),
srcIds = ids.map(id => this._srcIdFor[id]);
operation.inputNames = inputNames || [];
operation.inputValues = inputNames.map((name, i) => {
var id = srcIds[i],
srcDataName = this._dataNameFor[id],
srcOpId = this.getOpIdFor(id),
srcOpName = this._nameFor[srcOpId];
if (this.isInputOp[srcOpId]) {
return this._nameFor[srcOpId];
} else {
return [srcOpName, srcDataName];
}
});
return operation;
})
.then(operation => {
// For each reference, run the plugin and retrieve the generated code
operation.refNames = [];
if (!this.isInputOp[operation.id]) {
operation.refNames = this.core.getPointerNames(node)
.filter(name => name !== 'base');
}
var refs = operation.refNames
.map(ref => [ref, this.core.getPointerPath(node, ref)]);
return Q.all(
refs.map(pair => this.genPtrSnippet.apply(this, pair))
);
})
.then(codeFiles => {
operation.refs = codeFiles;
return operation;
});
};
Export.prototype.genPtrSnippet = function (ptrName, pId) {
return this.getPtrCodeHash(pId)
.then(hash => this.blobClient.getObjectAsString(hash));
};
Export.prototype.createHeader = function (title, length) {
var len;
title = ` ${title} `;
length = length || HEADER_LENGTH;
len = Math.max(
Math.floor((length - title.length)/2),
2
);
return [
'',
title,
''
].join(new Array(len+1).join('-')) + '\n';
};
Export.prototype.genOperationCode = function (operation) {
var header = this.createHeader(`"${operation.name}" Operation`),
codeParts = [],
body = [];
codeParts.push(header);
codeParts.push(`local ${operation.name}_results`);
codeParts.push('do');
if (operation.inputs.length) {
body.push(operation.inputs.join('\n'));
}
if (operation.refs.length) {
body.push(operation.refs.join('\n'));
}
body.push(operation.code);
codeParts.push(indent(body.join('\n')));
codeParts.push('end');
codeParts.push('');
operation.code = codeParts.join('\n');
return operation;
};
_.extend(Export.prototype, PtrCodeGen.prototype);
// Extra utilities for export types
Export.prototype.INIT_CLASSES_FN = '__init_classes';
Export.prototype.INIT_LAYERS_FN = '__init_layers';
Export.prototype.getAllDefinitions = function (sections) {
var code = [],
classes,
initClassFn,
initLayerFn;
classes = sections.orderedClasses
// Create fns from the classes
.map(name => this.indent(sections.classes[name])).join('\n');
initClassFn = [
`local function ${this.INIT_CLASSES_FN}()`,
this.indent(classes),
'end'
].join('\n');
code = code.concat(initClassFn);
// wrap the layers in a function
initLayerFn = [
`local function ${this.INIT_LAYERS_FN}()`,
this.indent(_.values(sections.layers).join('\n\n')),
'end'
].join('\n');
code = code.concat(initLayerFn);
// Add operation fn definitions
code = code.concat(_.values(sections.operations));
code = code.concat(_.values(sections.pipelines));
// define deserializers, serializers
code.push(sections.deserializers);
code.push(sections.serializers);
code.push(this.getDeepforgeObject());
code.push('deepforge.initialize()');
code.push(sections.serializeOutputsDef);
return code.join('\n\n');
};
Export.prototype.getDeepforgeObject = function (content) {
content = content || {};
content.initCode = content.initCode || `${this.INIT_CLASSES_FN}()\n${' '}${this.INIT_LAYERS_FN}()`;
return DeepForgeTpl(content);
};
return Export;
});
-47
Ver Arquivo
@@ -1,47 +0,0 @@
-- Instantiate the deepforge object
deepforge = {}
function deepforge.initialize()
require 'nn'
require 'rnn'
<%= initCode %>
end
-- Graph support
torch.class('deepforge.Graph')
function deepforge.Graph:__init(name)
-- nop
end
torch.class('deepforge._Line')
function deepforge._Line:__init(graphId, name, opts)
-- nop
end
function deepforge._Line:add(x, y)
-- nop
end
function deepforge.Graph:line(name, opts)
return deepforge._Line(self.id, name, opts)
end
-- Image support
function deepforge.image(name, tensor)
-- nop
end
torch.class('deepforge.Image')
function deepforge.Image:__init(name, tensor)
-- nop
end
function deepforge.Image:update(tensor)
-- nop
end
function deepforge.Image:title(name)
-- nop
end
-13
Ver Arquivo
@@ -1,13 +0,0 @@
/* globals define*/
// The supported export formats and metadata
define([
'./formats/cli/cli'
], function(
Format0
) {
return {
'Basic CLI': Format0
};
});
-21
Ver Arquivo
@@ -1,21 +0,0 @@
<% // Add default format
formats.unshift({ name: 'cli', main: 'cli.js', displayName: 'Basic CLI' })
%>
/* globals define*/
// The supported export formats and metadata
define([
<%= formats.map(function(format) {
return ' \'./formats/' + format.name + '/' +
path.basename(format.main.replace(/\.js$/, '')) + '\''
})
.join(',\n') %>
], function(
<%= formats.map(function(f, index) { return ' Format' + index; }).join(',\n') %>
) {
return {
<%= formats.map(function(f, index) {
return ' \'' + f.displayName + '\': Format' + index;
}).join(',\n') %>
};
});
-103
Ver Arquivo
@@ -1,103 +0,0 @@
/*globals define*/
// Simple torch cli for the given pipeline
define([
], function(
) {
var TOBOOLEAN =
`local function toboolean(str)
if str == 'true' then
return true
elseif str == 'false' then
return false
end
end`;
var CliExporter = {};
CliExporter.deserializersFromString = function(sections) {
var hasBool = false;
// Add serializers given cli string input
Object.keys(this.isInputOp).forEach(id => {
var node = this.inputNode[id],
base = this.core.getBase(node),
type = this.core.getAttribute(base, 'name'),
name = this._nameFor[id];
if (type === 'boolean') {
hasBool = true;
sections.deserializerFor[name] = 'toboolean';
} else if (type === 'number') {
sections.deserializerFor[name] = 'tonumber';
} else if (type === 'string') {
sections.deserializerFor[name] = 'tostring';
}
});
if (hasBool) {
sections.deserializers += '\n' + TOBOOLEAN;
}
return sections;
};
CliExporter.main = function (sections, staticInputs) {
var code = [];
// Update deserializers for cli input
this.deserializersFromString(sections);
// Define all the operations, pipelines, etc
// 'getAllDefinitions' is provided as part of the public api
code.push(this.getAllDefinitions(sections));
// Command line specific stuff
var files = {},
main,
args,
staticNames = staticInputs.map(input => input.name),
varDefs,
index = 1;
// Create some names for the inputs
args = sections.pipelineInputNames.map(name => `${sections.deserializerFor[name]}(${name})`);
main = `local outputs = ${sections.pipelineName}(${args.join(', ')})`;
// Grab the args from the cli
code.push(sections.pipelineInputNames.map((name, index) => {
return `local ${name} = arg[${index + 1}]`;
}).join('\n'));
// Add the hash for each of the static inputs and reference them
staticInputs.forEach(input => {
files[`res/${input.name}`] = input.hash;
});
varDefs = staticNames.map(name => {
return `local ${name} = './res/${name}'`;
});
// Grab the remaining args from the cli
varDefs = varDefs.concat(sections.pipelineInputNames.map(name => {
if (!staticNames.includes(name)) {
return `local ${name} = arg[${index++}]`;
}
}));
// Add the main fn
code.push(varDefs.join('\n'));
code.push(main);
// Save outputs to disk
code.push(sections.serializeOutputs);
files['init.lua'] = code.join('\n\n');
// if no extra assets, just return the main file
return staticInputs.length ? files : files['init.lua'];
};
return CliExporter;
});
-14
Ver Arquivo
@@ -1,14 +0,0 @@
{
"id": "Export",
"name": "Export",
"version": "1.0.0",
"description": "",
"icon": {
"class": "glyphicon glyphicon-cog",
"src": ""
},
"disableServerSideExecution": false,
"disableBrowserSideExecution": false,
"writeAccessRequired": false,
"configStructure": []
}
-7
Ver Arquivo
@@ -1,7 +0,0 @@
local function toboolean(str)
if str == 'true' then
return true
elseif str == 'false' then
return false
end
end
@@ -49,11 +49,6 @@ define([
this.LayerDict = createLayerDict(this.core, this.META);
this.uniqueId = 2;
this.varnames = {net: true};
this.definitions = [
'require \'nn\'',
'require \'rnn\''
];
return PluginBase.prototype.main.apply(this, arguments);
};
@@ -76,6 +71,11 @@ define([
result = {},
code = '';
this.definitions = [
'import torch',
'import torch.nn as nn'
];
// Add an index to each layer
layers.forEach((l, index) => l[INDEX] = index);
@@ -85,6 +85,7 @@ define([
code += this.genLayerDefinitions(layers);
}
// TODO: Define the network w/ 'class ARCHITECTURE_NAME'
this.logger.debug('Generating architecture code...');
code += this.genArchCode(layers);
this.logger.debug('Prepending hoisted code...');
@@ -130,7 +131,7 @@ define([
var args = this.createArgString(layer),
def = `nn.${layer.name}${args}`,
type = layer.base.base.name,
memberIds,
addedIds,
node,
name,
children,
@@ -141,32 +142,28 @@ define([
// each nested architecture's code to the given container
if (type === 'Container') {
// Get the members of the 'addLayers' set
memberIds = {};
addedIds = {};
id = layer[SimpleNodeConstants.NODE_PATH];
node = this._nodeCache[id];
this.core.getMemberPaths(node, Constants.CONTAINED_LAYER_SET)
.forEach(id => memberIds[id] = true);
.forEach(id => addedIds[id] = true);
// Get the (sorted) children
children = layer[SimpleNodeConstants.CHILDREN]
.map(child => { // get (child, index) tuples
var index = null;
var index;
id = child[SimpleNodeConstants.NODE_PATH];
if (memberIds[id]) {
index = this.core.getMemberRegistry(node,
Constants.CONTAINED_LAYER_SET, id, Constants.CONTAINED_LAYER_INDEX);
}
index = this.core.getMemberRegistry(node, Constants.CONTAINED_LAYER_SET, id, Constants.CONTAINED_LAYER_INDEX);
return [child, index];
})
.filter(pair => pair[1] !== null) // remove non-members
.filter(pair => pair[1] !== undefined) // remove non-members
.sort((a, b) => a[1] < b[1] ? -1 : 1) // sort by 'index'
.map(pair => pair[0]);
var addedLayerDefs = '',
firstLayer;
for (var i = 0; i < children.length; i++) {
id = children[i][SimpleNodeConstants.NODE_PATH];
// Get the children!
@@ -0,0 +1,344 @@
/*globals define, _*/
/*jshint node:true, browser:true*/
/**
* Generated by PluginGenerator 1.7.0 from webgme on Sat Jun 04 2016 18:01:54 GMT-0500 (CDT).
* A plugin that inherits from the PluginBase. To see source code documentation about available
* properties and methods visit %host%/docs/source/PluginBase.html.
*/
define([
'text!./metadata.json',
'plugin/PluginBase',
'deepforge/plugin/PtrCodeGen',
'q'
], function (
pluginMetadata,
PluginBase,
PtrCodeGen,
Q
) {
'use strict';
pluginMetadata = JSON.parse(pluginMetadata);
var HEADER_LENGTH = 60;
/**
* Initializes a new instance of GenerateExecFile.
* @class
* @augments {PluginBase}
* @classdesc This class represents the plugin GenerateExecFile.
* @constructor
*/
var GenerateExecFile = function () {
// Call base class' constructor.
PluginBase.call(this);
this.pluginMetadata = pluginMetadata;
this._srcIdFor = {}; // input path -> output data node path
this._nameFor = {}; // input path -> opname
this._dataNameFor = {};
this._opNames = {};
// topo sort stuff
this._nextOps = {};
this._incomingCnts = {};
this._operations = {};
this.activeNodeId = null;
this.activeNodeDepth = null;
};
/**
* Metadata associated with the plugin. Contains id, name, version, description, icon, configStructue etc.
* This is also available at the instance at this.pluginMetadata.
* @type {object}
*/
GenerateExecFile.metadata = pluginMetadata;
// Prototypical inheritance from PluginBase.
GenerateExecFile.prototype = Object.create(PluginBase.prototype);
GenerateExecFile.prototype.constructor = GenerateExecFile;
/**
* Main function for the plugin to execute. This will perform the execution.
* Notes:
* - Always log with the provided logger.[error,warning,info,debug].
* - Do NOT put any user interaction logic UI, etc. inside this method.
* - callback always has to be called even if error happened.
*
* @param {function(string, plugin.PluginResult)} callback - the result callback
*/
GenerateExecFile.prototype.main = function (callback) {
// Get all the children and call generate exec file
this.activeNodeId = this.core.getPath(this.activeNode);
this.activeNodeDepth = this.activeNodeId.split('/').length + 1;
if (this.isMetaTypeOf(this.activeNode, this.META.Execution)) {
this.activeNodeDepth++;
}
return this.core.loadChildren(this.activeNode)
.then(nodes => this.createExecFile(nodes))
.then(code => this.blobClient.putFile('init.lua', code))
.then(hash => {
this.result.addArtifact(hash);
this.result.setSuccess(true);
callback(null, this.result);
})
.fail(err => callback(err));
};
GenerateExecFile.prototype.createExecFile = function (children) {
// Convert opNodes' jobs to the nested operations
var opNodes,
nodes;
return this.unpackJobs(children)
.then(_nodes => {
nodes = _nodes;
opNodes = nodes
.filter(node => this.isMetaTypeOf(node, this.META.Operation));
return Q.all(nodes.map(node => this.registerNameAndData(node)));
})
.then(() => Q.all(opNodes.map(node => this.createOperation(node))))
.then(operations => {
var nextIds = opNodes.map(n => this.core.getPath(n))
.filter(id => !this._incomingCnts[id]);
operations.forEach(op => this._operations[op.id] = op);
// Toposort and concat!
return this.combineOpNodes(nextIds);
})
.fail(err => this.logger.error(err));
};
GenerateExecFile.prototype.unpackJobs = function (nodes) {
return Q.all(
nodes.map(node => {
if (!this.isMetaTypeOf(node, this.META.Job)) {
return node;
}
return this.core.loadChildren(node)
.then(children =>
children.find(c => this.isMetaTypeOf(c, this.META.Operation))
);
})
);
};
GenerateExecFile.prototype.combineOpNodes = function (opIds) {
var nextIds = [],
dstIds,
code,
id;
// Combine all nodes with incoming cnts of 0
code = opIds.map(id => this._operations[id].code).join('\n');
// Decrement all next ops
dstIds = opIds.map(id => this._nextOps[id])
.reduce((l1, l2) => l1.concat(l2), []);
for (var i = dstIds.length; i--;) {
id = dstIds[i];
if (--this._incomingCnts[id] === 0) {
nextIds.push(id);
}
}
// append
return [
code,
nextIds.length ? this.combineOpNodes(nextIds) : ''
].join('\n');
};
GenerateExecFile.prototype.registerNameAndData = function (node) {
var name = this.core.getAttribute(node, 'name'),
id = this.core.getPath(node),
basename = name,
i = 2;
if (this.isMetaTypeOf(node, this.META.Operation)) {
// Get a unique operation name
while (this._opNames[name]) {
name = basename + '_' + i;
i++;
}
// register the unique name
this._opNames[name] = true;
this._nameFor[id] = name;
// For operations, register all output data node names by path
return this.core.loadChildren(node)
.then(cntrs => {
var cntr = cntrs.find(n => this.isMetaTypeOf(n, this.META.Outputs));
return this.core.loadChildren(cntr);
})
.then(outputs => {
outputs.forEach(output => {
var dataId = this.core.getPath(output);
name = this.core.getAttribute(output, 'name');
this._dataNameFor[dataId] = name;
});
});
// For each input data node, register the associated output id
} else if (this.isMetaTypeOf(node, this.META.Transporter)) {
var outputData = this.core.getPointerPath(node, 'src'),
inputData = this.core.getPointerPath(node, 'dst'),
srcOpId = this.getOpIdFor(outputData),
dstOpId = this.getOpIdFor(inputData);
this._srcIdFor[inputData] = outputData;
// Store the next operation ids for the op id
if (!this._nextOps[srcOpId]) {
this._nextOps[srcOpId] = [];
}
this._nextOps[srcOpId].push(dstOpId);
// Increment the incoming counts for each dst op
this._incomingCnts[dstOpId] = this._incomingCnts[dstOpId] || 0;
this._incomingCnts[dstOpId]++;
}
};
GenerateExecFile.prototype.getOpIdFor = function (dataId) {
var ids = dataId.split('/'),
depth = ids.length;
ids.splice(this.activeNodeDepth - depth);
return ids.join('/');
};
// For each operation...
// - unpack the inputs from prev ops
// - add the attributes table (if used)
// - check for '\<attributes\>' in code
// - add the references
// - generate the code
// - replace the `return <thing>` w/ `<ref-name> = <thing>`
GenerateExecFile.prototype.createOperation = function (node) {
var id = this.core.getPath(node),
operation = {};
operation.name = this._nameFor[id];
operation.id = id;
operation.code = this.core.getAttribute(node, 'code');
// Update the 'code' attribute
// Change the last return statement to assign the results to a table
operation.code = this.assignResultToVar(operation.code,
`${operation.name}_results`);
// Get all the input names (and sources)
return this.core.loadChildren(node)
.then(containers => {
var inputs;
inputs = containers
.find(cntr => this.isMetaTypeOf(cntr, this.META.Inputs));
this.logger.info(`${name} has ${containers.length} cntrs`);
return this.core.loadChildren(inputs);
})
.then(data => {
// Get the input names and sources
var inputNames = data.map(d => this.core.getAttribute(d, 'name')),
ids = data.map(d => this.core.getPath(d)),
srcIds = ids.map(id => this._srcIdFor[id]);
operation.inputs = inputNames.map((name, i) => {
var id = srcIds[i],
srcDataName = this._dataNameFor[id],
srcOpId = this.getOpIdFor(id),
srcOpName = this._nameFor[srcOpId];
return `local ${name} = ${srcOpName}_results.${srcDataName}`;
});
return operation;
})
.then(operation => {
// For each reference, run the plugin and retrieve the generated code
operation.refNames = this.core.getPointerNames(node)
.filter(name => name !== 'base');
var refs = operation.refNames
.map(ref => [ref, this.core.getPointerPath(node, ref)]);
return Q.all(
refs.map(pair => this.genPtrSnippet.apply(this, pair))
);
})
.then(codeFiles => {
operation.refs = codeFiles;
this.genOperationCode(operation);
return operation;
});
};
GenerateExecFile.prototype.genPtrSnippet = function (ptrName, pId) {
return this.getPtrCodeHash(pId)
.then(hash => this.blobClient.getObjectAsString(hash))
.then(code => this.createHeader(`creating ${ptrName}`, 40) + '\n' +
this.assignResultToVar(code, ptrName));
};
GenerateExecFile.prototype.createHeader = function (title, length) {
var len;
title = ` ${title} `;
length = length || HEADER_LENGTH;
len = Math.max(
Math.floor((length - title.length)/2),
2
);
return [
'',
title,
''
].join(new Array(len+1).join('-')) + '\n';
};
GenerateExecFile.prototype.genOperationCode = function (operation) {
var header = this.createHeader(`"${operation.name}" Operation`),
codeParts = [];
codeParts.push(header);
if (operation.inputs.length) {
codeParts.push(operation.inputs.join('\n'));
}
if (operation.refs.length) {
codeParts.push(operation.refs.join('\n'));
}
codeParts.push(operation.code);
codeParts.push('');
operation.code = codeParts.join('\n');
return operation;
};
GenerateExecFile.prototype.assignResultToVar = function (code, name) {
var i = code.lastIndexOf('return');
return code.substring(0, i) +
code.substring(i)
.replace('return', `local ${name} = `);
};
_.extend(GenerateExecFile.prototype, PtrCodeGen.prototype);
return GenerateExecFile;
});
@@ -1,6 +1,6 @@
{
"id": "GenerateJob",
"name": "GenerateJob",
"id": "GenerateExecFile",
"name": "Generate Execution File",
"version": "0.1.0",
"description": "",
"icon": {
@@ -11,4 +11,4 @@
"disableBrowserSideExecution": false,
"writeAccessRequired": false,
"configStructure": []
}
}
@@ -1,194 +0,0 @@
/*globals define*/
/*jshint node:true, browser:true*/
define([
'plugin/GenerateArchitecture/GenerateArchitecture/GenerateArchitecture',
'SimpleNodes/Constants',
'text!./metadata.json',
'q',
'fs',
'path',
'child_process',
'rimraf'
], function (
PluginBase,
SimpleNodeConstants,
pluginMetadata,
Q,
fs,
path,
childProcess,
rm_rf
) {
'use strict';
pluginMetadata = JSON.parse(pluginMetadata);
/**
* Initializes a new instance of ValidateArchitecture.
* @class
* @augments {PluginBase}
* @classdesc This class represents the plugin ValidateArchitecture.
* @constructor
*/
var TMP_DIR = '/tmp',
spawn = childProcess.spawn,
GET_ARG_INDEX = /argument #([0-9]+) to/,
TORCH_INSTALLED = true;
var ValidateArchitecture = function () {
// Call base class' constructor.
PluginBase.call(this);
this.pluginMetadata = pluginMetadata;
};
/**
* Metadata associated with the plugin. Contains id, name, version, description, icon, configStructue etc.
* This is also available at the instance at this.pluginMetadata.
* @type {object}
*/
ValidateArchitecture.metadata = pluginMetadata;
// Prototypical inheritance from PluginBase.
ValidateArchitecture.prototype = Object.create(PluginBase.prototype);
ValidateArchitecture.prototype.constructor = ValidateArchitecture;
ValidateArchitecture.prototype.main = function (callback) {
var name = this.core.getAttribute(this.activeNode, 'name');
this._callback = callback;
// make the tmp dir
this._tmpFileId = path.join(TMP_DIR, `${name}_${Date.now()}`);
fs.mkdir(this._tmpFileId, err => {
if (err) throw err;
return PluginBase.prototype.main.call(this, callback);
});
};
ValidateArchitecture.prototype.createOutputFiles = function (tree) {
var layers = tree[SimpleNodeConstants.CHILDREN],
tests = [],
id;
if (!TORCH_INSTALLED) {
return this.validationFinished();
}
// Generate code for each layer
this.layerName = {};
for (var i = layers.length; i--;) {
id = layers[i][SimpleNodeConstants.NODE_PATH];
this.layerName[id] = layers[i].name;
tests.push([id, this.createLayerTestCode(layers[i])]);
}
// Run each code snippet
this.validateLayers(tests)
.then(errors => this.validationFinished(errors))
.fail(err => this.logger.error(`validation failed: ${err}`));
};
ValidateArchitecture.prototype.validationFinished = function (errors) {
if (!TORCH_INSTALLED) {
this.logger.warn('Torch is not installed. Architecture validation is not supported.');
} else {
this.logger.info(`found ${errors.length} validation errors`);
}
this.createMessage(null, {
errors: TORCH_INSTALLED ? errors : null
});
this.result.setSuccess(true);
this._callback(null, this.result);
};
ValidateArchitecture.prototype.createLayerTestCode = function (layer) {
var customLayerDefs = this.genLayerDefinitions([layer]);
return this.definitions.concat([
customLayerDefs,
this.createLayer(layer)
]).join('\n');
};
ValidateArchitecture.prototype.validateLayers = function (layerTests) {
return Q.all(layerTests.map(layer => this.validateLayer(layer[0], layer[1])))
.then(results => Q.nfcall(rm_rf, this._tmpFileId)
.then(() => results.filter(result => !!result))
);
};
ValidateArchitecture.prototype.validateLayer = function (id, code) {
var deferred = Q.defer(),
tmpPath = path.join(this._tmpFileId, id.replace(/[^a-zA-Z\d]+/g, '_'));
if (!TORCH_INSTALLED) {
deferred.resolve(null);
} else {
// Write to a temp file
fs.writeFile(tmpPath, code, err => {
var job,
stderr = '',
stdout = '';
if (err) {
return deferred.reject(`Could not create tmp file at ${tmpPath}: ${err}`);
}
// Run the file
job = spawn('th', [tmpPath]);
job.stderr.on('data', data => stderr += data.toString());
job.stdout.on('data', data => stdout += data.toString());
job.on('error', err => {
if (err.code === 'ENOENT') {
TORCH_INSTALLED = false;
}
});
job.on('close', code => {
if (code === 0) {
deferred.resolve(null);
} else {
// If it errored, clean the error and return it
deferred.resolve(this.parseError(id, stderr));
}
});
});
}
return deferred.promise;
};
ValidateArchitecture.prototype.parseError = function (id, stderr) {
var msg = stderr
.split('\n').shift() // first line
.replace(/^[^:]*: /, '') // remove the file path
.replace(/ at [^ ]*\)/, ')') // remove last line number
.replace(/ to '\?'/, ''); // remove unknown symbol
// convert 'bad argument #[num]' to the argument name
if (msg.indexOf('bad argument') === 0) {
var layerName = this.layerName[id],
args = this.LayerDict[layerName].args,
argIndex = +(stderr.match(GET_ARG_INDEX)[1]),
argName = args[argIndex-1].name;
// FIXME: This is not the correct index...
// This is the index for the incorrect argument passed to the
// tensor...
msg = msg.replace(`#${argIndex}`, `"${argName}"`);
}
return {
id: id,
msg: msg
};
};
ValidateArchitecture.prototype._saveOutput = function () {};
// for testing
ValidateArchitecture.prototype.setTorchInstalled = function (value) {
TORCH_INSTALLED = !!value;
};
return ValidateArchitecture;
});
@@ -1,14 +0,0 @@
{
"id": "ValidateArchitecture",
"name": "ValidateArchitecture",
"version": "0.1.0",
"description": "",
"icon": {
"class": "glyphicon glyphicon-cog",
"src": ""
},
"disableServerSideExecution": false,
"disableBrowserSideExecution": true,
"writeAccessRequired": false,
"configStructure": []
}
Arquivo binário não exibido.
Arquivo binário não exibido.
Arquivo binário não exibido.
Arquivo binário não exibido.
+1 -1
Ver Arquivo
@@ -1 +1 @@
0.5.0
1.0.3
Arquivo binário não exibido.
+1 -1
Ver Arquivo
@@ -1 +1 @@
0.6.0
0.4.1
Arquivo binário não exibido.
@@ -7,16 +7,14 @@ define([
'deepforge/viz/panels/ThumbnailControl',
'js/NodePropertyNames',
'js/Utils/ComponentSettings',
'underscore',
'q'
'underscore'
], function (
Constants,
DeepForge,
ThumbnailControl,
nodePropertyNames,
ComponentSettings,
_,
Q
_
) {
'use strict';
@@ -38,7 +36,6 @@ define([
ThumbnailControl.call(this, options);
this._config = DEFAULT_CONFIG;
ComponentSettings.resolveWithWebGMEGlobal(this._config, this.getComponentId());
this.validateLayers = _.debounce(() => this.validateArchitecture(), 500);
};
_.extend(ArchEditorControl.prototype, ThumbnailControl.prototype);
@@ -206,7 +203,6 @@ define([
ArchEditorControl.prototype._initWidgetEventHandlers = function() {
ThumbnailControl.prototype._initWidgetEventHandlers.call(this);
this._widget.getCreateNewDecorator = this.getCreateNewDecorator.bind(this);
this._widget.insertLayer = this.insertLayer.bind(this);
};
ArchEditorControl.prototype.getCreateNewDecorator = function() {
@@ -216,63 +212,5 @@ define([
);
};
ArchEditorControl.prototype.insertLayer = function(layerBaseId, connId) {
var conn = this._client.getNode(connId),
parentId = conn.getParentId(),
layerId,
nextLayerId = conn.getPointer('dst').to,
connBaseId = conn.getBaseId(),
newConnId,
baseName = this._client.getNode(layerBaseId).getAttribute('name'),
prevLayerId = conn.getPointer('src').to,
srcName = this._client.getNode(prevLayerId).getAttribute('name'),
dstName = this._client.getNode(nextLayerId).getAttribute('name'),
msg = `Inserting ${baseName} layer between ${srcName} and ${dstName}`;
this._client.startTransaction(msg);
// Create the new layer
layerId = this._client.createNode({
parentId: parentId,
baseId: layerBaseId
});
// Connect the new layer to the previous dst of 'connId'
newConnId = this._client.createNode({
parentId: parentId,
baseId: connBaseId
});
this._client.setPointer(newConnId, 'src', layerId);
this._client.setPointer(newConnId, 'dst', nextLayerId);
// Change the dst of 'connId' to the new layer
this._client.setPointer(connId, 'dst', layerId);
this._client.completeTransaction();
};
ArchEditorControl.prototype._eventCallback = function() {
ThumbnailControl.prototype._eventCallback.apply(this, arguments);
this.validateLayers();
};
ArchEditorControl.prototype.validateArchitecture = function() {
var pluginId = 'ValidateArchitecture',
context = this._client.getCurrentPluginContext(pluginId);
this._logger.info('about to validate arch');
// Run the plugin in the browser (set namespace)
context.managerConfig.namespace = 'nn';
context.pluginConfig = {};
Q.ninvoke(this._client, 'runServerPlugin', pluginId, context)
.then(res => {
var results = res.messages[0].message;
if (results.errors !== null) {
this._widget.displayErrors(results.errors);
}
})
.fail(err => this._logger.warn(`Validation failed: ${err}`));
};
return ArchEditorControl;
});
@@ -1,55 +0,0 @@
/* globals define */
define([
'panels/PipelineIndex/PipelineIndexControl'
], function(
PipelineIndexControl
) {
var ArchIndexControl = function() {
PipelineIndexControl.apply(this, arguments);
};
ArchIndexControl.prototype = Object.create(PipelineIndexControl.prototype);
ArchIndexControl.prototype._getObjectDescriptor = function (nodeId) {
var node = this._client.getNode(nodeId),
base,
desc;
if (node) {
base = this._client.getNode(node.getBaseId());
desc = {
id: node.getId(),
name: node.getAttribute('name'),
parentId: node.getParentId(),
thumbnail: node.getAttribute('thumbnail'),
type: base.getAttribute('name')
};
}
return desc;
};
ArchIndexControl.prototype._initWidgetEventHandlers = function () {
this._widget.deletePipeline = id => {
var node = this._client.getNode(id),
name = node.getAttribute('name'),
msg = `Deleted "${name}" architecture`;
this._client.startTransaction(msg);
this._client.deleteNode(id);
this._client.completeTransaction();
};
this._widget.setName = (id, name) => {
var oldName = this._client.getNode(id).getAttribute('name'),
msg = `Renaming architecture: "${oldName}" -> "${name}"`;
if (oldName !== name && !/^\s*$/.test(name)) {
this._client.startTransaction(msg);
this._client.setAttribute(id, 'name', name);
this._client.completeTransaction();
}
};
};
return ArchIndexControl;
});

Alguns arquivos não foram exibidos porque demasiados arquivos foram alterados neste diff Mostrar Mais