Search in sources :

Example 6 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class PyDMLParserWrapper method createDMLProgram.

private static DMLProgram createDMLProgram(ProgramrootContext ast, String sourceNamespace) {
    DMLProgram dmlPgm = new DMLProgram();
    String namespace = (sourceNamespace != null && sourceNamespace.length() > 0) ? sourceNamespace : DMLProgram.DEFAULT_NAMESPACE;
    dmlPgm.getNamespaces().put(namespace, dmlPgm);
    // First add all the functions
    for (FunctionStatementContext fn : ast.functionBlocks) {
        FunctionStatementBlock functionStmtBlk = new FunctionStatementBlock();
        functionStmtBlk.addStatement(fn.info.stmt);
        try {
            dmlPgm.addFunctionStatementBlock(namespace, fn.info.functionName, functionStmtBlk);
        } catch (LanguageException e) {
            LOG.error("line: " + fn.start.getLine() + ":" + fn.start.getCharPositionInLine() + " cannot process the function " + fn.info.functionName);
            return null;
        }
    }
    // Then add all the statements
    for (StatementContext stmtCtx : ast.blocks) {
        Statement current = stmtCtx.info.stmt;
        if (current == null) {
            LOG.error("line: " + stmtCtx.start.getLine() + ":" + stmtCtx.start.getCharPositionInLine() + " cannot process the statement");
            return null;
        }
        // Ignore Newline logic
        if (current.isEmptyNewLineStatement()) {
            continue;
        }
        if (current instanceof ImportStatement) {
            // Handle import statements separately
            if (stmtCtx.info.namespaces != null) {
                // Add the DMLProgram entries into current program
                for (Map.Entry<String, DMLProgram> entry : stmtCtx.info.namespaces.entrySet()) {
                    // TODO handle namespace key already exists for different program value instead of overwriting
                    DMLProgram prog = entry.getValue();
                    if (prog != null && prog.getNamespaces().size() > 0) {
                        dmlPgm.getNamespaces().put(entry.getKey(), prog);
                    }
                    // Add dependent programs (handle imported script that also imports scripts)
                    for (Map.Entry<String, DMLProgram> dependency : entry.getValue().getNamespaces().entrySet()) {
                        String depNamespace = dependency.getKey();
                        DMLProgram depProgram = dependency.getValue();
                        if (dmlPgm.getNamespaces().get(depNamespace) == null) {
                            dmlPgm.getNamespaces().put(depNamespace, depProgram);
                        }
                    }
                }
            } else {
                LOG.error("line: " + stmtCtx.start.getLine() + ":" + stmtCtx.start.getCharPositionInLine() + " cannot process the import statement");
                return null;
            }
        }
        // Now wrap statement into individual statement block
        // merge statement will take care of merging these blocks
        dmlPgm.addStatementBlock(getStatementBlock(current));
    }
    // post-processing
    dmlPgm.hoistFunctionCallsFromExpressions();
    dmlPgm.mergeStatementBlocks();
    return dmlPgm;
}
Also used : LanguageException(org.apache.sysml.parser.LanguageException) FunctionStatementContext(org.apache.sysml.parser.pydml.PydmlParser.FunctionStatementContext) FunctionStatementBlock(org.apache.sysml.parser.FunctionStatementBlock) ImportStatement(org.apache.sysml.parser.ImportStatement) Statement(org.apache.sysml.parser.Statement) DMLProgram(org.apache.sysml.parser.DMLProgram) ImportStatement(org.apache.sysml.parser.ImportStatement) Map(java.util.Map) FunctionStatementContext(org.apache.sysml.parser.pydml.PydmlParser.FunctionStatementContext) StatementContext(org.apache.sysml.parser.pydml.PydmlParser.StatementContext)

Example 7 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class Explain method explain.

