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 2016/10/04 18:35:10 UTC

[1/2] incubator-systemml git commit: [SYSTEMML-1004] New spark tsmm2 matrix mult operator (compiler/runtime)

Repository: incubator-systemml
Updated Branches:
  refs/heads/master 0c63f5f61 -> 4e0949bae


[SYSTEMML-1004] New spark tsmm2 matrix mult operator (compiler/runtime)

If the number of columns exceeds the blocksize for expressions like t(X)
%*% X, we can no longer compile a spark/mr tsmm but use cpmm as a
fallback. Since cpmm shuffles both inputs, this had huge performance
impact. This patch introduces a new tsmm2 operator, which applies if the
number of columns is less or equal than 2x the blocksize, by using two
passes over the input (which is in comparison to shuffle significantly
faster). On our perftest scenario of 10Mx1K, icpt={1|2} for LinregDS,
this improved performance from ~300 to 95s (including spark context
creation and initial read; so the actual improvement for this operation
is even larger).


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

Branch: refs/heads/master
Commit: 8da700953cc8ee8ab710a104010e7b54ee77be16
Parents: 0c63f5f
Author: Matthias Boehm <mb...@us.ibm.com>
Authored: Mon Oct 3 17:41:27 2016 -0700
Committer: Matthias Boehm <mb...@us.ibm.com>
Committed: Mon Oct 3 17:50:37 2016 -0700

----------------------------------------------------------------------
 .../java/org/apache/sysml/hops/AggBinaryOp.java |  34 ++-
 src/main/java/org/apache/sysml/lops/MMTSJ.java  |  21 +-
 .../instructions/SPInstructionParser.java       |   6 +-
 .../instructions/spark/SPInstruction.java       |   2 +-
 .../instructions/spark/Tsmm2SPInstruction.java  | 293 +++++++++++++++++++
 .../matrix/data/OperationsOnMatrixValues.java   |   8 +-
 ...lMatrixMultiplicationTransposeSelf2Test.java | 213 ++++++++++++++
 .../binary/matrix_full_other/ZPackageSuite.java |   1 +
 8 files changed, 559 insertions(+), 19 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/8da70095/src/main/java/org/apache/sysml/hops/AggBinaryOp.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/hops/AggBinaryOp.java b/src/main/java/org/apache/sysml/hops/AggBinaryOp.java
index fa08f60..8e96ef9 100644
--- a/src/main/java/org/apache/sysml/hops/AggBinaryOp.java
+++ b/src/main/java/org/apache/sysml/hops/AggBinaryOp.java
@@ -78,6 +78,7 @@ public class AggBinaryOp extends Hop implements MultiThreadedHop
 		PMAPMM,   //partitioned map-side matrix-matrix multiplication (sp)
 		PMM,      //permutation matrix multiplication using distributed cache, for left input (mr/cp)
 		TSMM,     //transpose-self matrix multiplication (cp/mr/sp)
+		TSMM2,    //transpose-self matrix multiplication, 2-pass w/o shuffle (sp)
 		ZIPMM,    //zip matrix multiplication (sp)
 		MM        //in-memory matrix multiplication (cp)
 	};
@@ -200,7 +201,8 @@ public class AggBinaryOp extends Hop implements MultiThreadedHop
 				switch( _method )
 				{
 					case TSMM:
-						constructSparkLopsTSMM( mmtsj );
+					case TSMM2:	
+						constructSparkLopsTSMM( mmtsj, _method==MMultMethod.TSMM2 );
 						break;
 					case MAPMM_L:
 					case MAPMM_R:
@@ -564,7 +566,7 @@ public class AggBinaryOp extends Hop implements MultiThreadedHop
 		}
 		
 		Lop matmultCP = new MMTSJ(getInput().get(mmtsj.isLeft()?1:0).constructLops(),
-				                 getDataType(), getValueType(), et, mmtsj, k);
+				                 getDataType(), getValueType(), et, mmtsj, false, k);
 	
 		matmultCP.getOutputParameters().setDimensions(getDim1(), getDim2(), getRowsInBlock(), getColsInBlock(), getNnz());
 		setLineNumbers( matmultCP );
@@ -734,11 +736,12 @@ public class AggBinaryOp extends Hop implements MultiThreadedHop
 	 * @throws HopsException
 	 * @throws LopsException
 	 */
-	private void constructSparkLopsTSMM(MMTSJType mmtsj) 
+	private void constructSparkLopsTSMM(MMTSJType mmtsj, boolean multiPass) 
 		throws HopsException, LopsException
 	{
 		Hop input = getInput().get(mmtsj.isLeft()?1:0);
-		MMTSJ tsmm = new MMTSJ(input.constructLops(), getDataType(), getValueType(), ExecType.SPARK, mmtsj);
+		MMTSJ tsmm = new MMTSJ(input.constructLops(), getDataType(), 
+				getValueType(), ExecType.SPARK, mmtsj, multiPass);
 		setOutputDimensions(tsmm);
 		setLineNumbers(tsmm);
 		setLops(tsmm);
@@ -1886,13 +1889,30 @@ public class AggBinaryOp extends Hop implements MultiThreadedHop
 			}
 		}
 		
-		// Step 5: check for unknowns
+		// Step 5: check for TSMM2 (2 pass w/o suffle, preferred over CPMM/RMM)
+		if( mmtsj != MMTSJType.NONE && m1_rows >=0 && m1_cols>=0 
+			&& m2_rows >= 0 && m2_cols>=0 )
+		{
+			double mSize = (mmtsj == MMTSJType.LEFT) ? 
+					OptimizerUtils.estimateSizeExactSparsity(m2_rows, m2_cols-m2_cpb, 1.0) : 
+					OptimizerUtils.estimateSizeExactSparsity(m1_rows-m1_rpb, m1_cols, 1.0);	
+			double mSizeP = (mmtsj == MMTSJType.LEFT) ? 
+					OptimizerUtils.estimatePartitionedSizeExactSparsity(m2_rows, m2_cols-m2_cpb, m2_rpb, m2_cpb, 1.0) : 
+					OptimizerUtils.estimatePartitionedSizeExactSparsity(m1_rows-m1_rpb, m1_cols, m1_rpb, m1_cpb, 1.0); 
+			if( mSizeP < memBudgetExec && mSize+mSizeP < memBudgetLocal 
+				&& ((mmtsj == MMTSJType.LEFT) ? m2_cols<=2*m2_cpb : m1_rows<=2*m1_rpb) //4 output blocks
+				&& mSizeP < 2L*1024*1024*1024) { //2GB limitation as single broadcast
+				return MMultMethod.TSMM2;
+			}
+		}
+		
+		// Step 6: check for unknowns
 		// If the dimensions are unknown at compilation time, simply assume 
 		// the worst-case scenario and produce the most robust plan -- which is CPMM
 		if ( m1_rows == -1 || m1_cols == -1 || m2_rows == -1 || m2_cols == -1 )
 			return MMultMethod.CPMM;
 
