You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@systemml.apache.org by mb...@apache.org on 2018/04/18 07:12:48 UTC

[1/5] systemml git commit: [MINOR] Performance right indexing (avoid unnecessary nnz maintenance)

Repository: systemml
Updated Branches:
  refs/heads/master 767477aee -> 36a06ab68


[MINOR] Performance right indexing (avoid unnecessary nnz maintenance)

Project: http://git-wip-us.apache.org/repos/asf/systemml/repo
Commit: http://git-wip-us.apache.org/repos/asf/systemml/commit/d1389c3e
Tree: http://git-wip-us.apache.org/repos/asf/systemml/tree/d1389c3e
Diff: http://git-wip-us.apache.org/repos/asf/systemml/diff/d1389c3e

Branch: refs/heads/master
Commit: d1389c3eab2f0ab3accfa247316e4500eaac7116
Parents: 767477a
Author: Matthias Boehm <mb...@gmail.com>
Authored: Tue Apr 17 20:17:25 2018 -0700
Committer: Matthias Boehm <mb...@gmail.com>
Committed: Tue Apr 17 20:17:25 2018 -0700

----------------------------------------------------------------------
 .../java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java    | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/systemml/blob/d1389c3e/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java b/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java
index 3b6d682..7fab225 100644
--- a/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java
+++ b/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java
@@ -3726,7 +3726,8 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab
 		}
 		
 		//compute nnz of output (not maintained due to native calls)
-		dest.recomputeNonZeros();
+		dest.setNonZeros((getNonZeros() == getLength()) ? 
+			(ru-rl+1) * (cu-cl+1) : dest.recomputeNonZeros());
 	}
 	
 	@Override


[4/5] systemml git commit: [SYSTEMML-2252] Improved parfor rewrite update-in-place result indexing

Posted by mb...@apache.org.
[SYSTEMML-2252] Improved parfor rewrite update-in-place result indexing

This patch improves the existing update-in-place resulting indexing
rewrite of the parfor optimizer. In detail this includes (1) a fix for
compute the total size of pinned result variables (which incorrectly
double counted the degree of parallelism), and (2) properly compute the
remaining memory estimates without double counting the result indexing
in case this operation is the max memory consumer.

Furthermore, this also includes a cleanup of the parfor cost/memory
estimator to avoid unnecessary tracing and leverage java streams.


Project: http://git-wip-us.apache.org/repos/asf/systemml/repo
Commit: http://git-wip-us.apache.org/repos/asf/systemml/commit/2838cefd
Tree: http://git-wip-us.apache.org/repos/asf/systemml/tree/2838cefd
Diff: http://git-wip-us.apache.org/repos/asf/systemml/diff/2838cefd

Branch: refs/heads/master
Commit: 2838cefd9a361992a41173e713ef659738d0aed6
Parents: dfc48ae3
Author: Matthias Boehm <mb...@gmail.com>
Authored: Tue Apr 17 23:03:02 2018 -0700
Committer: Matthias Boehm <mb...@gmail.com>
Committed: Tue Apr 17 23:03:02 2018 -0700

----------------------------------------------------------------------
 .../parfor/opt/CostEstimator.java               | 49 +++++++++----------
 .../parfor/opt/CostEstimatorHops.java           | 48 ++++++++++--------
 .../parfor/opt/CostEstimatorRuntime.java        |  4 +-
 .../parfor/opt/OptimizerConstrained.java        | 10 ++--
 .../parfor/opt/OptimizerRuleBased.java          | 51 +++++++++-----------
 5 files changed, 78 insertions(+), 84 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/systemml/blob/2838cefd/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimator.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimator.java b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimator.java
index 2f5392e..167120f 100644
--- a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimator.java
+++ b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimator.java
@@ -20,11 +20,13 @@
 package org.apache.sysml.runtime.controlprogram.parfor.opt;
 
 import java.util.ArrayList;
+import java.util.Collection;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
 import org.apache.sysml.lops.LopProperties.ExecType;
+import org.apache.sysml.parser.ParForStatementBlock.ResultVar;
 import org.apache.sysml.runtime.controlprogram.parfor.opt.OptNode.ParamType;
 
 /**
@@ -34,9 +36,9 @@ import org.apache.sysml.runtime.controlprogram.parfor.opt.OptNode.ParamType;
  * 
  */
 public abstract class CostEstimator 