public static String explain(Program rtprog, ExplainCounts counts) {
    // counts number of instructions
    boolean sparkExec = OptimizerUtils.isSparkExecutionMode();
    if (counts == null) {
        counts = new ExplainCounts();
        countCompiledInstructions(rtprog, counts, !sparkExec, true, sparkExec);
    }
    StringBuilder sb = new StringBuilder();
    // create header
    sb.append("\nPROGRAM ( size CP/" + (sparkExec ? "SP" : "MR") + " = ");
    sb.append(counts.numCPInst);
    sb.append("/");
    sb.append(counts.numJobs);
    sb.append(" )\n");
    // explain functions (if exists)
    Map<String, FunctionProgramBlock> funcMap = rtprog.getFunctionProgramBlocks();
    if (funcMap != null && !funcMap.isEmpty()) {
        sb.append("--FUNCTIONS\n");
        // show function call graph
        if (!rtprog.getProgramBlocks().isEmpty() && rtprog.getProgramBlocks().get(0).getStatementBlock() != null) {
            sb.append("----FUNCTION CALL GRAPH\n");
            sb.append("------MAIN PROGRAM\n");
            DMLProgram prog = rtprog.getProgramBlocks().get(0).getStatementBlock().getDMLProg();
            FunctionCallGraph fgraph = new FunctionCallGraph(prog);
            sb.append(explainFunctionCallGraph(fgraph, new HashSet<String>(), null, 3));
        }
        // show individual functions
        for (Entry<String, FunctionProgramBlock> e : funcMap.entrySet()) {
            String fkey = e.getKey();
            FunctionProgramBlock fpb = e.getValue();
            if (fpb instanceof ExternalFunctionProgramBlock)
                sb.append("----EXTERNAL FUNCTION " + fkey + "\n");
            else {
                sb.append("----FUNCTION " + fkey + " [recompile=" + fpb.isRecompileOnce() + "]\n");
                for (ProgramBlock pb : fpb.getChildBlocks()) sb.append(explainProgramBlock(pb, 3));
            }
        }
    }
    // explain main program
    sb.append("--MAIN PROGRAM\n");
    for (ProgramBlock pb : rtprog.getProgramBlocks()) sb.append(explainProgramBlock(pb, 2));
    return sb.toString();
}
Also used : FunctionProgramBlock(org.apache.sysml.runtime.controlprogram.FunctionProgramBlock) ExternalFunctionProgramBlock(org.apache.sysml.runtime.controlprogram.ExternalFunctionProgramBlock) ExternalFunctionProgramBlock(org.apache.sysml.runtime.controlprogram.ExternalFunctionProgramBlock) DMLProgram(org.apache.sysml.parser.DMLProgram) FunctionCallGraph(org.apache.sysml.hops.ipa.FunctionCallGraph) FunctionProgramBlock(org.apache.sysml.runtime.controlprogram.FunctionProgramBlock) WhileProgramBlock(org.apache.sysml.runtime.controlprogram.WhileProgramBlock) ExternalFunctionProgramBlock(org.apache.sysml.runtime.controlprogram.ExternalFunctionProgramBlock) ForProgramBlock(org.apache.sysml.runtime.controlprogram.ForProgramBlock) IfProgramBlock(org.apache.sysml.runtime.controlprogram.IfProgramBlock) ProgramBlock(org.apache.sysml.runtime.controlprogram.ProgramBlock) ParForProgramBlock(org.apache.sysml.runtime.controlprogram.ParForProgramBlock) HashSet(java.util.HashSet)

Example 8 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class ParForDependencyAnalysisTest method runTest.

private void runTest(String scriptFilename, boolean expectedException) {
    boolean raisedException = false;
    try {
        // Tell the superclass about the name of this test, so that the superclass can
        // create temporary directories.
        int index = scriptFilename.lastIndexOf(".dml");
        String testName = scriptFilename.substring(0, index > 0 ? index : scriptFilename.length());
        TestConfiguration testConfig = new TestConfiguration(TEST_CLASS_DIR, testName, new String[] {});
        addTestConfiguration(testName, testConfig);
        loadTestConfiguration(testConfig);
        DMLConfig conf = new DMLConfig(getCurConfigFile().getPath());
        ConfigurationManager.setLocalConfig(conf);
        String dmlScriptString = "";
        HashMap<String, String> argVals = new HashMap<String, String>();
        // read script
        try (BufferedReader in = new BufferedReader(new FileReader(HOME + scriptFilename))) {
            String s1 = null;
            while ((s1 = in.readLine()) != null) dmlScriptString += s1 + "\n";
        }
        // parsing and dependency analysis
        ParserWrapper parser = ParserFactory.createParser(org.apache.sysml.api.mlcontext.ScriptType.DML);
        DMLProgram prog = parser.parse(DMLScript.DML_FILE_PATH_ANTLR_PARSER, dmlScriptString, argVals);
        DMLTranslator dmlt = new DMLTranslator(prog);
        dmlt.validateParseTree(prog);
    } catch (LanguageException ex) {
        raisedException = true;
        if (raisedException != expectedException)
            ex.printStackTrace();
    } catch (Exception ex2) {
        ex2.printStackTrace();
        throw new RuntimeException(ex2);
    // Assert.fail( "Unexpected exception occured during test run." );
    }
    // check correctness
    Assert.assertEquals(expectedException, raisedException);
}
Also used : DMLConfig(org.apache.sysml.conf.DMLConfig) HashMap(java.util.HashMap) TestConfiguration(org.apache.sysml.test.integration.TestConfiguration) DMLTranslator(org.apache.sysml.parser.DMLTranslator) LanguageException(org.apache.sysml.parser.LanguageException) LanguageException(org.apache.sysml.parser.LanguageException) BufferedReader(java.io.BufferedReader) DMLProgram(org.apache.sysml.parser.DMLProgram) FileReader(java.io.FileReader) ParserWrapper(org.apache.sysml.parser.ParserWrapper)