-		// Step 6: check for ZIPMM
+		// Step 7: check for ZIPMM
 		// If t(X)%*%y -> t(t(y)%*%X) rewrite and ncol(X)<blocksize
 		if( tmmRewrite && m1_rows >= 0 && m1_rows <= m1_rpb  //blocksize constraint left
 			&& m2_cols >= 0 && m2_cols <= m2_cpb )           //blocksize constraint right	
@@ -1900,7 +1920,7 @@ public class AggBinaryOp extends Hop implements MultiThreadedHop
 			return MMultMethod.ZIPMM;
 		}
 			
-		// Step 7: Decide CPMM vs RMM based on io costs
+		// Step 8: Decide CPMM vs RMM based on io costs
 		//estimate shuffle costs weighted by parallelism
 		//TODO currently we reuse the mr estimates, these need to be fine-tune for our spark operators
 		double rmm_costs = getRMMCostEstimate(m1_rows, m1_cols, m1_rpb, m1_cpb, m2_rows, m2_cols, m2_rpb, m2_cpb);

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/8da70095/src/main/java/org/apache/sysml/lops/MMTSJ.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/lops/MMTSJ.java b/src/main/java/org/apache/sysml/lops/MMTSJ.java
index 207dd74..c6fd535 100644
--- a/src/main/java/org/apache/sysml/lops/MMTSJ.java
+++ b/src/main/java/org/apache/sysml/lops/MMTSJ.java
@@ -32,8 +32,6 @@ import org.apache.sysml.parser.Expression.*;
  */
 public class MMTSJ extends Lop 
 {
-
-	
 	public enum MMTSJType {
 		NONE,
 		LEFT,
@@ -45,20 +43,27 @@ public class MMTSJ extends Lop
 	}
 	
 	private MMTSJType _type = null;
+	private boolean _multiPass = false;
 	private int _numThreads = 1;
 
-	public MMTSJ(Lop input1, DataType dt, ValueType vt, ExecType et, MMTSJType type) 
-	{
-		this(input1, dt, vt, et, type, -1);
+	public MMTSJ(Lop input1, DataType dt, ValueType vt, ExecType et, MMTSJType type) {
+		this(input1, dt, vt, et, type, false, -1);
 	}
 	
-	public MMTSJ(Lop input1, DataType dt, ValueType vt, ExecType et, MMTSJType type, int k) 
-	{
+	public MMTSJ(Lop input1, DataType dt, ValueType vt, ExecType et, MMTSJType type, boolean multiPass) {
+		this(input1, dt, vt, et, type, multiPass, -1);
+	}
+	
+	public MMTSJ(Lop input1, DataType dt, ValueType vt, ExecType et, MMTSJType type, boolean multiPass, int k) {
 		super(Lop.Type.MMTSJ, dt, vt);		
 		addInput(input1);
 		input1.addOutput(this);
 		_type = type;
+		_multiPass = multiPass;
 		_numThreads = k;
+		
+		if( multiPass && et != ExecType.SPARK )
+			throw new RuntimeException("Multipass tsmm only supported for exec type SPARK.");
 		 
 		boolean breaksAlignment = true; //if result keys (matrix indexes) different 
 		boolean aligner = false; //if groups multiple inputs by key (e.g., group)
@@ -103,7 +108,7 @@ public class MMTSJ extends Lop
 		StringBuilder sb = new StringBuilder();
 		sb.append( getExecType() );
 		sb.append( OPERAND_DELIMITOR );
-		sb.append( "tsmm" );
+		sb.append( _multiPass ? "tsmm2" : "tsmm" );
 		sb.append( OPERAND_DELIMITOR );
 		sb.append( getInputs().get(0).prepInputOperand(input_index1));
 		sb.append( OPERAND_DELIMITOR );

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/8da70095/src/main/java/org/apache/sysml/runtime/instructions/SPInstructionParser.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/instructions/SPInstructionParser.java b/src/main/java/org/apache/sysml/runtime/instructions/SPInstructionParser.java
index a244288..9008f09 100644
--- a/src/main/java/org/apache/sysml/runtime/instructions/SPInstructionParser.java
+++ b/src/main/java/org/apache/sysml/runtime/instructions/SPInstructionParser.java
@@ -73,6 +73,7 @@ import org.apache.sysml.runtime.instructions.spark.RmmSPInstruction;
 import org.apache.sysml.runtime.instructions.spark.SPInstruction;
 import org.apache.sysml.runtime.instructions.spark.SPInstruction.SPINSTRUCTION_TYPE;
 import org.apache.sysml.runtime.instructions.spark.TernarySPInstruction;
+import org.apache.sysml.runtime.instructions.spark.Tsmm2SPInstruction;
 import org.apache.sysml.runtime.instructions.spark.TsmmSPInstruction;
 import org.apache.sysml.runtime.instructions.spark.QuantileSortSPInstruction;
 import org.apache.sysml.runtime.instructions.spark.UaggOuterChainSPInstruction;
@@ -117,7 +118,8 @@ public class SPInstructionParser extends InstructionParser
 		//binary aggregate operators (matrix multiplication operators)
 		String2SPInstructionType.put( "mapmm"      , SPINSTRUCTION_TYPE.MAPMM);
 		String2SPInstructionType.put( "mapmmchain" , SPINSTRUCTION_TYPE.MAPMMCHAIN);
-		String2SPInstructionType.put( "tsmm"       , SPINSTRUCTION_TYPE.TSMM);
+		String2SPInstructionType.put( "tsmm"       , SPINSTRUCTION_TYPE.TSMM); //single-pass tsmm
+		String2SPInstructionType.put( "tsmm2"      , SPINSTRUCTION_TYPE.TSMM2); //multi-pass tsmm
 		String2SPInstructionType.put( "cpmm"   	   , SPINSTRUCTION_TYPE.CPMM);
 		String2SPInstructionType.put( "rmm"        , SPINSTRUCTION_TYPE.RMM);
 		String2SPInstructionType.put( "pmm"        , SPINSTRUCTION_TYPE.PMM);
@@ -310,6 +312,8 @@ public class SPInstructionParser extends InstructionParser
 				return MapmmChainSPInstruction.parseInstruction(str);
 			case TSMM:
 				return TsmmSPInstruction.parseInstruction(str);
+			case TSMM2:
+				return Tsmm2SPInstruction.parseInstruction(str);	
 			case PMM:
 				return PmmSPInstruction.parseInstruction(str);
 			case ZIPMM:

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/8da70095/src/main/java/org/apache/sysml/runtime/instructions/spark/SPInstruction.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/instructions/spark/SPInstruction.java b/src/main/java/org/apache/sysml/runtime/instructions/spark/SPInstruction.java
index d5301e7..f766fd6 100644
--- a/src/main/java/org/apache/sysml/runtime/instructions/spark/SPInstruction.java
+++ b/src/main/java/org/apache/sysml/runtime/instructions/spark/SPInstruction.java
@@ -37,7 +37,7 @@ public abstract class SPInstruction extends Instruction
 {
 	
 	public enum SPINSTRUCTION_TYPE { 
-		MAPMM, MAPMMCHAIN, CPMM, RMM, TSMM, PMM, ZIPMM, PMAPMM, //matrix multiplication instructions  
+		MAPMM, MAPMMCHAIN, CPMM, RMM, TSMM, TSMM2, PMM, ZIPMM, PMAPMM, //matrix multiplication instructions  
 		MatrixIndexing, Reorg, ArithmeticBinary, RelationalBinary, AggregateUnary, AggregateTernary, Reblock, CSVReblock, 
 		Builtin, BuiltinUnary, BuiltinBinary, MultiReturnBuiltin, Checkpoint, Compression, Cast,
 		CentralMoment, Covariance, QSort, QPick, 

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/8da70095/src/main/java/org/apache/sysml/runtime/instructions/spark/Tsmm2SPInstruction.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/instructions/spark/Tsmm2SPInstruction.java b/src/main/java/org/apache/sysml/runtime/instructions/spark/Tsmm2SPInstruction.java
new file mode 100644
index 0000000..120faa6
--- /dev/null
+++ b/src/main/java/org/apache/sysml/runtime/instructions/spark/Tsmm2SPInstruction.java
@@ -0,0 +1,293 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sysml.runtime.instructions.spark;
+
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.spark.api.java.JavaPairRDD;
+import org.apache.spark.api.java.function.PairFlatMapFunction;
+import org.apache.spark.api.java.function.PairFunction;
+import org.apache.spark.broadcast.Broadcast;
+import org.apache.sysml.hops.OptimizerUtils;
+import org.apache.sysml.lops.MMTSJ.MMTSJType;
+import org.apache.sysml.runtime.DMLRuntimeException;
+import org.apache.sysml.runtime.controlprogram.context.ExecutionContext;
+import org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext;
+import org.apache.sysml.runtime.functionobjects.Multiply;
+import org.apache.sysml.runtime.functionobjects.Plus;
+import org.apache.sysml.runtime.instructions.InstructionUtils;
+import org.apache.sysml.runtime.instructions.cp.CPOperand;
+import org.apache.sysml.runtime.instructions.spark.data.PartitionedBlock;
+import org.apache.sysml.runtime.instructions.spark.functions.IsBlockInRange;
+import org.apache.sysml.runtime.instructions.spark.utils.RDDAggregateUtils;
+import org.apache.sysml.runtime.matrix.MatrixCharacteristics;
+import org.apache.sysml.runtime.matrix.data.LibMatrixReorg;
+import org.apache.sysml.runtime.matrix.data.MatrixBlock;
+import org.apache.sysml.runtime.matrix.data.MatrixIndexes;
+import org.apache.sysml.runtime.matrix.data.OperationsOnMatrixValues;
+import org.apache.sysml.runtime.matrix.operators.AggregateBinaryOperator;
+import org.apache.sysml.runtime.matrix.operators.AggregateOperator;
+import org.apache.sysml.runtime.matrix.operators.Operator;
+
+import scala.Tuple2;
+
+/**
+ * 
+ */
+public class Tsmm2SPInstruction extends UnarySPInstruction 
+{
+	private MMTSJType _type = null;
+	
+	public Tsmm2SPInstruction(Operator op, CPOperand in1, CPOperand out, MMTSJType type, String opcode, String istr )
+	{
+		super(op, in1, out, opcode, istr);
+		_sptype = SPINSTRUCTION_TYPE.TSMM2;		
+		_type = type;
+	}
+
+	/**
+	 * 
+	 * @param str
+	 * @return
+	 * @throws DMLRuntimeException
+	 */
+	public static Tsmm2SPInstruction parseInstruction( String str ) 
+		throws DMLRuntimeException 
+	{
+		String parts[] = InstructionUtils.getInstructionPartsWithValueType(str);
+		String opcode = parts[0];
+		
+		//check supported opcode 
+		if ( !opcode.equalsIgnoreCase("tsmm2") ) {
+			throw new DMLRuntimeException("Tsmm2SPInstruction.parseInstruction():: Unknown opcode " + opcode);			
+		}
+			
+		CPOperand in1 = new CPOperand(parts[1]);
+		CPOperand out = new CPOperand(parts[2]);
+		MMTSJType type = MMTSJType.valueOf(parts[3]);
+		
+		return new Tsmm2SPInstruction(null, in1, out, type, opcode, str);
+	}
+	
+	@Override
+	public void processInstruction(ExecutionContext ec) 
+		throws DMLRuntimeException
+	{	
+		SparkExecutionContext sec = (SparkExecutionContext)ec;
+		
+		//get input
+		JavaPairRDD<MatrixIndexes,MatrixBlock> in = sec.getBinaryBlockRDDHandleForVariable( input1.getName() );
+		MatrixCharacteristics mc = sec.getMatrixCharacteristics( input1.getName() );
+		
+		//execute tsmm2 instruction 
+		//step 1: first pass of X, filter-collect-broadcast excess blocks 
+		JavaPairRDD<MatrixIndexes,MatrixBlock> tmp1 = 
+			in.filter(new IsBlockInRange(_type.isLeft() ? 1 : mc.getRowsPerBlock()+1, mc.getRows(), 
+					_type.isLeft() ? mc.getColsPerBlock()+1 : 1, mc.getCols(), mc))
+			  .mapToPair(new ShiftTSMMIndexesFunction(_type));		
+		PartitionedBlock<MatrixBlock> pmb = SparkExecutionContext.toPartitionedMatrixBlock(tmp1, 
+				(int)(_type.isLeft() ? mc.getRows() : mc.getRows() - mc.getRowsPerBlock()), 
+				(int)(_type.isLeft() ? mc.getCols()-mc.getColsPerBlock() : mc.getCols()), 
+				mc.getRowsPerBlock(), mc.getColsPerBlock(), -1L);
+		Broadcast<PartitionedBlock<MatrixBlock>> bpmb = sec.getSparkContext().broadcast(pmb);
+		
+		//step 2: second pass of X, compute tsmm/mapmm and aggregate result blocks
+		int outputDim = (int) (_type.isLeft() ? mc.getCols() : mc.getRows());
+		if( OptimizerUtils.estimateSize(outputDim, outputDim) <= 32*1024*1024 ) { //default: <=32MB
+			//output large blocks and reduceAll to avoid skew on combineByKey
+			JavaPairRDD<MatrixIndexes,MatrixBlock> tmp2 = in.mapToPair(
+					new RDDTSMM2ExtFunction(bpmb, _type, outputDim, (int)mc.getRowsPerBlock()));
+			MatrixBlock out = RDDAggregateUtils.sumStable(tmp2);
+		      
+			//put output block into symbol table (no lineage because single block)
+			//this also includes implicit maintenance of matrix characteristics
+			sec.setMatrixOutput(output.getName(), out);
+		}
+		else {
+			//output individual output blocks and aggregate by key (no action)
+			JavaPairRDD<MatrixIndexes,MatrixBlock> tmp2 = in.flatMapToPair(new RDDTSMM2Function(bpmb, _type));
+			JavaPairRDD<MatrixIndexes,MatrixBlock> out = RDDAggregateUtils.sumByKeyStable(tmp2);
+			
+			//put output RDD handle into symbol table
+			sec.getMatrixCharacteristics(output.getName()).set(outputDim, outputDim, mc.getRowsPerBlock(), mc.getColsPerBlock());
+			sec.setRDDHandleForVariable(output.getName(), out);	
+			sec.addLineageRDD(output.getName(), input1.getName());	
+		}
+	}
+	
+	/**
+	 * 
+	 */
+	private static class RDDTSMM2Function implements PairFlatMapFunction<Tuple2<MatrixIndexes, MatrixBlock>, MatrixIndexes, MatrixBlock> 
+	{
+		private static final long serialVersionUID = 2935770425858019666L;
+		
+		private Broadcast<PartitionedBlock<MatrixBlock>> _pb = null;
+		private MMTSJType _type = null;
+		private AggregateBinaryOperator _op = null;
+		
+		public RDDTSMM2Function( Broadcast<PartitionedBlock<MatrixBlock>> pb, MMTSJType type ) {
+			_pb = pb;
+			_type = type;
+			
+			//created operator for reuse
+			AggregateOperator agg = new AggregateOperator(0, Plus.getPlusFnObject());
+			_op = new AggregateBinaryOperator(Multiply.getMultiplyFnObject(), agg);
+		}
+
+		@Override
+		public Iterable<Tuple2<MatrixIndexes, MatrixBlock>> call(Tuple2<MatrixIndexes, MatrixBlock> arg0)
+			throws Exception 
+		{
+			List<Tuple2<MatrixIndexes,MatrixBlock>> ret = new ArrayList<Tuple2<MatrixIndexes,MatrixBlock>>();
+			MatrixIndexes ixin = arg0._1();
+			MatrixBlock mbin = arg0._2();
+			
+			//execute block tsmm operation
+			MatrixBlock out1 = mbin.transposeSelfMatrixMultOperations(new MatrixBlock(), _type);
+			long ixout = _type.isLeft() ? ixin.getColumnIndex() : ixin.getRowIndex();
+			ret.add(new Tuple2<MatrixIndexes, MatrixBlock>(new MatrixIndexes(ixout, ixout), out1));
+			
+			if( _type.isLeft() ? ixin.getColumnIndex() == 1 : ixin.getRowIndex() == 1 ) {
+				//execute block mapmm operation for full block only (output two blocks, due to symmetry)
+				MatrixBlock mbin2 = _pb.getValue().getBlock( //lookup broadcast block
+						(int)(_type.isLeft()?ixin.getRowIndex():1), 
+						(int)(_type.isLeft()?1:ixin.getColumnIndex()));
+				MatrixBlock mbin2t = transpose(mbin2, new MatrixBlock()); //prep for transpose rewrite mm
+				
+				MatrixBlock out2 = (MatrixBlock) OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes( //mm
+						_type.isLeft() ? mbin2t : mbin, _type.isLeft() ? mbin : mbin2t, new MatrixBlock(), _op);
+				MatrixIndexes ixout2 = _type.isLeft() ? new MatrixIndexes(2,1) : new MatrixIndexes(1,2);
+				ret.add(new Tuple2<MatrixIndexes,MatrixBlock>(ixout2, out2));
+				
+				MatrixBlock out3 = transpose(out2, new MatrixBlock()); 
+				MatrixIndexes ixout3 = _type.isLeft() ? new MatrixIndexes(1,2) : new MatrixIndexes(2,1);
+				ret.add(new Tuple2<MatrixIndexes,MatrixBlock>(ixout3, out3));
+			}
+			
+			return ret;
+		}
+	}
+
+	/**
+	 * Same semantics as RDDTSMM2Function but output single consolidated block.
+	 * 
+	 */
+	private static class RDDTSMM2ExtFunction implements PairFunction<Tuple2<MatrixIndexes, MatrixBlock>, MatrixIndexes, MatrixBlock> 
+	{
+		private static final long serialVersionUID = 3284059592407517911L;
+		
+		private Broadcast<PartitionedBlock<MatrixBlock>> _pb = null;
+		private MMTSJType _type = null;
+		private AggregateBinaryOperator _op = null;
+		private int _outputDim = -1;
+		private int _blen = -1; 
+		
+		public RDDTSMM2ExtFunction( Broadcast<PartitionedBlock<MatrixBlock>> pb, MMTSJType type, int outputDim, int blen ) {
+			_pb = pb;
+			_type = type;
+			_outputDim = outputDim;
+			_blen = blen;
+			
+			//created operator for reuse
+			AggregateOperator agg = new AggregateOperator(0, Plus.getPlusFnObject());
+			_op = new AggregateBinaryOperator(Multiply.getMultiplyFnObject(), agg);
+		}
+
+		@Override
+		public Tuple2<MatrixIndexes, MatrixBlock> call(Tuple2<MatrixIndexes, MatrixBlock> arg0)
+			throws Exception 
+		{
+			MatrixIndexes ixin = arg0._1();
+			MatrixBlock mbin = arg0._2();
+			
+			boolean fullBlock = _type.isLeft() ? ixin.getColumnIndex() == 1 : ixin.getRowIndex() == 1;
+			MatrixBlock out = new MatrixBlock(_outputDim, _outputDim, !fullBlock);
+			out.allocateDenseOrSparseBlock();
+			
+			//execute block tsmm operation
+			MatrixBlock out1 = mbin.transposeSelfMatrixMultOperations(new MatrixBlock(), _type);
+			int ix = (int) ((_type.isLeft() ? ixin.getColumnIndex() : ixin.getRowIndex())-1) * _blen;
+			out.copy(ix, ix+out1.getNumRows()-1, ix, ix+out1.getNumColumns()-1, out1, true);
+			
+			if( fullBlock ) {
+				//execute block mapmm operation for full block only (output two blocks, due to symmetry)
+				MatrixBlock mbin2 = _pb.getValue().getBlock( //lookup broadcast block
+						(int)(_type.isLeft()?ixin.getRowIndex():1), 
+						(int)(_type.isLeft()?1:ixin.getColumnIndex()));
+				MatrixBlock mbin2t = transpose(mbin2, new MatrixBlock()); //prep for transpose rewrite mm
+				
+				MatrixBlock out2 = (MatrixBlock) OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes( //mm
+						_type.isLeft() ? mbin2t : mbin, _type.isLeft() ? mbin : mbin2t, new MatrixBlock(), _op);
+				
+				MatrixIndexes ixout2 = _type.isLeft() ? new MatrixIndexes(2,1) : new MatrixIndexes(1,2);
+				out.copy((int)(ixout2.getRowIndex()-1)*_blen, (int)(ixout2.getRowIndex()-1)*_blen+out2.getNumRows()-1, 
+						(int)(ixout2.getColumnIndex()-1)*_blen, (int)(ixout2.getColumnIndex()-1)*_blen+out2.getNumColumns()-1, out2, true);
+				MatrixBlock out3 = transpose(out2, new MatrixBlock()); 
+				out.copy((int)(ixout2.getColumnIndex()-1)*_blen, (int)(ixout2.getColumnIndex()-1)*_blen+out3.getNumRows()-1, 
+						(int)(ixout2.getRowIndex()-1)*_blen, (int)(ixout2.getRowIndex()-1)*_blen+out3.getNumColumns()-1, out3, true);
+			}
+			
+			return new Tuple2<MatrixIndexes,MatrixBlock>(new MatrixIndexes(1,1), out);
+		}
+	}
+	
+	/**
+	 * 
+	 */
+	private static class ShiftTSMMIndexesFunction implements PairFunction<Tuple2<MatrixIndexes, MatrixBlock>, MatrixIndexes, MatrixBlock> 
+	{
+		private static final long serialVersionUID = -3858454295795680100L;
+		
+		private MMTSJType _type = null;
+		
+		public ShiftTSMMIndexesFunction( MMTSJType type ) {
+			_type = type;
+		}
+
+		@Override
+		public Tuple2<MatrixIndexes, MatrixBlock> call(Tuple2<MatrixIndexes, MatrixBlock> arg0)
+			throws Exception 
+		{
+			if( _type.isLeft() )
+				return new Tuple2<MatrixIndexes,MatrixBlock>(new MatrixIndexes(arg0._1().getRowIndex(), 1), arg0._2());
+			else
+				return new Tuple2<MatrixIndexes,MatrixBlock>(new MatrixIndexes(1, arg0._1().getColumnIndex()), arg0._2());	
+		}
+	}	
+	
+	/**
+	 * Helper function to setup output dimensions.
+	 * 
+	 * @param in
+	 * @return
+	 * @throws DMLRuntimeException 
+	 */
+	private static MatrixBlock transpose(MatrixBlock in, MatrixBlock out) throws DMLRuntimeException {
+		if( out == null )
+			out = new MatrixBlock(in.getNumColumns(), in.getNumRows(), in.getNonZeros());
+		else
+			out.reset(in.getNumColumns(), in.getNumRows(), in.getNonZeros());
+		
+		return LibMatrixReorg.transpose(in, out);
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/8da70095/src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java b/src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java
index bd457ca..20e887b 100644
--- a/src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java
+++ b/src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java
@@ -291,13 +291,17 @@ public class OperationsOnMatrixValues
 			value1.aggregateBinaryOperations(indexes1, value1, indexes2, value2, valueOut, op);
 	}
 
-	public static void performAggregateBinaryIgnoreIndexes(
+	public static MatrixValue performAggregateBinaryIgnoreIndexes(
 			MatrixValue value1, MatrixValue value2,
 			MatrixValue valueOut, AggregateBinaryOperator op) 
 	throws DMLRuntimeException {
 			
 		//perform on the value
-		value1.aggregateBinaryOperations(value1, value2, valueOut, op);
+		if( value2 instanceof CompressedMatrixBlock )
+			value2.aggregateBinaryOperations(value1, value2, valueOut, op);
+		else
+			value1.aggregateBinaryOperations(value1, value2, valueOut, op);
+		return valueOut;
 	}
 	
 	/**

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/8da70095/src/test/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/FullMatrixMultiplicationTransposeSelf2Test.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/FullMatrixMultiplicationTransposeSelf2Test.java b/src/test/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/FullMatrixMultiplicationTransposeSelf2Test.java
new file mode 100644
index 0000000..491e052
--- /dev/null
+++ b/src/test/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/FullMatrixMultiplicationTransposeSelf2Test.java
@@ -0,0 +1,213 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sysml.test.integration.functions.binary.matrix_full_other;
+
+import java.util.HashMap;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.apache.sysml.api.DMLScript;
+import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;
+import org.apache.sysml.hops.AggBinaryOp;
+import org.apache.sysml.hops.AggBinaryOp.MMultMethod;
+import org.apache.sysml.lops.LopProperties.ExecType;
+import org.apache.sysml.lops.MMTSJ.MMTSJType;
+import org.apache.sysml.runtime.instructions.Instruction;
+import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;
+import org.apache.sysml.test.integration.AutomatedTestBase;
+import org.apache.sysml.test.integration.TestConfiguration;
+import org.apache.sysml.test.utils.TestUtils;
+import org.apache.sysml.utils.Statistics;
+
+/**
+ * This testcase validates the new tsmm2 (spark only) instruction. We test against
+ * all backends to ensure this operator is not mistakenly compiled for MR/CP. 
+ * 
+ */
+public class FullMatrixMultiplicationTransposeSelf2Test extends AutomatedTestBase 
+{
+	private final static String TEST_NAME1 = "TransposeSelfMatrixMultiplication1";
+	private final static String TEST_NAME2 = "TransposeSelfMatrixMultiplication2";
+	private final static String TEST_DIR = "functions/binary/matrix_full_other/";
+	private final static String TEST_CLASS_DIR = TEST_DIR + FullMatrixMultiplicationTransposeSelf2Test.class.getSimpleName() + "/";
+	private final static double eps = 1e-10;
+	
+	private final static int rows1 = 2105;
+	private final static int cols1 = 1003; //multi-block, but excess fits in broadcast
+	
+	private final static double sparsity1 = 0.64;
+	private final static double sparsity2 = 0.07;
+	
+	
+	@Override
+	public void setUp() {
+		TestUtils.clearAssertionInformation();
+		addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { "B" })); 
+		addTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] { "B" })); 
+		if (TEST_CACHE_ENABLED)
+			setOutAndExpectedDeletionDisabled(true);
+	}
+
+	@BeforeClass
+	public static void init() {
+		TestUtils.clearDirectory(TEST_DATA_DIR + TEST_CLASS_DIR);
+	}
+
+	@AfterClass
+	public static void cleanUp() {
+		if (TEST_CACHE_ENABLED)
+			TestUtils.clearDirectory(TEST_DATA_DIR + TEST_CLASS_DIR);
+	}
+
+	@Test
+	public void testTSMMLeftDenseCP() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.LEFT, ExecType.CP, false);
+	}
+	
+	@Test
+	public void testTSMMLeftSparseCP() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.LEFT, ExecType.CP, true);
+	}
+	
+	@Test
+	public void testTSMMRightDenseCP() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.RIGHT, ExecType.CP, false);
+	}
+	
+	@Test
+	public void testTSMMRightSparseCP() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.RIGHT, ExecType.CP, true);
+	}
+	
+	@Test
+	public void testTSMMLeftDenseSP() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.LEFT, ExecType.SPARK, false);
+	}
+	
+	@Test
+	public void testTSMMLeftSparseSP() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.LEFT, ExecType.SPARK, true);
+	}
+	
+	@Test
+	public void testTSMMRightDenseSP() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.RIGHT, ExecType.SPARK, false);
+	}
+	
+	@Test
+	public void testTSMMRightSparseSP() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.RIGHT, ExecType.SPARK, true);
+	}
+	
+	@Test
+	public void testTSMMLeftDenseMR() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.LEFT, ExecType.MR, false);
+	}
+	
+	@Test
+	public void testTSMMLeftSparseMR() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.LEFT, ExecType.MR, true);
+	}
+	
+	@Test
+	public void testTSMMRightDenseMR() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.RIGHT, ExecType.MR, false);
+	}
+	
+	@Test
+	public void testTSMMRightSparseMR() {
+		runTransposeSelfMatrixMultiplicationTest(MMTSJType.RIGHT, ExecType.MR, true);
+	}
+	
+
+	/**
+	 * 
+	 * @param type
+	 * @param instType
+	 * @param sparse
+	 */
+	private void runTransposeSelfMatrixMultiplicationTest( MMTSJType type, ExecType instType, boolean sparse )
+	{
+		RUNTIME_PLATFORM platformOld = rtplatform;
+		switch( instType ){
+			case MR: rtplatform = RUNTIME_PLATFORM.HADOOP; break;
+			case SPARK: rtplatform = RUNTIME_PLATFORM.SPARK; break;
+			default: rtplatform = RUNTIME_PLATFORM.HYBRID; break;
+		}
+	
+		boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
+		if( rtplatform == RUNTIME_PLATFORM.SPARK )
+			DMLScript.USE_LOCAL_SPARK_CONFIG = true;
+
+		if( instType == ExecType.SPARK ) //force tsmm2 to prevent mapmm
+			AggBinaryOp.FORCED_MMULT_METHOD = MMultMethod.TSMM2;
+		
+		//setup exec type, rows, cols, caching dir
+		int rows = (type == MMTSJType.LEFT) ? rows1 : cols1;
+		int cols = (type == MMTSJType.LEFT) ? cols1 : rows1;
+		double sparsity = sparse ? sparsity2 : sparsity1;
+		String TEST_NAME = (type == MMTSJType.LEFT) ? TEST_NAME1 : TEST_NAME2;
+		
+		String TEST_CACHE_DIR = "";
+		if (TEST_CACHE_ENABLED)
+			TEST_CACHE_DIR = rows + "_" + cols + "_" + sparsity + "/";
+		
+		try
+		{
+			TestConfiguration config = getTestConfiguration(TEST_NAME);
+			loadTestConfiguration(config, TEST_CACHE_DIR);
+			
+			/* This is for running the junit test the new way, i.e., construct the arguments directly */
+			String HOME = SCRIPT_DIR + TEST_DIR;
+			fullDMLScriptName = HOME + TEST_NAME + ".dml";
+			programArgs = new String[]{"-stats", "-args", input("A"),
+				Integer.toString(rows), Integer.toString(cols), output("B") };
+			
+			fullRScriptName = HOME + TEST_NAME + ".R";
+			rCmd = "Rscript" + " " + fullRScriptName + " " + inputDir() + " " + expectedDir();
+	
+			//generate actual dataset
+			double[][] A = getRandomMatrix(rows, cols, 0, 1, sparsity, 7); 
+			writeInputMatrix("A", A, true);
+	
+			//run dml and R scripts
+			runTest(true, false, null, -1); 
+			runRScript(true); 
+			
+			//compare matrices 
+			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("B");
+			HashMap<CellIndex, Double> rfile  = readRMatrixFromFS("B");
+			TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R");
+		
+			//check for compiled tsmm instructions
+			if( instType == ExecType.SPARK || instType == ExecType.CP ) {
+				String opcode = (instType==ExecType.SPARK) ? Instruction.SP_INST_PREFIX + "tsmm2" : "tsmm";
+				Assert.assertTrue("Missing opcode: "+opcode, Statistics.getCPHeavyHitterOpCodes().contains(opcode) );
+			}
+		}
+		finally {
+			DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
+			AggBinaryOp.FORCED_MMULT_METHOD = null;
+			rtplatform = platformOld;
+		}
+	}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/8da70095/src/test_suites/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/ZPackageSuite.java
----------------------------------------------------------------------
diff --git a/src/test_suites/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/ZPackageSuite.java b/src/test_suites/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/ZPackageSuite.java
index 876327d..97666de 100644
--- a/src/test_suites/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/ZPackageSuite.java
+++ b/src/test_suites/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/ZPackageSuite.java
@@ -31,6 +31,7 @@ import org.junit.runners.Suite;
 	FullIntegerDivisionTest.class,
 	FullMatrixMultiplicationTest.class,
 	FullMatrixMultiplicationTransposeSelfTest.class,