-{	
+{
 	protected static final Log LOG = LogFactory.getLog(CostEstimator.class.getName());
-    	
+
 	//default parameters
 	public static final double DEFAULT_EST_PARALLELISM = 1.0; //default degree of parallelism: serial
 	public static final long   FACTOR_NUM_ITERATIONS   = 10; //default problem size
@@ -46,7 +48,7 @@ public abstract class CostEstimator
 
 	public enum TestMeasure {
 		EXEC_TIME,
-		MEMORY_USAGE	
+		MEMORY_USAGE
 	}
 	
 	public enum DataFormat {
@@ -55,6 +57,7 @@ public abstract class CostEstimator
 	}
 	
 	protected boolean _inclCondPart = false;
+	protected Collection<ResultVar> _exclRetVars = null;
 	
 	/**
 	 * Main leaf node estimation method - to be overwritten by specific cost estimators
@@ -93,12 +96,18 @@ public abstract class CostEstimator
 	}
 	
 	public double getEstimate( TestMeasure measure, OptNode node, boolean inclCondPart ) {
-		//temporarily change local flag and get estimate
-		boolean oldInclCondPart = _inclCondPart;
-		_inclCondPart = inclCondPart; 
+		_inclCondPart = inclCondPart; //temporary
+		double val = getEstimate(measure, node, null);
+		_inclCondPart = false;
+		return val;
+	}
+	
+	public double getEstimate(TestMeasure measure, OptNode node, boolean inclCondPart, Collection<ResultVar> retVars) {
+		_inclCondPart = inclCondPart; //temporary
+		_exclRetVars = retVars;
 		double val = getEstimate(measure, node, null);
-		//reset local flag and return
-		_inclCondPart = oldInclCondPart;
+		_inclCondPart = false; 
+		_exclRetVars = null;
 		return val;
 	}
 	
@@ -125,8 +134,6 @@ public abstract class CostEstimator
 		else
 		{
 			//aggreagtion methods for different program block types and measure types
-			//TODO EXEC TIME requires reconsideration of for/parfor/if predicates 
-			//TODO MEMORY requires reconsideration of parfor -> potential overestimation, but safe
 			String tmp = null;
 			double N = -1;
 			switch ( measure )
@@ -190,34 +197,24 @@ public abstract class CostEstimator
 		return val;
 	}
 
-	protected double getDefaultEstimate(TestMeasure measure)  {
+	protected double getDefaultEstimate(TestMeasure measure) {
 		switch( measure ) {
 			case EXEC_TIME:    return DEFAULT_TIME_ESTIMATE;
 			case MEMORY_USAGE: return DEFAULT_MEM_ESTIMATE_CP;
-		}		
+		}
 		return -1;
 	}
 
 	protected double getMaxEstimate( TestMeasure measure, ArrayList<OptNode> nodes, ExecType et ) {
-		double max = Double.MIN_VALUE; //smallest positive value
-		for( OptNode n : nodes )
-			max = Math.max(max, getEstimate(measure, n, et));
-		return max;
+		return nodes.stream().mapToDouble(n -> getEstimate(measure, n, et))
+			.max().orElse(Double.NEGATIVE_INFINITY);
 	}
 
 	protected double getSumEstimate( TestMeasure measure, ArrayList<OptNode> nodes, ExecType et ) {
-		double sum = 0;
-		for( OptNode n : nodes )
-			sum += getEstimate( measure, n, et );
-		return sum;
+		return nodes.stream().mapToDouble(n -> getEstimate(measure, n, et)).sum();
 	}
 
 	protected double getWeightedEstimate( TestMeasure measure, ArrayList<OptNode> nodes, ExecType et ) {
-		double ret = 0;
-		int len = nodes.size();
-		for( OptNode n : nodes )
-			ret += getEstimate( measure, n, et );
-		ret /= len; //weighting
-		return ret;
+		return nodes.stream().mapToDouble(n -> getEstimate(measure, n, et)).sum() / nodes.size(); //weighting
 	}
 }

http://git-wip-us.apache.org/repos/asf/systemml/blob/2838cefd/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorHops.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorHops.java b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorHops.java
index 55d9c0c..3cb0c6f 100644
--- a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorHops.java
+++ b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorHops.java
@@ -21,8 +21,10 @@ package org.apache.sysml.runtime.controlprogram.parfor.opt;
 
 import org.apache.sysml.api.DMLScript;
 import org.apache.sysml.hops.Hop;
+import org.apache.sysml.hops.LeftIndexingOp;
 import org.apache.sysml.hops.OptimizerUtils;
 import org.apache.sysml.lops.LopProperties.ExecType;
+import org.apache.sysml.parser.ParForStatementBlock.ResultVar;
 import org.apache.sysml.runtime.DMLRuntimeException;
 import org.apache.sysml.runtime.controlprogram.parfor.opt.OptNode.NodeType;
 import org.apache.sysml.runtime.controlprogram.parfor.opt.Optimizer.CostModelType;
@@ -30,15 +32,15 @@ import org.apache.sysml.runtime.controlprogram.parfor.stat.InfrastructureAnalyze
 
 public class CostEstimatorHops extends CostEstimator
 {
-	public static double DEFAULT_MEM_MR = -1;
-	public static double DEFAULT_MEM_SP = 20*1024*1024;
+	public static final double DEFAULT_MEM_SP = 20*1024*1024;
+	public static final double DEFAULT_MEM_MR;
 	
 	private OptTreePlanMappingAbstract _map = null;
 	
 	static {
-		DEFAULT_MEM_MR = DEFAULT_MEM_ESTIMATE_MR; //20MB
-		if( InfrastructureAnalyzer.isLocalMode() )
-			DEFAULT_MEM_MR = DEFAULT_MEM_MR + InfrastructureAnalyzer.getRemoteMaxMemorySortBuffer();
+		DEFAULT_MEM_MR = DEFAULT_MEM_ESTIMATE_MR //20MB
+			+ (InfrastructureAnalyzer.isLocalMode() ?
+			InfrastructureAnalyzer.getRemoteMaxMemorySortBuffer() : 0);
 	}
 	
 	
@@ -61,30 +63,26 @@ public class CostEstimatorHops extends CostEstimator
 		
 		//handle specific cases 
 		double DEFAULT_MEM_REMOTE = OptimizerUtils.isSparkExecutionMode() ? 
-								DEFAULT_MEM_SP : DEFAULT_MEM_MR;
+			DEFAULT_MEM_SP : DEFAULT_MEM_MR;
 		
-		if( value >= DEFAULT_MEM_REMOTE )   	  
+		if( value >= DEFAULT_MEM_REMOTE )
 		{
 			//check for CP estimate but MR type
-			if( h.getExecType()==ExecType.MR ) 
-			{
+			if( h.getExecType()==ExecType.MR ) {
 				value = DEFAULT_MEM_REMOTE;
 			}
 			//check for CP estimate but Spark type (include broadcast requirements)
-			else if( h.getExecType()==ExecType.SPARK )
-			{
+			else if( h.getExecType()==ExecType.SPARK ) {
 				value = DEFAULT_MEM_REMOTE + h.getSpBroadcastSize();
 			}
 			//check for invalid cp memory estimate
-			else if ( h.getExecType()==ExecType.CP && value >= OptimizerUtils.getLocalMemBudget() )
-			{
+			else if ( h.getExecType()==ExecType.CP && value >= OptimizerUtils.getLocalMemBudget() ) {
 				if( DMLScript.rtplatform != DMLScript.RUNTIME_PLATFORM.SINGLE_NODE && h.getForcedExecType()==null )
 					LOG.warn("Memory estimate larger than budget but CP exec type (op="+h.getOpString()+", name="+h.getName()+", memest="+h.getMemEstimate()+").");
 				value = DEFAULT_MEM_REMOTE;
 			}
 			//check for non-existing exec type
-			else if ( h.getExecType()==null)
-			{
+			else if ( h.getExecType()==null) {
 				//note: if exec type is 'null' lops have never been created (e.g., r(T) for tsmm),
 				//in that case, we do not need to raise a warning 
 				value = DEFAULT_MEM_REMOTE;
@@ -92,18 +90,23 @@ public class CostEstimatorHops extends CostEstimator
 		}
 		
 		//check for forced runtime platform
-		if( h.getForcedExecType()==ExecType.MR  || h.getForcedExecType()==ExecType.SPARK) 
-		{
+		if( h.getForcedExecType()==ExecType.MR  || h.getForcedExecType()==ExecType.SPARK) {
 			value = DEFAULT_MEM_REMOTE;
 		}
 		
-		if( value <= 0 ) //no mem estimate
-		{
+		if( value <= 0 ) { //no mem estimate
 			LOG.warn("Cannot get memory estimate for hop (op="+h.getOpString()+", name="+h.getName()+", memest="+h.getMemEstimate()+").");
 			value = CostEstimator.DEFAULT_MEM_ESTIMATE_CP;
 		}
 		
-		LOG.trace("Memory estimate "+h.getName()+", "+h.getOpString()+"("+node.getExecType()+")"+"="+OptimizerRuleBased.toMB(value));
+		//correction for disabled result indexing
+		value = (_exclRetVars!=null && h instanceof LeftIndexingOp
+			&& ResultVar.contains(_exclRetVars, h.getName())) ? 0 : value;
+		
+		if( LOG.isTraceEnabled() ) {
+			LOG.trace("Memory estimate "+h.getName()+", "+h.getOpString()
+				+"("+node.getExecType()+")"+"="+OptimizerRuleBased.toMB(value));
+		}
 		
 		return value;
 	}
@@ -125,7 +128,10 @@ public class CostEstimatorHops extends CostEstimator
 		if( value <= 0 ) //no mem estimate
 			value = CostEstimator.DEFAULT_MEM_ESTIMATE_CP;
 		
-		LOG.trace("Memory estimate (forced exec type) "+h.getName()+", "+h.getOpString()+"("+node.getExecType()+")"+"="+OptimizerRuleBased.toMB(value));
+		if( LOG.isTraceEnabled() ) {
+			LOG.trace("Memory estimate (forced exec type) "+h.getName()+", "
+				+h.getOpString()+"("+node.getExecType()+")"+"="+OptimizerRuleBased.toMB(value));
+		}
 		
 		return value;
 	}

http://git-wip-us.apache.org/repos/asf/systemml/blob/2838cefd/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorRuntime.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorRuntime.java b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorRuntime.java
index 9a842a7..ee05af0 100644
--- a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorRuntime.java
+++ b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/CostEstimatorRuntime.java
@@ -71,10 +71,10 @@ public class CostEstimatorRuntime extends CostEstimator
 		//(currently only called for entire parfor program in order to
 		//decide for LOCAL vs REMOTE parfor execution)
 		double ret = DEFAULT_TIME_ESTIMATE;
-		boolean isCP = (et == ExecType.CP || et == null);		
+		boolean isCP = (et == ExecType.CP || et == null);
 		if( !node.isLeaf() && isCP ) {
 			ProgramBlock pb = (ProgramBlock)_map.getMappedProg(node.getID())[1];
-			ret = CostEstimationWrapper.getTimeEstimate(pb, _ec, true);				
+			ret = CostEstimationWrapper.getTimeEstimate(pb, _ec, true);
 		}
 		return ret;
 	}

http://git-wip-us.apache.org/repos/asf/systemml/blob/2838cefd/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerConstrained.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerConstrained.java b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerConstrained.java
index 68731c1..4088e63 100644
--- a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerConstrained.java
+++ b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerConstrained.java
@@ -54,9 +54,7 @@ import org.apache.sysml.runtime.controlprogram.parfor.opt.OptNode.ParamType;
  * - 4) rewrite set execution strategy
  * - 9) rewrite set degree of parallelism
  * - 10) rewrite set task partitioner
- * - 11) rewrite set result merge 		 		
- *
- * TODO generalize for nested parfor (currently only awareness of top-level constraints, if present leave child as they are)
+ * - 11) rewrite set result merge
  *
  */
 public class OptimizerConstrained extends OptimizerRuleBased
@@ -167,7 +165,7 @@ public class OptimizerConstrained extends OptimizerRuleBased
 
 			//rewrite 14:
 			HashSet<ResultVar> inplaceResultVars = new HashSet<>();
-			super.rewriteSetInPlaceResultIndexing(pn, M1, ec.getVariables(), inplaceResultVars, ec);
+			super.rewriteSetInPlaceResultIndexing(pn, _cost, ec.getVariables(), inplaceResultVars, ec);
 
 			//rewrite 15:
 			super.rewriteDisableCPCaching(pn, inplaceResultVars, ec.getVariables());
@@ -183,7 +181,7 @@ public class OptimizerConstrained extends OptimizerRuleBased
 
 			// rewrite 14: set in-place result indexing
 			HashSet<ResultVar> inplaceResultVars = new HashSet<>();
-			super.rewriteSetInPlaceResultIndexing(pn, M1, ec.getVariables(), inplaceResultVars, ec);
+			super.rewriteSetInPlaceResultIndexing(pn, _cost, ec.getVariables(), inplaceResultVars, ec);
 
 			if( !OptimizerUtils.isSparkExecutionMode() ) {
 				// rewrite 16: runtime piggybacking
@@ -316,7 +314,7 @@ public class OptimizerConstrained extends OptimizerRuleBased
 		if( !pn.getParam(ParamType.TASK_PARTITIONER).equals(PTaskPartitioner.UNSPECIFIED.toString()) )
 		{
 			ParForProgramBlock pfpb = (ParForProgramBlock) OptTreeConverter
-                    .getAbstractPlanMapping().getMappedProg(pn.getID())[1];
+				.getAbstractPlanMapping().getMappedProg(pn.getID())[1];
 			pfpb.setTaskPartitioner(PTaskPartitioner.valueOf(pn.getParam(ParamType.TASK_PARTITIONER)));
 			String tsExt = "";
 			if( pn.getParam(ParamType.TASK_SIZE)!=null )

http://git-wip-us.apache.org/repos/asf/systemml/blob/2838cefd/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerRuleBased.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerRuleBased.java b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerRuleBased.java
index 536acb3..2bf8fe5 100644
--- a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerRuleBased.java
+++ b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/opt/OptimizerRuleBased.java
@@ -166,25 +166,22 @@ public class OptimizerRuleBased extends Optimizer
 	protected double _lm = -1; //local memory constraint
 	protected double _rm = -1; //remote memory constraint (mappers)
 	protected double _rm2 = -1; //remote memory constraint (reducers)
-		
+	
 	protected CostEstimator _cost = null;
 
 	@Override
-	public CostModelType getCostModelType() 
-	{
+	public CostModelType getCostModelType() {
 		return CostModelType.STATIC_MEM_METRIC;
 	}
 
 
 	@Override
-	public PlanInputType getPlanInputType() 
-	{
+	public PlanInputType getPlanInputType() {
 		return PlanInputType.ABSTRACT_PLAN;
 	}
 
 	@Override
-	public POptMode getOptMode() 
-	{
+	public POptMode getOptMode() {
 		return POptMode.RULEBASED;
 	}
 	
@@ -261,7 +258,7 @@ public class OptimizerRuleBased extends Optimizer
 			if( flagRecompMR ){
 				//rewrite 5: set operations exec type
 				rewriteSetOperationsExecType( pn, flagRecompMR );
-				M1 = _cost.getEstimate(TestMeasure.MEMORY_USAGE, pn); //reestimate 		
+				M1 = _cost.getEstimate(TestMeasure.MEMORY_USAGE, pn); //reestimate
 			}
 			
 			// rewrite 6: data colocation
@@ -287,7 +284,7 @@ public class OptimizerRuleBased extends Optimizer
 			
 			// rewrite 14: set in-place result indexing
 			HashSet<ResultVar> inplaceResultVars = new HashSet<>();
-			rewriteSetInPlaceResultIndexing(pn, M1, ec.getVariables(), inplaceResultVars, ec);
+			rewriteSetInPlaceResultIndexing(pn, _cost, ec.getVariables(), inplaceResultVars, ec);
 			
 			// rewrite 15: disable caching
 			rewriteDisableCPCaching(pn, inplaceResultVars, ec.getVariables());
@@ -302,7 +299,7 @@ public class OptimizerRuleBased extends Optimizer
 			
 			// rewrite 14: set in-place result indexing
 			HashSet<ResultVar> inplaceResultVars = new HashSet<>();
-			rewriteSetInPlaceResultIndexing(pn, M1, ec.getVariables(), inplaceResultVars, ec);
+			rewriteSetInPlaceResultIndexing(pn, _cost, ec.getVariables(), inplaceResultVars, ec);
 			
 			if( !OptimizerUtils.isSparkExecutionMode() ) {
 				// rewrite 16: runtime piggybacking
@@ -1609,7 +1606,7 @@ public class OptimizerRuleBased extends Optimizer
 			if( inMatrix.equals(varName) )
 			{
 				//check that all parents are transpose-safe operations
-				//(even a transient write would not be safe due to indirection into other DAGs)			
+				//(even a transient write would not be safe due to indirection into other DAGs)
 				ArrayList<Hop> parent = h.getParent();
 				for( Hop p : parent )
 					ret &= p.isTransposeSafe();
@@ -1624,7 +1621,7 @@ public class OptimizerRuleBased extends Optimizer
 	//REWRITE set in-place result indexing
 	///
 
-	protected void rewriteSetInPlaceResultIndexing(OptNode pn, double M, LocalVariableMap vars, HashSet<ResultVar> inPlaceResultVars, ExecutionContext ec) 
+	protected void rewriteSetInPlaceResultIndexing(OptNode pn, CostEstimator cost, LocalVariableMap vars, HashSet<ResultVar> inPlaceResultVars, ExecutionContext ec) 
 	{
 		//assertions (warnings of corrupt optimizer decisions)
 		if( pn.getNodeType() != NodeType.PARFOR )
@@ -1639,16 +1636,17 @@ public class OptimizerRuleBased extends Optimizer
 		//only if all fit pinned in remaining budget, we apply this rewrite.
 		ArrayList<ResultVar> retVars = pfpb.getResultVariables();
 		
-		//compute total sum of pinned result variable memory
-		double sum = computeTotalSizeResultVariables(retVars, vars, pfpb.getDegreeOfParallelism());
-		
-		//NOTE: currently this rule is too conservative (the result variable is assumed to be dense and
-		//most importantly counted twice if this is part of the maximum operation)
-		double totalMem = Math.max((M+sum), rComputeSumMemoryIntermediates(pn, new HashSet<ResultVar>()));
-		
-		//optimization decision
-		if( rHasOnlyInPlaceSafeLeftIndexing(pn, retVars) ) //basic correctness constraint
+		//basic correctness constraint
+		double totalMem = -1;
+		if( rHasOnlyInPlaceSafeLeftIndexing(pn, retVars) )
 		{
+			//compute total sum of pinned result variable memory 
+			double sum = computeTotalSizeResultVariables(retVars, vars, pfpb.getDegreeOfParallelism());
+		
+			//compute memory estimate without result indexing, and total sum per worker
+			double M = cost.getEstimate(TestMeasure.MEMORY_USAGE, pn, true, retVars);
+			totalMem = M + sum;
+			
 			//result update in-place for MR/Spark (w/ remote memory constraint)
 			if( (  pfpb.getExecMode() == PExecMode.REMOTE_MR_DP || pfpb.getExecMode() == PExecMode.REMOTE_MR
 				|| pfpb.getExecMode() == PExecMode.REMOTE_SPARK_DP || pfpb.getExecMode() == PExecMode.REMOTE_SPARK) 
@@ -1706,14 +1704,9 @@ public class OptimizerRuleBased extends Optimizer
 			if( !(dat instanceof MatrixObject) )
 				continue;
 			MatrixObject mo = (MatrixObject)dat;
-			if( mo.getNnz() == 0 ) 
-				sum += OptimizerUtils.estimateSizeExactSparsity(mo.getNumRows(), mo.getNumColumns(), 1.0);
-			else {
-				// Every worker will consume memory for (MatrixSize/k + nnz) data.
-				// This is applicable only when there is non-zero nnz. 
-				sum += (k+1) * (OptimizerUtils.estimateSizeExactSparsity(mo.getNumRows(), 
-					mo.getNumColumns(), Math.min((1.0/k)+mo.getSparsity(), 1.0)));
-			} 
+			// every worker will consume memory for at most (max_nnz/k + in_nnz)
+			sum += (OptimizerUtils.estimateSizeExactSparsity(mo.getNumRows(), 
+				mo.getNumColumns(), Math.min((1.0/k)+mo.getSparsity(), 1.0)));
 		}
 		return sum;
 	}


[3/5] systemml git commit: [SYSTEMML-2250] Multi-threaded parfor result merge (per block)

Posted by mb...@apache.org.
[SYSTEMML-2250] Multi-threaded parfor result merge (per block)

This patch leverages the common thread pool to merge parfor worker
results in a multi-threaded manner into dense result matrices in the
context of local in-memory result merge. This reduces the serial
fraction of parfor programs which is especially important for scale-up
machines with large degree of parallelism.
 

Project: http://git-wip-us.apache.org/repos/asf/systemml/repo
Commit: http://git-wip-us.apache.org/repos/asf/systemml/commit/dfc48ae3
Tree: http://git-wip-us.apache.org/repos/asf/systemml/tree/dfc48ae3
Diff: http://git-wip-us.apache.org/repos/asf/systemml/diff/dfc48ae3

Branch: refs/heads/master
Commit: dfc48ae3cca5725a547b724ee865a186650528c4
Parents: fdc5511
Author: Matthias Boehm <mb...@gmail.com>
Authored: Tue Apr 17 22:58:01 2018 -0700
Committer: Matthias Boehm <mb...@gmail.com>
Committed: Tue Apr 17 22:58:01 2018 -0700

----------------------------------------------------------------------
 .../controlprogram/parfor/ResultMerge.java      | 13 ++---
 .../parfor/ResultMergeLocalMemory.java          |  2 +-
 .../sysml/runtime/matrix/data/MatrixBlock.java  | 60 ++++++++++++++------
 3 files changed, 49 insertions(+), 26 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/systemml/blob/dfc48ae3/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMerge.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMerge.java b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMerge.java
index be87b17..7b8a931 100644
--- a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMerge.java
+++ b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMerge.java
@@ -83,19 +83,16 @@ public abstract class ResultMerge implements Serializable
 	 */
 	public abstract MatrixObject executeParallelMerge( int par );
 	
-	/**
-	 * ?
-	 * 
-	 * @param out initially empty block
-	 * @param in input matrix block
-	 * @param appendOnly ?
-	 */
 	protected void mergeWithoutComp( MatrixBlock out, MatrixBlock in, boolean appendOnly ) {
+		mergeWithoutComp(out, in, appendOnly, false);
+	}
+	
+	protected void mergeWithoutComp( MatrixBlock out, MatrixBlock in, boolean appendOnly, boolean par ) {
 		//pass through to matrix block operations
 		if( _isAccum )
 			out.binaryOperationsInPlace(PLUS, in);
 		else
-			out.merge(in, appendOnly);
+			out.merge(in, appendOnly, par);
 	}
 
 	/**

http://git-wip-us.apache.org/repos/asf/systemml/blob/dfc48ae3/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMergeLocalMemory.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMergeLocalMemory.java b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMergeLocalMemory.java
index e3a2e82..c76b3f9 100644
--- a/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMergeLocalMemory.java
+++ b/src/main/java/org/apache/sysml/runtime/controlprogram/parfor/ResultMergeLocalMemory.java
@@ -262,7 +262,7 @@ public class ResultMergeLocalMemory extends ResultMerge
 	 */
 	private void merge( MatrixBlock out, MatrixBlock in, boolean appendOnly ) {
 		if( _compare == null )
-			mergeWithoutComp(out, in, appendOnly);
+			mergeWithoutComp(out, in, appendOnly, true);
 		else
 			mergeWithComp(out, in, _compare);
 	}

http://git-wip-us.apache.org/repos/asf/systemml/blob/dfc48ae3/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java b/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java
index 7fab225..5ce4963 100644
--- a/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java
+++ b/src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java
@@ -31,6 +31,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Iterator;
+import java.util.stream.IntStream;
 
 import org.apache.commons.math3.random.Well1024a;
 import org.apache.hadoop.io.DataInputBuffer;
@@ -1578,6 +1579,10 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab
 	 * @param appendOnly ?
 	 */
 	public void merge(MatrixBlock that, boolean appendOnly) {
+		merge(that, appendOnly, false);
+	}
+	
+	public void merge(MatrixBlock that, boolean appendOnly, boolean par) {
 		//check for empty input source (nothing to merge)
 		if( that == null || that.isEmptyBlock(false) )
 			return;
@@ -1599,6 +1604,8 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab
 		long nnz = nonZeros + that.nonZeros;
 		if( sparse )
 			mergeIntoSparse(that, appendOnly);
+		else if( par )
+			mergeIntoDensePar(that);
 		else
 			mergeIntoDense(that);
 		
@@ -1608,35 +1615,54 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab
 
 	private void mergeIntoDense(MatrixBlock that)
 	{
-		if( that.sparse ) //DENSE <- SPARSE
-		{
+		if( that.sparse ) { //DENSE <- SPARSE
 			double[] a = getDenseBlockValues();
 			SparseBlock b = that.sparseBlock;
 			int m = rlen;
 			int n = clen;
-			
-			for( int i=0, aix=0; i<m; i++, aix+=n )
-				if( !b.isEmpty(i) )
-				{
-					int bpos = b.pos(i);
-					int blen = b.size(i);
-					int[] bix = b.indexes(i);
-					double[] bval = b.values(i);
-					for( int j=bpos; j<bpos+blen; j++ )
-						if( bval[j] != 0 )
-							a[ aix + bix[j] ] = bval[j];
-				}
+			for( int i=0, aix=0; i<m; i++, aix+=n ) {
+				if( b.isEmpty(i) ) continue;
+				int bpos = b.pos(i);
+				int blen = b.size(i);
+				int[] bix = b.indexes(i);
+				double[] bval = b.values(i);
+				for( int j=bpos; j<bpos+blen; j++ )
+					if( bval[j] != 0 )
+						a[ aix + bix[j] ] = bval[j];
+			}
 		}
-		else //DENSE <- DENSE
-		{
+		else { //DENSE <- DENSE
 			double[] a = getDenseBlockValues();
 			double[] b = that.getDenseBlockValues();
 			int len = rlen * clen;
-			
 			for( int i=0; i<len; i++ )
 				a[i] = ( b[i] != 0 ) ? b[i] : a[i];
 		}
 	}
+	
+	private void mergeIntoDensePar(MatrixBlock that)
+	{
+		if( that.sparse ) { //DENSE <- SPARSE
+			double[] a = getDenseBlockValues();
+			SparseBlock b = that.sparseBlock;
+			IntStream.range(0, rlen).parallel().forEach(i -> {
+				if( b.isEmpty(i) ) return;
+				int aix = i*clen;
+				int bpos = b.pos(i);
+				int blen = b.size(i);
+				int[] bix = b.indexes(i);
+				double[] bval = b.values(i);
+				for( int j=bpos; j<bpos+blen; j++ )
+					if( bval[j] != 0 )
+						a[ aix + bix[j] ] = bval[j];
+			});
+		}
+		else { //DENSE <- DENSE
+			double[] a = getDenseBlockValues();
+			double[] b = that.getDenseBlockValues();
+			Arrays.parallelSetAll(a, i -> (b[i]!=0) ? b[i] : a[i]);
+		}
+	}
 
 	private void mergeIntoSparse(MatrixBlock that, boolean appendOnly)
 	{


[5/5] systemml git commit: [SYSTEMML-2254] Robustness transformdecode for ncol(data) < ncol(meta)

Posted by mb...@apache.org.
[SYSTEMML-2254] Robustness transformdecode for ncol(data) < ncol(meta)

This patch fixes the robustness of transformdecode. So far, we created
the output frame in the number of columns in the given meta data frame.
However, this leads to index-out-of-bound exceptions if the given input
data has fewer columns than the meta data frame due to unnecessary
pass-through encoders that try to access non-existing columns.


Project: http://git-wip-us.apache.org/repos/asf/systemml/repo
Commit: http://git-wip-us.apache.org/repos/asf/systemml/commit/36a06ab6
Tree: http://git-wip-us.apache.org/repos/asf/systemml/tree/36a06ab6
Diff: http://git-wip-us.apache.org/repos/asf/systemml/diff/36a06ab6

Branch: refs/heads/master
Commit: 36a06ab6876d3d92e01b8c94a46c77841d654792
Parents: 2838cef
Author: Matthias Boehm <mb...@gmail.com>
Authored: Wed Apr 18 00:14:27 2018 -0700
Committer: Matthias Boehm <mb...@gmail.com>
Committed: Wed Apr 18 00:14:27 2018 -0700

----------------------------------------------------------------------
 .../cp/ParameterizedBuiltinCPInstruction.java   |  3 ++-
 .../transform/decode/DecoderFactory.java        | 25 ++++++++++++--------
 .../transform/decode/DecoderPassThrough.java    |  3 ++-
 3 files changed, 19 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/systemml/blob/36a06ab6/src/main/java/org/apache/sysml/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.java b/src/main/java/org/apache/sysml/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.java
index fe18dbc..06aeef3 100644
--- a/src/main/java/org/apache/sysml/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.java
+++ b/src/main/java/org/apache/sysml/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.java
@@ -268,7 +268,8 @@ public class ParameterizedBuiltinCPInstruction extends ComputationCPInstruction
 			String[] colnames = meta.getColumnNames();
 			
 			//compute transformdecode
-			Decoder decoder = DecoderFactory.createDecoder(getParameterMap().get("spec"), colnames, null, meta);
+			Decoder decoder = DecoderFactory.createDecoder(
+				getParameterMap().get("spec"), colnames, null, meta, data.getNumColumns());
 			FrameBlock fbout = decoder.decode(data, new FrameBlock(decoder.getSchema()));
 			fbout.setColumnNames(Arrays.copyOfRange(colnames, 0, fbout.getNumColumns()));
 			

http://git-wip-us.apache.org/repos/asf/systemml/blob/36a06ab6/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderFactory.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderFactory.java b/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderFactory.java
index d8b9f3a..c2788cb 100644
--- a/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderFactory.java
+++ b/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderFactory.java
@@ -36,45 +36,50 @@ import org.apache.wink.json4j.JSONObject;
 
 public class DecoderFactory 
 {
+	public static Decoder createDecoder(String spec, String[] colnames, ValueType[] schema, FrameBlock meta) {
+		return createDecoder(spec, colnames, schema, meta, meta.getNumColumns());
+	}
+	
 	@SuppressWarnings("unchecked")
-	public static Decoder createDecoder(String spec, String[] colnames, ValueType[] schema, FrameBlock meta) 
+	public static Decoder createDecoder(String spec, String[] colnames, ValueType[] schema, FrameBlock meta, int clen) 
 	{
 		Decoder decoder = null;
 		
-		try 
+		try
 		{
 			//parse transform specification
 			JSONObject jSpec = new JSONObject(spec);
 			List<Decoder> ldecoders = new ArrayList<>();
-		
+			
 			//create decoders 'recode', 'dummy' and 'pass-through'
 			List<Integer> rcIDs = Arrays.asList(ArrayUtils.toObject(
 					TfMetaUtils.parseJsonIDList(jSpec, colnames, TfUtils.TXMETHOD_RECODE)));
 			List<Integer> dcIDs = Arrays.asList(ArrayUtils.toObject(
 					TfMetaUtils.parseJsonIDList(jSpec, colnames, TfUtils.TXMETHOD_DUMMYCODE))); 
 			rcIDs = new ArrayList<Integer>(CollectionUtils.union(rcIDs, dcIDs));
+			int len = dcIDs.isEmpty() ? Math.min(meta.getNumColumns(), clen) : meta.getNumColumns();
 			List<Integer> ptIDs = new ArrayList<Integer>(CollectionUtils
-					.subtract(UtilFunctions.getSeqList(1, meta.getNumColumns(), 1), rcIDs)); 
-
+				.subtract(UtilFunctions.getSeqList(1, len, 1), rcIDs));
+			
 			//create default schema if unspecified (with double columns for pass-through)
 			if( schema == null ) {
-				schema = UtilFunctions.nCopies(meta.getNumColumns(), ValueType.STRING);
+				schema = UtilFunctions.nCopies(len, ValueType.STRING);
 				for( Integer col : ptIDs )
 					schema[col-1] = ValueType.DOUBLE;
 			}
 			
 			if( !dcIDs.isEmpty() ) {
 				ldecoders.add(new DecoderDummycode(schema, 
-						ArrayUtils.toPrimitive(dcIDs.toArray(new Integer[0]))));
+					ArrayUtils.toPrimitive(dcIDs.toArray(new Integer[0]))));
 			}
 			if( !rcIDs.isEmpty() ) {
 				ldecoders.add(new DecoderRecode(schema, !dcIDs.isEmpty(),
-						ArrayUtils.toPrimitive(rcIDs.toArray(new Integer[0]))));
+					ArrayUtils.toPrimitive(rcIDs.toArray(new Integer[0]))));
 			}
 			if( !ptIDs.isEmpty() ) {
 				ldecoders.add(new DecoderPassThrough(schema, 
-						ArrayUtils.toPrimitive(ptIDs.toArray(new Integer[0])),
-						ArrayUtils.toPrimitive(dcIDs.toArray(new Integer[0]))));	
+					ArrayUtils.toPrimitive(ptIDs.toArray(new Integer[0])),
+					ArrayUtils.toPrimitive(dcIDs.toArray(new Integer[0]))));
 			}
 			
 			//create composite decoder of all created decoders

http://git-wip-us.apache.org/repos/asf/systemml/blob/36a06ab6/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderPassThrough.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderPassThrough.java b/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderPassThrough.java
index 8224b5c..79cf3d4 100644
--- a/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderPassThrough.java
+++ b/src/main/java/org/apache/sysml/runtime/transform/decode/DecoderPassThrough.java
@@ -44,8 +44,9 @@ public class DecoderPassThrough extends Decoder
 	@Override
 	public FrameBlock decode(MatrixBlock in, FrameBlock out) {
 		out.ensureAllocatedColumns(in.getNumRows());
+		int clen = Math.min(_colList.length, out.getNumColumns());
 		for( int i=0; i<in.getNumRows(); i++ ) {
-			for( int j=0; j<_colList.length; j++ ) {
+			for( int j=0; j<clen; j++ ) {
 				int srcColID = _srcCols[j];
 				int tgtColID = _colList[j];
 				double val = in.quickGetValue(i, srcColID-1);


[2/5] systemml git commit: [SYSTEMML-2249] Reduced bufferpool thread contention (min thresholds)

Posted by mb...@apache.org.
[SYSTEMML-2249] Reduced bufferpool thread contention (min thresholds)

In multi-threaded environment with large degree of parallelism many
small operations, the bufferpool shows - despite the small critical
region - unnecessary contention. So far we use a min threshold of 4KB
(objects below that threshold are not subject to bufferpool eviction),
which still stems from a time when we ran CP programs in very small
drivers of 400MB. In modern scale-up environments with heap sizes of
~1TB, such a small threshold causes unnecessary contention. This patch
resolves this by using a conservative threshold of max(4KB, 1e-5 * MEM)
relative to the max heap size MEM.
 

Project: http://git-wip-us.apache.org/repos/asf/systemml/repo
Commit: http://git-wip-us.apache.org/repos/asf/systemml/commit/fdc55118
Tree: http://git-wip-us.apache.org/repos/asf/systemml/tree/fdc55118
Diff: http://git-wip-us.apache.org/repos/asf/systemml/diff/fdc55118

Branch: refs/heads/master
Commit: fdc551183b46d99944d9fb42b91ec35ee5156ceb
Parents: d1389c3
Author: Matthias Boehm <mb...@gmail.com>
Authored: Tue Apr 17 20:26:28 2018 -0700
Committer: Matthias Boehm <mb...@gmail.com>
Committed: Tue Apr 17 20:26:28 2018 -0700

----------------------------------------------------------------------
 .../controlprogram/caching/CacheableData.java   | 27 ++++++++++----------
 1 file changed, 14 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/systemml/blob/fdc55118/src/main/java/org/apache/sysml/runtime/controlprogram/caching/CacheableData.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/controlprogram/caching/CacheableData.java b/src/main/java/org/apache/sysml/runtime/controlprogram/caching/CacheableData.java
index 3c001bc..1ba6c4c 100644
--- a/src/main/java/org/apache/sysml/runtime/controlprogram/caching/CacheableData.java
+++ b/src/main/java/org/apache/sysml/runtime/controlprogram/caching/CacheableData.java
@@ -76,21 +76,22 @@ public abstract class CacheableData<T extends CacheBlock> extends Data
 
 	/** Global logging instance for all subclasses of CacheableData */
 	protected static final Log LOG = LogFactory.getLog(CacheableData.class.getName());
-    
+	
 	// global constant configuration parameters
-	public static final long 	CACHING_THRESHOLD = 4*1024; //obj not s.t. caching if below threshold [in bytes]
-	public static final double 	CACHING_BUFFER_SIZE = 0.15; 
+	public static final long    CACHING_THRESHOLD = (long)Math.max(4*1024, //obj not s.t. caching
+		1e-5 * InfrastructureAnalyzer.getLocalMaxMemory());       //if below threshold [in bytes]
+	public static final double  CACHING_BUFFER_SIZE = 0.15; 
 	public static final RPolicy CACHING_BUFFER_POLICY = RPolicy.FIFO; 
 	public static final boolean CACHING_BUFFER_PAGECACHE = false; 
 	public static final boolean CACHING_WRITE_CACHE_ON_READ = false;	
 	public static final String  CACHING_COUNTER_GROUP_NAME    = "SystemML Caching Counters";
 	public static final String  CACHING_EVICTION_FILEEXTENSION = ".dat";
 	public static final boolean CACHING_ASYNC_FILECLEANUP = true;
-    
+	
 	/**
 	 * Defines all possible cache status types for a data blob.
-     * An object of class {@link CacheableData} can be in one of the following
-     * five status types:
+	 * An object of class {@link CacheableData} can be in one of the following
+	 * five status types:
 	 *
 	 * <code>EMPTY</code>: Either there is no data blob at all, or the data blob  
 	 * resides in a specified import file and has never been downloaded yet.
@@ -102,13 +103,13 @@ public abstract class CacheableData<T extends CacheBlock> extends Data
 	 * <code>CACHED</code>:   The data blob is in main memory, and nobody is using nor referencing it. 
 	 * There is always an persistent recovery object for it
 	 **/
-    protected enum CacheStatus {
-    	EMPTY, 
-    	READ, 
-    	MODIFY, 
-    	CACHED,
-    	CACHED_NOWRITE,
-    }
+	protected enum CacheStatus {
+		EMPTY, 
+		READ, 
+		MODIFY, 
+		CACHED,
+		CACHED_NOWRITE,
+	}
 	
 	/** Global flag indicating if caching is enabled (controls eviction) */
 	private static volatile boolean _activeFlag = false;