Example 9 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class InterProceduralAnalysis method propagateStatisticsAcrossBlock.

// ///////////////////////////
// INTRA-PROCEDURE ANALYSIS
// ////
private void propagateStatisticsAcrossBlock(StatementBlock sb, LocalVariableMap callVars, FunctionCallSizeInfo fcallSizes, Set<String> fnStack) {
    if (sb instanceof FunctionStatementBlock) {
        FunctionStatementBlock fsb = (FunctionStatementBlock) sb;
        FunctionStatement fstmt = (FunctionStatement) fsb.getStatement(0);
        for (StatementBlock sbi : fstmt.getBody()) propagateStatisticsAcrossBlock(sbi, callVars, fcallSizes, fnStack);
    } else if (sb instanceof WhileStatementBlock) {
        WhileStatementBlock wsb = (WhileStatementBlock) sb;
        WhileStatement wstmt = (WhileStatement) wsb.getStatement(0);
        // old stats into predicate
        propagateStatisticsAcrossPredicateDAG(wsb.getPredicateHops(), callVars);
        // remove updated constant scalars
        Recompiler.removeUpdatedScalars(callVars, wsb);
        // check and propagate stats into body
        LocalVariableMap oldCallVars = (LocalVariableMap) callVars.clone();
        for (StatementBlock sbi : wstmt.getBody()) propagateStatisticsAcrossBlock(sbi, callVars, fcallSizes, fnStack);
        if (Recompiler.reconcileUpdatedCallVarsLoops(oldCallVars, callVars, wsb)) {
            // second pass if required
            propagateStatisticsAcrossPredicateDAG(wsb.getPredicateHops(), callVars);
            for (StatementBlock sbi : wstmt.getBody()) propagateStatisticsAcrossBlock(sbi, callVars, fcallSizes, fnStack);
        }
        // remove updated constant scalars
        Recompiler.removeUpdatedScalars(callVars, sb);
    } else if (sb instanceof IfStatementBlock) {
        IfStatementBlock isb = (IfStatementBlock) sb;
        IfStatement istmt = (IfStatement) isb.getStatement(0);
        // old stats into predicate
        propagateStatisticsAcrossPredicateDAG(isb.getPredicateHops(), callVars);
        // check and propagate stats into body
        LocalVariableMap oldCallVars = (LocalVariableMap) callVars.clone();
        LocalVariableMap callVarsElse = (LocalVariableMap) callVars.clone();
        for (StatementBlock sbi : istmt.getIfBody()) propagateStatisticsAcrossBlock(sbi, callVars, fcallSizes, fnStack);
        for (StatementBlock sbi : istmt.getElseBody()) propagateStatisticsAcrossBlock(sbi, callVarsElse, fcallSizes, fnStack);
        callVars = Recompiler.reconcileUpdatedCallVarsIf(oldCallVars, callVars, callVarsElse, isb);
        // remove updated constant scalars
        Recompiler.removeUpdatedScalars(callVars, sb);
    } else if (// incl parfor
    sb instanceof ForStatementBlock) {
        ForStatementBlock fsb = (ForStatementBlock) sb;
        ForStatement fstmt = (ForStatement) fsb.getStatement(0);
        // old stats into predicate
        propagateStatisticsAcrossPredicateDAG(fsb.getFromHops(), callVars);
        propagateStatisticsAcrossPredicateDAG(fsb.getToHops(), callVars);
        propagateStatisticsAcrossPredicateDAG(fsb.getIncrementHops(), callVars);
        // remove updated constant scalars
        Recompiler.removeUpdatedScalars(callVars, fsb);
        // check and propagate stats into body
        LocalVariableMap oldCallVars = (LocalVariableMap) callVars.clone();
        for (StatementBlock sbi : fstmt.getBody()) propagateStatisticsAcrossBlock(sbi, callVars, fcallSizes, fnStack);
        if (Recompiler.reconcileUpdatedCallVarsLoops(oldCallVars, callVars, fsb))
            for (StatementBlock sbi : fstmt.getBody()) propagateStatisticsAcrossBlock(sbi, callVars, fcallSizes, fnStack);
        // remove updated constant scalars
        Recompiler.removeUpdatedScalars(callVars, sb);
    } else // generic (last-level)
    {
        // remove updated constant scalars
        Recompiler.removeUpdatedScalars(callVars, sb);
        // old stats in, new stats out if updated
        ArrayList<Hop> roots = sb.getHops();
        DMLProgram prog = sb.getDMLProg();
        // replace scalar reads with literals
        Hop.resetVisitStatus(roots);
        propagateScalarsAcrossDAG(roots, callVars);
        // refresh stats across dag
        Hop.resetVisitStatus(roots);
        propagateStatisticsAcrossDAG(roots, callVars);
        // propagate stats into function calls
        Hop.resetVisitStatus(roots);
        propagateStatisticsIntoFunctions(prog, roots, callVars, fcallSizes, fnStack);
    }
}
Also used : ForStatementBlock(org.apache.sysml.parser.ForStatementBlock) ExternalFunctionStatement(org.apache.sysml.parser.ExternalFunctionStatement) FunctionStatement(org.apache.sysml.parser.FunctionStatement) IfStatement(org.apache.sysml.parser.IfStatement) FunctionStatementBlock(org.apache.sysml.parser.FunctionStatementBlock) LocalVariableMap(org.apache.sysml.runtime.controlprogram.LocalVariableMap) ArrayList(java.util.ArrayList) DMLProgram(org.apache.sysml.parser.DMLProgram) WhileStatement(org.apache.sysml.parser.WhileStatement) ForStatement(org.apache.sysml.parser.ForStatement) FunctionStatementBlock(org.apache.sysml.parser.FunctionStatementBlock) IfStatementBlock(org.apache.sysml.parser.IfStatementBlock) WhileStatementBlock(org.apache.sysml.parser.WhileStatementBlock) ForStatementBlock(org.apache.sysml.parser.ForStatementBlock) StatementBlock(org.apache.sysml.parser.StatementBlock) WhileStatementBlock(org.apache.sysml.parser.WhileStatementBlock) IfStatementBlock(org.apache.sysml.parser.IfStatementBlock)