+	FullMatrixMultiplicationTransposeSelf2Test.class,
 	FullMinMaxComparisonTest.class,
 	FullPowerTest.class,
 	FullPPredMatrixTest.class,


[2/2] incubator-systemml git commit: [SYSTEMML-1008] Fix removeEmpty w/ select vector (empty input handling)

Posted by mb...@apache.org.
[SYSTEMML-1008] Fix removeEmpty w/ select vector (empty input handling)

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

Branch: refs/heads/master
Commit: 4e0949bae4724987d9486449796bdf6675e11f4a
Parents: 8da7009
Author: Matthias Boehm <mb...@us.ibm.com>
Authored: Mon Oct 3 18:47:11 2016 -0700
Committer: Matthias Boehm <mb...@us.ibm.com>
Committed: Mon Oct 3 18:47:11 2016 -0700

----------------------------------------------------------------------
 .../runtime/matrix/data/LibMatrixReorg.java     |   8 +-
 .../unary/matrix/RemoveEmptySelTest.java        | 161 +++++++++++++++++++
 .../functions/unary/matrix/removeEmptySel.dml   |  35 ++++
 .../functions/unary/matrix/ZPackageSuite.java   |   1 +
 4 files changed, 203 insertions(+), 2 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/4e0949ba/src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java
----------------------------------------------------------------------
diff --git a/src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java b/src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java
index 179f835..af30af8 100644
--- a/src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java
+++ b/src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java
@@ -596,7 +596,7 @@ public class LibMatrixReorg
 		//check for empty inputs 
 		//(the semantics of removeEmpty are that for an empty m-by-n matrix, the output 
 		//is an empty 1-by-n or m-by-1 matrix because we don't allow matrices with dims 0)
-		if( in.isEmptyBlock(false) ) {
+		if( in.isEmptyBlock(false) && select == null  ) {
 			if( rows )
 				ret.reset(1, in.clen, in.sparse);
 			else //cols
@@ -1947,6 +1947,8 @@ public class LibMatrixReorg
 		rlen2 = Math.max(rlen2, 1); //ensure valid output
 		boolean sp = MatrixBlock.evalSparseFormatInMemory(rlen2, n, in.nonZeros);
 		ret.reset(rlen2, n, sp);
+		if( in.isEmptyBlock(false) )
+			return ret;
 		
 		if( in.sparse ) //* <- SPARSE
 		{
@@ -2055,7 +2057,9 @@ public class LibMatrixReorg
 		clen2 = Math.max(clen2, 1); //ensure valid output
 		boolean sp = MatrixBlock.evalSparseFormatInMemory(m, clen2, in.nonZeros);
 		ret.reset(m, clen2, sp);
-			
+		if( in.isEmptyBlock(false) )
+			return ret;
+		
 		if( in.sparse ) //* <- SPARSE 
 		{
 			//note: output dense or sparse

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/4e0949ba/src/test/java/org/apache/sysml/test/integration/functions/unary/matrix/RemoveEmptySelTest.java
----------------------------------------------------------------------
diff --git a/src/test/java/org/apache/sysml/test/integration/functions/unary/matrix/RemoveEmptySelTest.java b/src/test/java/org/apache/sysml/test/integration/functions/unary/matrix/RemoveEmptySelTest.java
new file mode 100644
index 0000000..cba0e99
--- /dev/null
+++ b/src/test/java/org/apache/sysml/test/integration/functions/unary/matrix/RemoveEmptySelTest.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sysml.test.integration.functions.unary.matrix;
+
+import java.util.HashMap;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.apache.sysml.api.DMLScript;
+import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;
+import org.apache.sysml.lops.LopProperties.ExecType;
+import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;
+import org.apache.sysml.test.integration.AutomatedTestBase;
+import org.apache.sysml.test.integration.TestConfiguration;
+import org.apache.sysml.test.utils.TestUtils;
+
+public class RemoveEmptySelTest extends AutomatedTestBase 
+{
+	private final static String TEST_NAME = "removeEmptySel";
+	private final static String TEST_DIR = "functions/unary/matrix/";
+	private static final String TEST_CLASS_DIR = TEST_DIR + RemoveEmptySelTest.class.getSimpleName() + "/";
+
+	private final static int rows = 1007;
+	private final static int cols = 1005;
+	
+	@Override
+	public void setUp() {
+		TestUtils.clearAssertionInformation();
+		addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] { "R" }) );
+	}
+	
+	@Test
+	public void testRemoveEmptyRowSelCP() {
+		runTestRemoveEmptySel( "rows", ExecType.CP, false );
+	}
+	
+	@Test
+	public void testRemoveEmptyRowSelEmptyCP() {
+		runTestRemoveEmptySel( "rows", ExecType.CP, true );
+	}
+	
+	@Test
+	public void testRemoveEmptyColSelCP() {
+		runTestRemoveEmptySel( "cols", ExecType.CP, false );
+	}
+	
+	@Test
+	public void testRemoveEmptyColSelEmptyCP() {
+		runTestRemoveEmptySel( "cols", ExecType.CP, true );
+	}
+	
+	@Test
+	public void testRemoveEmptyRowSelSP() {
+		runTestRemoveEmptySel( "rows", ExecType.SPARK, false );
+	}
+	
+	@Test
+	public void testRemoveEmptyRowSelEmptySP() {
+		runTestRemoveEmptySel( "rows", ExecType.SPARK, true );
+	}
+	
+	@Test
+	public void testRemoveEmptyColSelSP() {
+		runTestRemoveEmptySel( "cols", ExecType.SPARK, false );
+	}
+	
+	@Test
+	public void testRemoveEmptyColSelEmptySP() {
+		runTestRemoveEmptySel( "cols", ExecType.SPARK, true );
+	}
+
+	@Test
+	public void testRemoveEmptyRowSelMR() {
+		runTestRemoveEmptySel( "rows", ExecType.MR, false );
+	}
+	
+	@Test
+	public void testRemoveEmptyRowSelEmptyMR() {
+		runTestRemoveEmptySel( "rows", ExecType.MR, true );
+	}
+	
+	@Test
+	public void testRemoveEmptyColSelMR() {
+		runTestRemoveEmptySel( "cols", ExecType.MR, false );
+	}
+	
+	@Test
+	public void testRemoveEmptyColSelEmptyMR() {
+		runTestRemoveEmptySel( "cols", ExecType.MR, true );
+	}
+	
+	/**
+	 * 
+	 * @param testname
+	 * @param margin
+	 * @param et
+	 * @param sparse
+	 * @param empty
+	 */
+	private void runTestRemoveEmptySel( String margin, ExecType et, boolean empty )
+	{		
+		//rtplatform for MR
+		RUNTIME_PLATFORM platformOld = rtplatform;
+		switch( et ){
+			case MR: rtplatform = RUNTIME_PLATFORM.HADOOP; break;
+			case SPARK: rtplatform = RUNTIME_PLATFORM.SPARK; break;
+			default: rtplatform = RUNTIME_PLATFORM.HYBRID; break;
+		}
+	
+		boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;
+		if( rtplatform == RUNTIME_PLATFORM.SPARK )
+			DMLScript.USE_LOCAL_SPARK_CONFIG = true;
+		
+		try
+		{	
+			//register test configuration
+			TestConfiguration config = getTestConfiguration(TEST_NAME);
+			config.addVariable("rows", rows);
+			config.addVariable("cols", cols);
+			loadTestConfiguration(config);
+			
+			String HOME = SCRIPT_DIR + TEST_DIR;
+			fullDMLScriptName = HOME + TEST_NAME + ".dml";
+			programArgs = new String[]{"-stats", "-args", Integer.toString(empty?0:1), 
+					Integer.toString(rows), Integer.toString(cols), margin, output("R") };
+		
+			//run dml test
+			runTest(true, false, null, -1);
+	
+			//compare expected dimensions
+			HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("R");
+			Double expectedRows = (double) (margin.equals("rows") ? rows/2 : rows);
+			Double expectedCols = (double) (margin.equals("cols") ? cols/2 : cols);
+			Assert.assertEquals("Wrong output nrow.", expectedRows, dmlfile.get(new CellIndex(1,1)));
+			Assert.assertEquals("Wrong output ncol.", expectedCols, dmlfile.get(new CellIndex(2,1)));			
+		}
+		finally
+		{
+			//reset platform for additional tests
+			rtplatform = platformOld;
+			DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;
+		}
+	}	
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/4e0949ba/src/test/scripts/functions/unary/matrix/removeEmptySel.dml
----------------------------------------------------------------------
diff --git a/src/test/scripts/functions/unary/matrix/removeEmptySel.dml b/src/test/scripts/functions/unary/matrix/removeEmptySel.dml
new file mode 100644
index 0000000..297914e
--- /dev/null
+++ b/src/test/scripts/functions/unary/matrix/removeEmptySel.dml
@@ -0,0 +1,35 @@
+#-------------------------------------------------------------
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+# 
+#   http://www.apache.org/licenses/LICENSE-2.0
+# 
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#
+#-------------------------------------------------------------
+
+
+V = matrix($1, rows=$2, cols=$3);
+if( $4=="rows" ) {
+  S = matrix(0, rows=nrow(V), cols=1)
+  S[1:(nrow(V)/2),] = matrix(1, rows=nrow(V)/2, cols=1);
+}  
+else { 
+  S = matrix(0, rows=1, cols=ncol(V))
+  S[,1:(ncol(V)/2)] = matrix(1, rows=1, cols=ncol(V)/2);
+}
+
+Vp = removeEmpty(target=V, margin=$4, select=S);
+R = rbind(as.matrix(nrow(Vp)), as.matrix(ncol(Vp)));
+write(R, $5);  

http://git-wip-us.apache.org/repos/asf/incubator-systemml/blob/4e0949ba/src/test_suites/java/org/apache/sysml/test/integration/functions/unary/matrix/ZPackageSuite.java
----------------------------------------------------------------------
diff --git a/src/test_suites/java/org/apache/sysml/test/integration/functions/unary/matrix/ZPackageSuite.java b/src/test_suites/java/org/apache/sysml/test/integration/functions/unary/matrix/ZPackageSuite.java
index dac067d..65bc06b 100644
--- a/src/test_suites/java/org/apache/sysml/test/integration/functions/unary/matrix/ZPackageSuite.java
+++ b/src/test_suites/java/org/apache/sysml/test/integration/functions/unary/matrix/ZPackageSuite.java
@@ -48,6 +48,7 @@ import org.junit.runners.Suite;
 	NegationTest.class,
 	PrintTest.class,
 	QRSolverTest.class,
+	RemoveEmptySelTest.class,
 	RemoveEmptyTest.class,
 	ReplaceTest.class,
 	RoundTest.class,