Example 10 with DMLProgram

use of org.apache.sysml.parser.DMLProgram in project incubator-systemml by apache.

the class DMLScript method execute.

// /////////////////////////////
// private internal interface
// (core compilation and execute)
// //////
/**
 * The running body of DMLScript execution. This method should be called after execution properties have been correctly set,
 * and customized parameters have been put into _argVals
 *
 * @param dmlScriptStr DML script string
 * @param fnameOptConfig configuration file
 * @param argVals map of argument values
 * @param allArgs arguments
 * @param scriptType type of script (DML or PyDML)
 * @throws IOException if IOException occurs
 */
private static void execute(String dmlScriptStr, String fnameOptConfig, Map<String, String> argVals, String[] allArgs, ScriptType scriptType) throws IOException {
    SCRIPT_TYPE = scriptType;
    // print basic time and environment info
    printStartExecInfo(dmlScriptStr);
    // Step 1: parse configuration files & write any configuration specific global variables
    DMLConfig dmlconf = DMLConfig.readConfigurationFile(fnameOptConfig);
    ConfigurationManager.setGlobalConfig(dmlconf);
    CompilerConfig cconf = OptimizerUtils.constructCompilerConfig(dmlconf);
    ConfigurationManager.setGlobalConfig(cconf);
    LOG.debug("\nDML config: \n" + dmlconf.getConfigInfo());
    // Sets the GPUs to use for this process (a range, all GPUs, comma separated list or a specific GPU)
    GPUContextPool.AVAILABLE_GPUS = dmlconf.getTextValue(DMLConfig.AVAILABLE_GPUS);
    String evictionPolicy = dmlconf.getTextValue(DMLConfig.GPU_EVICTION_POLICY).toUpperCase();
    try {
        DMLScript.GPU_EVICTION_POLICY = EvictionPolicy.valueOf(evictionPolicy);
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Unsupported eviction policy:" + evictionPolicy);
    }
    // Step 2: set local/remote memory if requested (for compile in AM context)
    if (dmlconf.getBooleanValue(DMLConfig.YARN_APPMASTER)) {
        DMLAppMasterUtils.setupConfigRemoteMaxMemory(dmlconf);
    }
    // Step 3: parse dml script
    Statistics.startCompileTimer();
    ParserWrapper parser = ParserFactory.createParser(scriptType);
    DMLProgram prog = parser.parse(DML_FILE_PATH_ANTLR_PARSER, dmlScriptStr, argVals);
    // Step 4: construct HOP DAGs (incl LVA, validate, and setup)
    DMLTranslator dmlt = new DMLTranslator(prog);
    dmlt.liveVariableAnalysis(prog);
    dmlt.validateParseTree(prog);
    dmlt.constructHops(prog);
    // init working directories (before usage by following compilation steps)
    initHadoopExecution(dmlconf);
    // Step 5: rewrite HOP DAGs (incl IPA and memory estimates)
    dmlt.rewriteHopsDAG(prog);
    // Step 6: construct lops (incl exec type and op selection)
    dmlt.constructLops(prog);
    if (LOG.isDebugEnabled()) {
        LOG.debug("\n********************** LOPS DAG *******************");
        dmlt.printLops(prog);
        dmlt.resetLopsDAGVisitStatus(prog);
    }
    // Step 7: generate runtime program, incl codegen
    Program rtprog = dmlt.getRuntimeProgram(prog, dmlconf);
    // launch SystemML appmaster (if requested and not already in launched AM)
    if (dmlconf.getBooleanValue(DMLConfig.YARN_APPMASTER)) {
        if (!isActiveAM() && DMLYarnClientProxy.launchDMLYarnAppmaster(dmlScriptStr, dmlconf, allArgs, rtprog))
            // if AM launch unsuccessful, fall back to normal execute
            return;
        if (// in AM context (not failed AM launch)
        isActiveAM())
            DMLAppMasterUtils.setupProgramMappingRemoteMaxMemory(rtprog);
    }
    // Step 9: prepare statistics [and optional explain output]
    // count number compiled MR jobs / SP instructions
    ExplainCounts counts = Explain.countDistributedOperations(rtprog);
    Statistics.resetNoOfCompiledJobs(counts.numJobs);
    // explain plan of program (hops or runtime)
    if (EXPLAIN != ExplainType.NONE)
        LOG.info(Explain.display(prog, rtprog, EXPLAIN, counts));
    Statistics.stopCompileTimer();
    // double costs = CostEstimationWrapper.getTimeEstimate(rtprog, ExecutionContextFactory.createContext());
    // System.out.println("Estimated costs: "+costs);
    // Step 10: execute runtime program
    ExecutionContext ec = null;
    try {
        ec = ExecutionContextFactory.createContext(rtprog);
        ScriptExecutorUtils.executeRuntimeProgram(rtprog, ec, dmlconf, STATISTICS ? STATISTICS_COUNT : 0);
    } finally {
        if (ec != null && ec instanceof SparkExecutionContext)
            ((SparkExecutionContext) ec).close();
        LOG.info("END DML run " + getDateTime());
        // cleanup scratch_space and all working dirs
        cleanupHadoopExecution(dmlconf);
    }
}
Also used : DMLConfig(org.apache.sysml.conf.DMLConfig) DMLRuntimeException(org.apache.sysml.runtime.DMLRuntimeException) DMLProgram(org.apache.sysml.parser.DMLProgram) Program(org.apache.sysml.runtime.controlprogram.Program) SparkExecutionContext(org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext) ExecutionContext(org.apache.sysml.runtime.controlprogram.context.ExecutionContext) ExplainCounts(org.apache.sysml.utils.Explain.ExplainCounts) DMLProgram(org.apache.sysml.parser.DMLProgram) ParserWrapper(org.apache.sysml.parser.ParserWrapper) SparkExecutionContext(org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext) CompilerConfig(org.apache.sysml.conf.CompilerConfig) DMLTranslator(org.apache.sysml.parser.DMLTranslator)

Aggregations

DMLProgram (org.apache.sysml.parser.DMLProgram)19 LanguageException (org.apache.sysml.parser.LanguageException)8 FunctionStatementBlock (org.apache.sysml.parser.FunctionStatementBlock)7 DMLConfig (org.apache.sysml.conf.DMLConfig)5 DMLTranslator (org.apache.sysml.parser.DMLTranslator)5 ParseException (org.apache.sysml.parser.ParseException)5 ParserWrapper (org.apache.sysml.parser.ParserWrapper)5 FunctionStatement (org.apache.sysml.parser.FunctionStatement)4 ImportStatement (org.apache.sysml.parser.ImportStatement)4 StatementBlock (org.apache.sysml.parser.StatementBlock)4 ForProgramBlock (org.apache.sysml.runtime.controlprogram.ForProgramBlock)4 FunctionProgramBlock (org.apache.sysml.runtime.controlprogram.FunctionProgramBlock)4 ProgramBlock (org.apache.sysml.runtime.controlprogram.ProgramBlock)4 BufferedReader (java.io.BufferedReader)3 FileReader (java.io.FileReader)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3