author
int64 658
755k
| date
stringlengths 19
19
| timezone
int64 -46,800
43.2k
| hash
stringlengths 40
40
| message
stringlengths 5
490
| mods
list | language
stringclasses 20
values | license
stringclasses 3
values | repo
stringlengths 5
68
| original_message
stringlengths 12
491
|
---|---|---|---|---|---|---|---|---|---|
49,758 | 15.10.2019 22:56:02 | -7,200 | 656c4686035fc2241e00c2974226c1a6b678c2fd | Parallel implementation of sort() (invoked by DML function order() )
Closes | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -17,6 +17,9 @@ maven-eclipse.xml\n*.iml\n*.iws\n+# vscode\n+.vscode\n+\n# checksum files\n*.crc\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -139,5 +139,8 @@ SYSTEMDS-180 New Builtin Functions II OK\n* 188 Builtin function ALS\n+SYSTEMDS-190 Ramp-Up Tasks\n+* 191 Parallel Sort OK\n+\nOthers:\n* Break append instruction to cbind and rbind\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/ReorgOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/ReorgOp.java",
"diff": "@@ -189,26 +189,29 @@ public class ReorgOp extends MultiThreadedHop\n}\ncase SORT:\n{\n- Hop input = getInput().get(0);\n- Hop by = getInput().get(1);\n- Hop desc = getInput().get(2);\n- Hop ixret = getInput().get(3);\n+ Lop[] linputs = new Lop[4]; //input, by, desc, ixret\n+ for (int i = 0; i < 4; i++)\n+ linputs[i] = getInput().get(i).constructLops();\n+ Hop by = getInput().get(2);\n+ Transform transform1;\nif( et==ExecType.SPARK ) {\nboolean sortRewrite = !FORCE_DIST_SORT_INDEXES\n&& isSortSPRewriteApplicable() && by.getDataType().isScalar();\n- Lop transform1 = constructCPOrSparkSortLop(input, by, desc, ixret, et, sortRewrite);\n- setOutputDimensions(transform1);\n- setLineNumbers(transform1);\n- setLops(transform1);\n+ int k = 1;\n+ // number of threads set to 1 for spark.\n+ transform1 = new Transform( linputs, HopsTransf2Lops.get(ReOrgOp.SORT), getDataType(), getValueType(), et, sortRewrite, k);\n}\nelse //CP\n{\n- Lop transform1 = constructCPOrSparkSortLop(input, by, desc, ixret, et, false);\n+ int k = OptimizerUtils.getConstrainedNumThreads(_maxNumThreads);\n+ transform1 = new Transform( linputs, HopsTransf2Lops.get(ReOrgOp.SORT), getDataType(), getValueType(), et, false, k);\n+ }\n+\nsetOutputDimensions(transform1);\nsetLineNumbers(transform1);\nsetLops(transform1);\n- }\n+\nbreak;\n}\n@@ -222,15 +225,6 @@ public class ReorgOp extends MultiThreadedHop\nreturn getLops();\n}\n- private static Lop constructCPOrSparkSortLop( Hop input, Hop by, Hop desc, Hop ixret, ExecType et, boolean bSortIndInMem )\n- {\n- Hop[] hinputs = new Hop[]{input, by, desc, ixret};\n- Lop[] linputs = new Lop[4];\n- for( int i=0; i<4; i++ )\n- linputs[i] = hinputs[i].constructLops();\n- return new Transform( linputs, HopsTransf2Lops.get(ReOrgOp.SORT),\n- input.getDataType(), input.getValueType(), et, bSortIndInMem);\n- }\n@Override\nprotected double computeOutputMemEstimate( long dim1, long dim2, long nnz ) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/lops/Transform.java",
"new_path": "src/main/java/org/tugraz/sysds/lops/Transform.java",
"diff": "@@ -80,6 +80,13 @@ public class Transform extends Lop\ninit(inputs, op, dt, vt, et);\n}\n+ public Transform(Lop[] inputs, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et, boolean bSortIndInMem, int k) {\n+ super(Lop.Type.Transform, dt, vt);\n+ _bSortIndInMem = bSortIndInMem;\n+ _numThreads = k;\n+ init(inputs, op, dt, vt, et);\n+ }\n+\nprivate void init (Lop[] input, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et)\n{\noperation = op;\n@@ -178,6 +185,10 @@ public class Transform extends Lop\nsb.append( OPERAND_DELIMITOR );\nsb.append( _numThreads );\n}\n+ if( getExecType()==ExecType.CP && operation == OperationTypes.Sort ) {\n+ sb.append( OPERAND_DELIMITOR );\n+ sb.append( _numThreads );\n+ }\nif( getExecType()==ExecType.SPARK && operation == OperationTypes.Reshape ) {\nsb.append( OPERAND_DELIMITOR );\nsb.append( _outputEmptyBlock );\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ReorgCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ReorgCPInstruction.java",
"diff": "@@ -108,13 +108,14 @@ public class ReorgCPInstruction extends UnaryCPInstruction {\nreturn new ReorgCPInstruction(new ReorgOperator(DiagIndex.getDiagIndexFnObject()), in, out, opcode, str);\n}\nelse if ( opcode.equalsIgnoreCase(\"rsort\") ) {\n- InstructionUtils.checkNumFields(parts, 5);\n+ InstructionUtils.checkNumFields(str, 5,6);\nin.split(parts[1]);\nout.split(parts[5]);\nCPOperand col = new CPOperand(parts[2]);\nCPOperand desc = new CPOperand(parts[3]);\nCPOperand ixret = new CPOperand(parts[4]);\n- return new ReorgCPInstruction(new ReorgOperator(new SortIndex(1,false,false)),\n+ int k = Integer.parseInt(parts[6]);\n+ return new ReorgCPInstruction(new ReorgOperator(new SortIndex(1,false,false), k),\nin, out, col, desc, ixret, opcode, str);\n}\nelse {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/LibMatrixReorg.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/LibMatrixReorg.java",
"diff": "@@ -24,6 +24,7 @@ package org.tugraz.sysds.runtime.matrix.data;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject.UpdateType;\n+//import org.tugraz.sysds.runtime.controlprogram.parfor.stat.Timing;\nimport org.tugraz.sysds.runtime.data.DenseBlock;\nimport org.tugraz.sysds.runtime.data.DenseBlockFactory;\nimport org.tugraz.sysds.runtime.data.SparseBlock;\n@@ -72,6 +73,9 @@ public class LibMatrixReorg\n//minimum number of elements for multi-threaded execution\npublic static final long PAR_NUMCELL_THRESHOLD = 1024*1024; //1M\n+ // SORTING threshold\n+ public static final int PAR_NUMCELL_THRESHOLD_SORT = 1024;\n+\n//allow shallow dense/sparse copy for unchanged data (which is\n//safe due to copy-on-write and safe update-in-place handling)\npublic static final boolean SHALLOW_COPY_REORG = true;\n@@ -116,6 +120,9 @@ public class LibMatrixReorg\nreturn diag(in, out);\ncase SORT:\nSortIndex ix = (SortIndex) op.fn;\n+ if (op.getNumThreads() > 1)\n+ return sort(in, out, ix.getCols(), ix.getDecreasing(), ix.getIndexReturn(), op.getNumThreads());\n+ else\nreturn sort(in, out, ix.getCols(), ix.getDecreasing(), ix.getIndexReturn());\ndefault:\nthrow new DMLRuntimeException(\"Unsupported reorg operator: \"+op.fn);\n@@ -308,6 +315,21 @@ public class LibMatrixReorg\n}\npublic static MatrixBlock sort(MatrixBlock in, MatrixBlock out, int[] by, boolean desc, boolean ixret) {\n+ return sort(in,out,by,desc,ixret,1);\n+ }\n+\n+ /**\n+ * @param in Input matrix to sort\n+ * @param out Output matrix where the sorted input is inserted to\n+ * @param by The Ordering parameter\n+ * @param desc A boolean, specifying if it should be descending order.\n+ * @param ixret A boolean, specifying if the return should be the sorted indexes.\n+ * @param k Number of parallel threads\n+ * @return The sorted out matrix.\n+ */\n+ public static MatrixBlock sort(MatrixBlock in, MatrixBlock out, int[] by, boolean desc, boolean ixret, int k) {\n+ //Timing time = new Timing(true);\n+\n//meta data gathering and preparation\nboolean sparse = in.isInSparseFormat();\nint rlen = in.rlen;\n@@ -329,6 +351,9 @@ public class LibMatrixReorg\nif( !sparse && clen == 1 ) { //DENSE COLUMN VECTOR\n//in-place quicksort, unstable (no indexes needed)\nout.copy( in ); //dense (always single block)\n+ if (k > 1)\n+ Arrays.parallelSort(out.getDenseBlockValues());\n+ else\nArrays.sort(out.getDenseBlockValues());\nif( desc )\nsortReverseDense(out);\n@@ -340,6 +365,7 @@ public class LibMatrixReorg\nif( in.isEmptyBlock(false) ) { //EMPTY INPUT BLOCK\nout.allocateDenseBlock(false); //single block\ndouble[] c = out.getDenseBlockValues();\n+ // create a list containing the indexes of each element in in.\nfor( int i=0; i<rlen; i++ )\nc[i] = i+1; //seq(1,n)\nreturn out;\n@@ -356,8 +382,37 @@ public class LibMatrixReorg\nvalues[i] = in.quickGetValue(i, by[0]-1);\n}\n+ // step 4: split the data into number of blocks of PAR_NUMCELL_THRESHOLD_SORT (1024) elements.\n+ if (k == 1 || rlen < PAR_NUMCELL_THRESHOLD_SORT){ // There is no parallel\n//sort index vector on extracted data (unstable)\nSortUtils.sortByValue(0, rlen, values, vix);\n+ } else {\n+ try {\n+ ExecutorService pool = CommonThreadPool.get(k);\n+\n+ ArrayList<SortTask> tasks = new ArrayList<>();\n+\n+ // sort smaller blocks.\n+ int blklen = (int)(Math.ceil((double)rlen/k));\n+ for( int i=0; i*blklen<rlen; i++ ){\n+\n+ int start = i*blklen;\n+ int stop = Math.min(rlen , i*blklen + blklen);\n+\n+ tasks.add(new SortTask(start, stop, vix, values));\n+ }\n+ List<Future<Object>> taskret = pool.invokeAll(tasks);\n+ pool.shutdown();\n+ for( Future<Object> task : taskret )\n+ task.get();\n+\n+ mergeSortedBlocks(blklen, vix, values, k);\n+ }\n+ catch(Exception ex) {\n+ throw new DMLRuntimeException(ex);\n+ }\n+ }\n+\n//sort by secondary columns if required (in-place)\nif( by.length > 1 )\n@@ -2115,6 +2170,37 @@ public class LibMatrixReorg\n}\n}\n+ // Method to merge all blocks of a specified length.\n+ private static void mergeSortedBlocks(int blockLength, int[] valueIndexes, double[] values, int k){\n+ // Check if the blocklength is bigger than the size of the values\n+ // if it is smaller then merge the blocks, if not merging is done\n+\n+ int vlen = values.length;\n+ int mergeBlockSize = blockLength * 2;\n+ if (mergeBlockSize <= vlen + blockLength){\n+ try {\n+ ExecutorService pool = CommonThreadPool.get(k);\n+ ArrayList<MergeTask> tasks = new ArrayList<>();\n+ for( int i=0; i*mergeBlockSize<vlen; i++ ){\n+ int start = i*mergeBlockSize;\n+ if (start + blockLength < vlen){\n+ int stop = Math.min(vlen , (i+1)*mergeBlockSize);\n+ tasks.add(new MergeTask(start, stop, blockLength, valueIndexes, values));\n+ }\n+ }\n+ List<Future<Object>> taskret = pool.invokeAll(tasks);\n+ pool.shutdown();\n+ for( Future<Object> task : taskret )\n+ task.get();\n+ // recursive merge larger blocks.\n+ mergeSortedBlocks(mergeBlockSize, valueIndexes, values, k);\n+ }\n+ catch(Exception ex) {\n+ throw new DMLRuntimeException(ex);\n+ }\n+ }\n+ }\n+\nprivate static void sortBySecondary(int rl, int ru, double[] values, int[] vix, MatrixBlock in, int[] by, int off) {\n//find runs of equal values in current offset and index range\n//replace value by next column, sort, and recurse until single value\n@@ -2341,4 +2427,88 @@ public class LibMatrixReorg\nreturn rexpandColumns(_in, _out, _max, _cast, _ignore, _rl, _ru);\n}\n}\n+\n+ private static class SortTask implements Callable<Object>\n+ {\n+ private final int _start;\n+ private final int _end;\n+ private final int[] _indexes;\n+ private final double[] _values;\n+\n+\n+ protected SortTask(int start, int end, int[] indexes, double[] values){\n+ _start = start;\n+ _end = end;\n+ _indexes = indexes;\n+ _values = values;\n+\n+ }\n+\n+ @Override\n+ public Long call(){\n+ SortUtils.sortByValue(_start, _end, _values, _indexes);\n+ return 1l;\n+ }\n+\n+ }\n+\n+ private static class MergeTask implements Callable<Object>\n+ {\n+ private final int _start;\n+ private final int _end;\n+ private final int _blockSize;\n+ private final int[] _indexes;\n+ private final double[] _values;\n+\n+ protected MergeTask(int start, int end, int blockSize, int[] indexes, double[] values){\n+ _start = start;\n+ _end = end;\n+ _blockSize = blockSize;\n+ _indexes = indexes;\n+ _values = values;\n+ }\n+\n+ @Override\n+ public Long call(){\n+ // Find the middle index of the two merge blocks\n+ int middle = _start + _blockSize;\n+ // Early return if edge case\n+ if (middle == _end) return 1l;\n+\n+ // Pointer left side merge.\n+ int pointlIndex = middle -1;\n+ // Pointer to merge index.\n+ int positionToAssign = _end - 1;\n+\n+ // Make copy of entire right side so that we use left side directly as output.\n+ // Results in worst case (and most cases) allocation of extra array of half input size.\n+ int[] rhsCopy = new int[_end-middle];\n+ double[] rhsCopyV = new double[_end-middle];\n+ for(int i = middle ; i < _end ; i++){\n+ rhsCopy[i-middle] = _indexes[i];\n+ rhsCopyV[i-middle] = _values[i];\n+ }\n+ int pointrIndex = _end - middle - 1;\n+\n+ //int tmpI;\n+ //double tmpD;\n+ while (positionToAssign >= _start && pointrIndex >= 0) {\n+ if ( pointrIndex < 0 ||\n+ ( pointlIndex >= _start && _values[pointlIndex] > rhsCopyV[pointrIndex])\n+ ){\n+ _values[positionToAssign] = _values[pointlIndex];\n+ _indexes[positionToAssign] = _indexes[pointlIndex];\n+ pointlIndex--;\n+ positionToAssign--;\n+ } else {\n+ _values[positionToAssign] = rhsCopyV[pointrIndex];\n+ _indexes[positionToAssign] = rhsCopy[pointrIndex];\n+ positionToAssign--;\n+ pointrIndex--;\n+ }\n+ }\n+\n+ return 1l;\n+ }\n+ }\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-191] Parallel implementation of sort() (invoked by DML function order() )
Closes #65 |
49,720 | 07.12.2019 17:38:36 | -3,600 | ec557c14edd1e9f1a2e997f28e87b33db438a6f7 | Cleanup detectSchema builtin function
CleanUp_DetectSchema
1. Test file moved to Frame Package
2. String handling changes with ValueType
3. Double overflow handled
4. Sample storage removed
5. DML test file moved to functions/frame
Closes | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/FrameBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/FrameBlock.java",
"diff": "@@ -35,7 +35,6 @@ import java.io.*;\nimport java.lang.ref.SoftReference;\nimport java.util.*;\nimport java.util.concurrent.ThreadLocalRandom;\n-import java.util.stream.Collectors;\n@SuppressWarnings({\"rawtypes\",\"unchecked\"}) //allow generic native arrays\npublic class FrameBlock implements Writable, CacheBlock, Externalizable\n@@ -1767,75 +1766,72 @@ public class FrameBlock implements Writable, CacheBlock, Externalizable\n}\n}\n- private static String isType(String val) {\n- //TODO use consistent names (why not return value types)\n+ private static ValueType isType(String val) {\nval = val.trim().toLowerCase().replaceAll(\"\\\"\", \"\");\nif (val.matches(\"(true|false|t|f|0|1)\"))\n- return \"Boolean\";\n+ return ValueType.BOOLEAN;\nelse if (val.matches(\"[-+]?\\\\d+\"))\n- return \"Long\";\n+ return ValueType.INT64;\nelse if (val.matches(\"[-+]?[0-9]+\\\\.?[0-9]*([e]?[-+]?[0-9]+)\") || val.equals(\"infinity\") || val.equals(\"-infinity\") || val.equals(\"nan\"))\n- return \"Double\";\n- else if (val.length() == 1)\n- return \"Character\";\n- else return \"String\";\n+ return ValueType.FP64;\n+ else return ValueType.STRING;\n}\npublic FrameBlock detectSchemaFromRow(double sampleFraction) {\nint rows = this.getNumRows();\nint cols = this.getNumColumns();\n+ String[] schemaInfo = new String[cols];\nint sample = (int) (sampleFraction * rows);\nif (sample <= 0)\nsample = rows;\n- String[] schemaInfo = new String[cols];\n- HashMap<String, String> cellType = new HashMap<>();\n- FrameBlock fb = null;\n-\nfor (int i = 0; i < cols; i++) {\n- //TODO avoid keeping all the values sampled\n+ ValueType state = ValueType.UNKNOWN;\nArray obj = this.getColumn(i);\n- for (int j = 0; j < sample; j++) {\n+ for (int j = 0; j < sample; j++)\n+ {\n+ String dataValue = null;\n+ //read a not null sample value\n+ while (dataValue == null) {\nint randomIndex = ThreadLocalRandom.current().nextInt(0, rows - 1);\n- cellType.put(obj.get(randomIndex).toString().replace(\"\\\"\", \"\").toLowerCase(), isType(obj.get(randomIndex).toString()));\n+ dataValue = obj.get(randomIndex).toString().trim().replace(\"\\\"\", \"\").toLowerCase();\n}\n- //TODO fix special value handling, etc\n- //TODO fix string handling - use value type\n- if (cellType.containsValue(\"String\"))\n- schemaInfo[i] = \"STRING\";\n- else if (cellType.containsValue(\"Double\")) {\n- if (cellType.containsKey(\"infinity\") || cellType.containsKey(\"-infinity\") || cellType.containsKey(\"nan\"))\n- schemaInfo[i] = \"FP64\";\n+ if (isType(dataValue) == ValueType.STRING) {\n+ state = ValueType.STRING;\n+ break;\n+ }\n+ else if (isType(dataValue) == ValueType.FP64) {\n+ if (dataValue.equals(\"infinity\") || dataValue.equals(\"-infinity\") || dataValue.equals(\"nan\")) {\n+ state = ValueType.FP64;\n+ }\nelse {\n- //TODO fix handling of floats -> double would overflow here\n- Set<Float> cellValues = cellType.keySet().stream().map(s -> Float.parseFloat(s)).collect(Collectors.toSet());\n- float maxValue = Collections.max(cellValues);\n- if (maxValue >= (1.40129846432481707 * Math.exp(-45)) && maxValue <= (3.40282346638528860 * Math.exp(38))) {\n- schemaInfo[i] = \"FP32\";\n+ double maxValue = Double.parseDouble(dataValue);\n+ if ((maxValue >= (-Float.MAX_VALUE)) && (maxValue <= Float.MAX_VALUE))\n+ state = (state == ValueType.FP64 ? state : ValueType.FP32);\n+ else\n+ state = ValueType.FP64;\n+ }\n}\n+ else if (isType(dataValue) == ValueType.INT64) {\n+ long maxValue = Long.parseLong(dataValue);\n+ if ((maxValue >= Integer.MIN_VALUE) && (maxValue <= Integer.MAX_VALUE))\n+ state = ((state == ValueType.FP64 || state == ValueType.FP32 || state == ValueType.INT64) ? state : ValueType.INT32);\nelse\n- schemaInfo[i] = \"FP64\";\n+ state = ((state == ValueType.FP64 || state == ValueType.FP32) ? state : ValueType.INT64);\n}\n- } else if (cellType.containsValue(\"Long\")) {\n- Set<Long> cellValues = cellType.keySet().stream().map(s -> Long.parseLong(s)).collect(Collectors.toSet());\n- long maxValue = Collections.max(cellValues);\n- if (maxValue >= Math.pow(-2, 31) && maxValue <= (Math.pow(2, 31) - 1)) {\n- schemaInfo[i] = \"INT32\";\n- } else\n- schemaInfo[i] = \"INT64\";\n+ else if (isType(dataValue) == ValueType.BOOLEAN)\n+ state = ((new ArrayList<>(Arrays.asList(ValueType.FP64, ValueType.FP32, ValueType.INT64, ValueType.INT32)).contains(state)) ? state : ValueType.BOOLEAN);\n+ else if (isType(dataValue) == ValueType.STRING)\n+ state = ((new ArrayList<>(Arrays.asList(ValueType.FP64, ValueType.FP32, ValueType.INT64, ValueType.INT32, ValueType.BOOLEAN)).contains(state)) ? state : ValueType.STRING);\n}\n- else if (cellType.containsValue(\"Boolean\")) schemaInfo[i] = \"BOOLEAN\";\n- else if (cellType.containsValue(\"Character\")) schemaInfo[i] = \"CHARACTER\";\n- cellType.clear();\n+ schemaInfo[i] = state.name();\n}\n- ValueType[] outputSchema = UtilFunctions.nCopies(this.getNumColumns(), ValueType.STRING);\n- String[] dataOut = new String[cols];\n- Arrays.setAll(dataOut, value -> schemaInfo[value]);\n- fb = new FrameBlock(outputSchema);\n- fb.appendRow(dataOut);\n+ //create output block one row representing the schema as strings\n+ FrameBlock fb = new FrameBlock(UtilFunctions.nCopies(cols, ValueType.STRING));\n+ fb.appendRow(schemaInfo);\nreturn fb;\n}\n@@ -1854,9 +1850,9 @@ public class FrameBlock implements Writable, CacheBlock, Externalizable\nrowTemp1[i] = \"STRING\";\nelse if (rowTemp1[i].equals(\"FP64\") || rowTemp2[i].equals(\"FP64\"))\nrowTemp1[i] = \"FP64\";\n- else if (rowTemp1[i].equals(\"FP32\") && new ArrayList<> (Arrays.asList(\"INT64\", \"INT32\", \"CHARACTER\")).contains(rowTemp2[i].toString()) )\n+ else if (rowTemp1[i].equals(\"FP32\") && new ArrayList<>(Arrays.asList(\"INT64\", \"INT32\", \"CHARACTER\")).contains(rowTemp2[i]) )\nrowTemp1[i] = \"FP32\";\n- else if (rowTemp1[i].equals(\"INT64\") && new ArrayList<> (Arrays.asList(\"INT32\", \"CHARACTER\")).contains(rowTemp2[i].toString()))\n+ else if (rowTemp1[i].equals(\"INT64\") && new ArrayList<>(Arrays.asList(\"INT32\", \"CHARACTER\")).contains(rowTemp2[i]))\nrowTemp1[i] = \"INT64\";\nelse if (rowTemp1[i].equals(\"INT32\") || rowTemp2[i].equals(\"CHARACTER\"))\nrowTemp1[i] = \"INT32\";\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/unary/frame/DetectSchemaTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/frame/DetectSchemaTest.java",
"diff": "* limitations under the License.\n*/\n-package org.tugraz.sysds.test.functions.unary.frame;\n+package org.tugraz.sysds.test.functions.frame;\nimport org.junit.AfterClass;\nimport org.junit.Assert;\n@@ -33,18 +33,15 @@ import org.tugraz.sysds.runtime.util.UtilFunctions;\nimport org.tugraz.sysds.test.AutomatedTestBase;\nimport org.tugraz.sysds.test.TestConfiguration;\nimport org.tugraz.sysds.test.TestUtils;\n-\nimport java.security.SecureRandom;\n-//TODO fix the tests\n-//TODO move to package frame\npublic class DetectSchemaTest extends AutomatedTestBase {\nprivate final static String TEST_NAME = \"DetectSchema\";\n- private final static String TEST_DIR = \"functions/unary/frame/\";\n+ private final static String TEST_DIR = \"functions/frame/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + DetectSchemaTest.class.getSimpleName() + \"/\";\n- private final static int rows = 120;\n- private final static Types.ValueType[] schemaStrings = {Types.ValueType.INT32, Types.ValueType.BOOLEAN, Types.ValueType.FP32, Types.ValueType.STRING};\n+ private final static int rows = 10000;\n+ private final static Types.ValueType[] schemaStrings = {Types.ValueType.INT32, Types.ValueType.BOOLEAN, Types.ValueType.FP32, Types.ValueType.STRING, Types.ValueType.STRING, Types.ValueType.FP32};\nprivate final static Types.ValueType[] schemaDoubles = new Types.ValueType[]{Types.ValueType.FP64, Types.ValueType.FP64};\nprivate final static Types.ValueType[] schemaMixed = new Types.ValueType[]{Types.ValueType.INT64, Types.ValueType.FP64, Types.ValueType.INT64, Types.ValueType.BOOLEAN};\n@@ -112,13 +109,15 @@ public class DetectSchemaTest extends AutomatedTestBase {\nFrameWriter writer = FrameWriterFactory.createFrameWriter(OutputInfo.CSVOutputInfo);\nif (!isStringTest) {\n- double[][] A = getRandomMatrix(rows, schema.length, -10, 10, 0.9, 2373);\n+ double[][] A = getRandomMatrix(rows, schema.length, -Double.MIN_VALUE, Double.MAX_VALUE, 0.7, 2373);\ninitFrameDataDouble(frame1, A, schema);\nwriter.writeFrameToHDFS(frame1, input(\"A\"), rows, schema.length);\n- } else {\n- double[][] A = getRandomMatrix(rows, schema.length - 1, -10, 10, 0.9, 2373);\n+ }\n+ else {\n+ double[][] A = getRandomMatrix(rows, 3, -Float.MAX_VALUE, Float.MAX_VALUE, 0.7, 2373);\ninitFrameDataString(frame1, A, schema);\n- writer.writeFrameToHDFS(frame1.slice(0, 119, 0, 3, new FrameBlock()), input(\"A\"), rows, schema.length);\n+ writer.writeFrameToHDFS(frame1.slice(0, rows-1, 0, schema.length-1, new FrameBlock()), input(\"A\"), rows, schema.length);\n+ schema[schema.length-2] = Types.ValueType.FP64;\n}\nrunTest(true, false, null, -1);\n@@ -143,7 +142,7 @@ public class DetectSchemaTest extends AutomatedTestBase {\n}\nprivate static void initFrameDataString(FrameBlock frame1, double[][] data, Types.ValueType[] lschema) {\n- for (int j = 0; j < lschema.length - 1; j++) {\n+ for (int j = 0; j < 3; j++) {\nTypes.ValueType vt = lschema[j];\nswitch (vt) {\ncase STRING:\n@@ -188,6 +187,8 @@ public class DetectSchemaTest extends AutomatedTestBase {\n}\nString[] randomData = generateRandomString(8, rows);\nframe1.appendColumn(randomData);\n+ frame1.appendColumn(doubleSpecialData(rows));\n+ frame1.appendColumn(floatLimitData(rows));\n}\nprivate static void initFrameDataDouble(FrameBlock frame, double[][] data, Types.ValueType[] lschema) {\n@@ -201,7 +202,7 @@ public class DetectSchemaTest extends AutomatedTestBase {\n}\n}\n- public static String[] generateRandomString(int stringLength, int rows) {\n+ private static String[] generateRandomString(int stringLength, int rows) {\nString CHAR_LOWER = \"abcdefghijklmnopqrstuvwxyz\";\nString CHAR_UPPER = CHAR_LOWER.toUpperCase();\nString NUMBER = \"0123456789\";\n@@ -221,4 +222,22 @@ public class DetectSchemaTest extends AutomatedTestBase {\n}\nreturn A;\n}\n+\n+ private static String[] doubleSpecialData(int rows) {\n+ String[] dataArray = new String[]{\"Infinity\", \"3.4028234e+38\", \"Nan\" , \"-3.4028236e+38\" };\n+ String[] A = new String[rows];\n+ SecureRandom random = new SecureRandom();\n+ for (int j = 0; j < rows; j++)\n+ A[j] = dataArray[random.nextInt(4)];\n+ return A;\n+ }\n+\n+ private static double[] floatLimitData(int rows) {\n+ double[] dataArray = new double[]{Float.MAX_VALUE, 3.4028233E38, 3.4028234e38 , 3.4028228e38, 2.4028228e38, -3.4028234e38, -3.40282310e38};\n+ double[] A = new double[rows];\n+ SecureRandom random = new SecureRandom();\n+ for (int j = 0; j < rows; j++)\n+ A[j] = dataArray[random.nextInt(7)];\n+ return A;\n+ }\n}\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/scripts/functions/unary/frame/DetectSchema.dml",
"new_path": "src/test/scripts/functions/frame/DetectSchema.dml",
"diff": "#\n#-------------------------------------------------------------\n-\nX = read($1, rows=$2, cols=$3, data_type=\"frame\", format=\"csv\", header=FALSE);\nR = detectSchema(X);\nprint(toString(R))\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-183] Cleanup detectSchema builtin function
CleanUp_DetectSchema
1. Test file moved to Frame Package
2. String handling changes with ValueType
3. Double overflow handled
4. Sample storage removed
5. DML test file moved to functions/frame
Closes #64. |
49,720 | 07.12.2019 18:55:48 | -3,600 | 7a11d1b6648de4f24a2b3c8499b99ea5c86fd185 | Multiple imputation using chained equation (MICE)
1. Main DML script (mice_linearReg.dml)
2. Java test file (BuiltinMiceLinearRegTest.java)
3. DML test script (mice_linearRegression.dml)
Closes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/builtin/mice_lm.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+# Assumptions\n+# 1. The data is continous/numerical\n+# 2. The missing values are denoted by zeros\n+\n+# Builtin function Implements binary-class SVM with squared slack variables\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Double --- matrix X of feature vectors\n+# iter Integer 3 Number of iteration for multiple imputations\n+# complete Integer 3 A complete dataset generated though a specific iteration\n+# ---------------------------------------------------------------------------------------------\n+\n+\n+#Output(s)\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# dataset Double --- imputed dataset\n+# singleSet Double --- A complete dataset generated though a specific iteration\n+\n+\n+\n+m_mice_lm = function(Matrix[Double] X, Integer iter = 3, Integer complete = 3)\n+ return(Matrix[Double] dataset, Matrix[Double] singleSet)\n+{\n+ n = nrow(X)\n+ row = n*complete;\n+ col = ncol(X);\n+ Result = matrix(0, rows = 1, cols = col)\n+ Mask_Result = matrix(0, rows = 1, cols = col)\n+\n+ # storing the mask/address of missing values\n+ Mask = (X == 0);\n+ # filling the missing data with their means\n+ X2 = X+(Mask*colMeans(X))\n+\n+ # slicing non-missing dataset for training columnwise linear regression\n+ inverseMask = 1 - Mask;\n+\n+ for(k in 1:iter)\n+ {\n+ Mask_Filled = Mask;\n+\n+ parfor(i in 1:col)\n+ {\n+ # construct column selector\n+ sel = cbind(matrix(1,1,i-1), as.matrix(0), matrix(1,1,col-i));\n+\n+ # prepare train data set X and Y\n+ slice1 = removeEmpty(target = X2, margin = \"rows\", select = inverseMask[,i])\n+ while(FALSE){}\n+ train_X = removeEmpty(target = slice1, margin = \"cols\", select = sel);\n+ train_Y = slice1[,i]\n+\n+ # prepare score data set X and Y for imputing Y\n+ slice2 = removeEmpty(target = X2, margin = \"rows\", select = Mask[,i])\n+ while(FALSE){}\n+ test_X = removeEmpty(target = slice2, margin = \"cols\", select = sel);\n+ test_Y = slice2[,i]\n+\n+ # learning a regression line\n+ beta = lm(X=train_X, y=train_Y, verbose=FALSE);\n+\n+ # predicting missing values\n+ pred = lmpredict(X=test_X, w=beta)\n+\n+ # imputing missing column values (assumes Mask_Filled being 0/1-matrix)\n+ R = removeEmpty(target=Mask_Filled[,i] * seq(1,n), margin=\"rows\");\n+ Mask_Filled[,i] = table(R, 1, pred, n, 1);\n+ }\n+\n+ # binding results of multiple imputations\n+ Result = rbind(Result, X + Mask_Filled)\n+ Mask_Result = rbind(Mask_Result, Mask_Filled)\n+ Mask_Filled = Mask;\n+ }\n+ # return imputed dataset\n+ Result = Result[2: n*iter+1, ]\n+ Mask_Result = Mask_Result[2: n*iter+1, ]\n+ index = (((complete*n)-n)+1)\n+\n+ # aggregating the results\n+ Agg_Matrix = Mask_Result[index:row, ]\n+ for(d in 1:(iter-1))\n+ Agg_Matrix = Agg_Matrix + Mask_Result[(((d-1)*n)+1):(n*d),]\n+ Agg_Matrix =(Agg_Matrix/iter)\n+\n+ # return imputed data\n+ dataset = X + Agg_Matrix\n+ singleSet = Result[index:row, ]\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"diff": "@@ -112,6 +112,7 @@ public enum Builtins {\nMAX_POOL_BACKWARD(\"max_pool_backward\", false),\nMEDIAN(\"median\", false),\nMOMENT(\"moment\", \"centralMoment\", false),\n+ MICE_LM(\"mice_lm\", true),\nNCOL(\"ncol\", false),\nNORMALIZE(\"normalize\", true),\nNROW(\"nrow\", false),\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinMiceLinearRegTest.java",
"diff": "+/*\n+ * Copyright 2019 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.builtin;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.lops.LopProperties;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+\n+public class BuiltinMiceLinearRegTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"mice_lm\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinMiceLinearRegTest.class.getSimpleName() + \"/\";\n+\n+ private final static int rows = 50;\n+ private final static int cols = 30;\n+ private final static int iter = 3;\n+ private final static int com = 2;\n+\n+ @Override\n+ public void setUp() {\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[]{\"B\"}));\n+ }\n+\n+ @Test\n+ public void testMatrixSparseCP() {\n+ runLmTest(0.7, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testMatrixDenseCP() {\n+ runLmTest(0.3, LopProperties.ExecType.CP);\n+ }\n+\n+// @Test\n+// public void testMatrixSparseSpark() {\n+// runLmTest(0.7, LopProperties.ExecType.SPARK);\n+// }\n+//\n+// @Test\n+// public void testMatrixDenseSpark() {\n+// runLmTest(0.3, LopProperties.ExecType.SPARK);\n+// }\n+\n+ private void runLmTest(double sparseVal, LopProperties.ExecType instType) {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+ try {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{\"-nvargs\", \"X=\" + input(\"A\"), \"iteration=\" + iter, \"com=\" + com, \"data=\" + output(\"B\")};\n+\n+ //generate actual dataset\n+ double[][] A = getRandomMatrix(rows, cols, 0, 1, sparseVal, 7);\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+\n+ runTest(true, false, null, -1);\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/builtin/mice_lm.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = read($X)\n+[dataset, singleSet]= mice_lm(X=X, iter=$iteration, complete=$com)\n+write(dataset, $data)\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-189] Multiple imputation using chained equation (MICE)
1. Main DML script (mice_linearReg.dml)
2. Java test file (BuiltinMiceLinearRegTest.java)
3. DML test script (mice_linearRegression.dml)
Closes #70. |
49,738 | 07.12.2019 20:42:00 | -3,600 | 2b0f5f763439902cc9b3581f521d23da459fc896 | [MINOR] Improved size inference for removeEmpty operations
RemoveEmpty rows/column operations allow to specify an optional select
vector where non-zeros determine the selected rows and columns. We now
exploit the number-of-non-zeros in these select vectors to exactly
determine the number of output rows/columns. | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -145,6 +145,7 @@ SYSTEMDS-190 New Builtin Functions III\nSYSTEMDS-200 Various Fixes\n* 201 Fix spark append instruction zero columns OK\n+ * 202 Fix rewrite split DAG multiple removeEmpty (pending op)\nOthers:\n* Break append instruction to cbind and rbind\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/ParameterizedBuiltinOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/ParameterizedBuiltinOp.java",
"diff": "@@ -758,12 +758,19 @@ public class ParameterizedBuiltinOp extends MultiThreadedHop\n//one output dimension dim1 or dim2 is completely data dependent\nHop target = getTargetHop();\nHop margin = getParameterHop(\"margin\");\n+ Hop select = getParameterHop(\"select\");\nif( margin instanceof LiteralOp ) {\nLiteralOp lmargin = (LiteralOp)margin;\n- if( \"rows\".equals(lmargin.getStringValue()) )\n+ if( \"rows\".equals(lmargin.getStringValue()) ) {\nsetDim2( target.getDim2() );\n- else if( \"cols\".equals(lmargin.getStringValue()) )\n+ if( select != null )\n+ setDim1(select.getNnz());\n+ }\n+ else if( \"cols\".equals(lmargin.getStringValue()) ) {\nsetDim1( target.getDim1() );\n+ if( select != null )\n+ setDim2(select.getNnz());\n+ }\n}\nsetNnz( target.getNnz() );\nbreak;\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Improved size inference for removeEmpty operations
RemoveEmpty rows/column operations allow to specify an optional select
vector where non-zeros determine the selected rows and columns. We now
exploit the number-of-non-zeros in these select vectors to exactly
determine the number of output rows/columns. |
49,689 | 07.12.2019 21:40:22 | -3,600 | c08893059474b60cd9c411f5bdd076f076da078f | Append operations (rbind/cbind) over lists of matrices
Initial version of rbind/cbind of List of matrices
Single list of only matrices
Only local execution
Closes | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/BuiltinFunctionExpression.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/BuiltinFunctionExpression.java",
"diff": "@@ -750,6 +750,10 @@ public class BuiltinFunctionExpression extends DataIdentifier\ncheckValueTypeParam(getFirstExpr(), ValueType.STRING);\ncheckValueTypeParam(getSecondExpr(), ValueType.STRING);\n}\n+ // append (rbind/cbind) all the elements of a list\n+ else if( getAllExpr().length == 1 ) {\n+ checkDataTypeParam(getFirstExpr(), DataType.LIST);\n+ }\n//matrix append (rbind/cbind)\nelse {\nif( getAllExpr().length < 2 )\n@@ -760,6 +764,10 @@ public class BuiltinFunctionExpression extends DataIdentifier\noutput.setDataType(id.getDataType());\noutput.setValueType(id.getValueType());\n+ if (id.getDataType() == DataType.LIST) {\n+ output.setDataType(DataType.MATRIX);\n+ output.setValueType(ValueType.FP64);\n+ }\n// set output dimensions and validate consistency\nlong m1rlen = getFirstExpr().getOutput().getDim1();\n@@ -787,6 +795,12 @@ public class BuiltinFunctionExpression extends DataIdentifier\nappendDim2 = (m2clen>=0) ? m2clen : appendDim2;\n}\n}\n+ //TODO: calculate output dimensions of List\n+ if( output.getDataType() == DataType.LIST ) {\n+ appendDim1 = -1;\n+ appendDim2 = -1;\n+ }\n+\noutput.setDimensions(appendDim1, appendDim2);\noutput.setBlocksize (id.getBlocksize());\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/DMLTranslator.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/DMLTranslator.java",
"diff": "@@ -2346,11 +2346,11 @@ public class DMLTranslator\ncase CBIND:\ncase RBIND:\n- OpOp2 appendOp1 = (source.getOpCode()==Builtins.CBIND) ? OpOp2.CBIND : OpOp2.RBIND;\n- OpOpN appendOp2 = (source.getOpCode()==Builtins.CBIND) ? OpOpN.CBIND : OpOpN.RBIND;\n+ OpOp2 appendOp2 = (source.getOpCode()==Builtins.CBIND) ? OpOp2.CBIND : OpOp2.RBIND;\n+ OpOpN appendOpN = (source.getOpCode()==Builtins.CBIND) ? OpOpN.CBIND : OpOpN.RBIND;\ncurrBuiltinOp = (source.getAllExpr().length == 2) ?\n- new BinaryOp(target.getName(), target.getDataType(), target.getValueType(), appendOp1, expr, expr2) :\n- new NaryOp(target.getName(), target.getDataType(), target.getValueType(), appendOp2,\n+ new BinaryOp(target.getName(), target.getDataType(), target.getValueType(), appendOp2, expr, expr2) :\n+ new NaryOp(target.getName(), target.getDataType(), target.getValueType(), appendOpN,\nprocessAllExpressions(source.getAllExpr(), hops));\nbreak;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/ExecutionContext.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/ExecutionContext.java",
"diff": "@@ -482,6 +482,19 @@ public class ExecutionContext {\nreturn (ListObject) dat;\n}\n+ private List<MatrixObject> getMatricesFromList(ListObject lo) {\n+ List<MatrixObject> ret = new ArrayList<>();\n+ for (Data e : lo.getData()) {\n+ if (e instanceof MatrixObject)\n+ ret.add((MatrixObject)e);\n+ else if (e instanceof ListObject)\n+ ret.addAll(getMatricesFromList((ListObject)e));\n+ else\n+ throw new DMLRuntimeException(\"List must contain only matrices or lists for rbind/cbind.\");\n+ }\n+ return ret;\n+ }\n+\npublic void releaseMatrixOutputForGPUInstruction(String varName) {\nMatrixObject mo = getMatrixObject(varName);\nif(mo.getGPUObject(getGPUContext(0)) == null || !mo.getGPUObject(getGPUContext(0)).isAllocated()) {\n@@ -526,8 +539,22 @@ public class ExecutionContext {\n}\npublic List<MatrixBlock> getMatrixInputs(CPOperand[] inputs) {\n- return Arrays.stream(inputs).filter(in -> in.isMatrix())\n+ return getMatrixInputs(inputs, false);\n+ }\n+\n+ public List<MatrixBlock> getMatrixInputs(CPOperand[] inputs, boolean includeList) {\n+ List<MatrixBlock> ret = Arrays.stream(inputs).filter(in -> in.isMatrix())\n.map(in -> getMatrixInput(in.getName())).collect(Collectors.toList());\n+\n+ if (includeList) {\n+ List<ListObject> lolist = Arrays.stream(inputs).filter(in -> in.isList())\n+ .map(in -> getListObject(in.getName())).collect(Collectors.toList());\n+ for (ListObject lo : lolist)\n+ ret.addAll( getMatricesFromList(lo).stream()\n+ .map(mo -> mo.acquireRead()).collect(Collectors.toList()));\n+ }\n+\n+ return ret;\n}\npublic List<ScalarObject> getScalarInputs(CPOperand[] inputs) {\n@@ -536,8 +563,19 @@ public class ExecutionContext {\n}\npublic void releaseMatrixInputs(CPOperand[] inputs) {\n+ releaseMatrixInputs(inputs, false);\n+ }\n+\n+ public void releaseMatrixInputs(CPOperand[] inputs, boolean includeList) {\nArrays.stream(inputs).filter(in -> in.isMatrix())\n.forEach(in -> releaseMatrixInput(in.getName()));\n+\n+ if (includeList) {\n+ List<ListObject> lolist = Arrays.stream(inputs).filter(in -> in.isList())\n+ .map(in -> getListObject(in.getName())).collect(Collectors.toList());\n+ for (ListObject lo : lolist)\n+ getMatricesFromList(lo).stream().forEach(mo -> mo.release());\n+ }\n}\n/**\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/CPOperand.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/CPOperand.java",
"diff": "@@ -92,6 +92,10 @@ public class CPOperand\nreturn _dataType.isTensor();\n}\n+ public boolean isList() {\n+ return _dataType.isList();\n+ }\n+\npublic boolean isScalar() {\nreturn _dataType.isScalar();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/MatrixBuiltinNaryCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/MatrixBuiltinNaryCPInstruction.java",
"diff": "@@ -38,7 +38,7 @@ public class MatrixBuiltinNaryCPInstruction extends BuiltinNaryCPInstruction imp\n@Override\npublic void processInstruction(ExecutionContext ec) {\n//separate scalars and matrices and pin all input matrices\n- List<MatrixBlock> matrices = ec.getMatrixInputs(inputs);\n+ List<MatrixBlock> matrices = ec.getMatrixInputs(inputs, true);\nList<ScalarObject> scalars = ec.getScalarInputs(inputs);\nMatrixBlock outBlock = null;\n@@ -57,7 +57,7 @@ public class MatrixBuiltinNaryCPInstruction extends BuiltinNaryCPInstruction imp\n}\n//release inputs and set output matrix or scalar\n- ec.releaseMatrixInputs(inputs);\n+ ec.releaseMatrixInputs(inputs, true);\nif( output.getDataType().isMatrix()) {\nec.setMatrixOutput(output.getName(), outBlock);\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/nary/NaryListCBindTest.java",
"diff": "+/*\n+ * Copyright 2019 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.nary;\n+\n+import java.util.HashMap;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.api.DMLScript;\n+import org.tugraz.sysds.common.Types.ExecMode;\n+import org.tugraz.sysds.lops.LopProperties.ExecType;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+public class NaryListCBindTest extends AutomatedTestBase\n+{\n+ private final static String TEST_NAME = \"NaryListCbind\";\n+ private final static String TEST_DIR = \"functions/nary/\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + NaryListCBindTest.class.getSimpleName() + \"/\";\n+\n+ private final static double epsilon=0.0000000001;\n+\n+ private final static int rows = 1101;\n+ private final static int cols1 = 101;\n+ private final static int cols2 = 79;\n+ private final static int cols3 = 123;\n+\n+ private final static double sparsity1 = 0.7;\n+ private final static double sparsity2 = 0.07;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {\"R\"}));\n+ }\n+\n+ @Test\n+ public void testNaryCbindDenseDenseDenseCP() {\n+ runCbindTest(false, false, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryCbindDenseDenseSparseCP() {\n+ runCbindTest(false, false, true, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryCbindDenseSparseDenseCP() {\n+ runCbindTest(false, true, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryCbindDenseSparseSparseCP() {\n+ runCbindTest(false, true, true, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryCbindSparseDenseDenseCP() {\n+ runCbindTest(true, false, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryCbindSparseDenseSparseCP() {\n+ runCbindTest(true, false, true, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryCbindSparseSparseDenseCP() {\n+ runCbindTest(true, true, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryCbindSparseSparseSparseCP() {\n+ runCbindTest(true, true, true, ExecType.CP);\n+ }\n+\n+ public void runCbindTest(boolean sparse1, boolean sparse2, boolean sparse3, ExecType et)\n+ {\n+ ExecMode platformOld = rtplatform;\n+ switch( et ) {\n+ case SPARK: rtplatform = ExecMode.SPARK; break;\n+ default: rtplatform = ExecMode.HYBRID; break;\n+ }\n+\n+ boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\n+ if( rtplatform == ExecMode.SPARK || rtplatform == ExecMode.HYBRID )\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+\n+ try\n+ {\n+ TestConfiguration config = getAndLoadTestConfiguration(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ String RI_HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = RI_HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{\"-explain\", \"-stats\", \"-args\", input(\"A\"),\n+ input(\"B\"), input(\"C\"), output(\"R\") };\n+ fullRScriptName = RI_HOME + TEST_NAME + \".R\";\n+ rCmd = \"Rscript\" + \" \" + fullRScriptName + \" \" +\n+ inputDir() + \" \"+ expectedDir();\n+\n+ //generate input data\n+ double sp1 = sparse1 ? sparsity2 : sparsity1;\n+ double sp2 = sparse2 ? sparsity2 : sparsity1;\n+ double sp3 = sparse3 ? sparsity2 : sparsity1;\n+ double[][] A = getRandomMatrix(rows, cols1, -1, 1, sp1, 711);\n+ double[][] B = getRandomMatrix(rows, cols2, -1, 1, sp2, 722);\n+ double[][] C = getRandomMatrix(rows, cols3, -1, 1, sp3, 733);\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+ writeInputMatrixWithMTD(\"B\", B, true);\n+ writeInputMatrixWithMTD(\"C\", C, true);\n+\n+ //run tests\n+ runTest(true, false, null, -1);\n+ runRScript(true);\n+\n+ //compare result data\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"R\");\n+ HashMap<CellIndex, Double> rfile = readRMatrixFromFS(\"R\");\n+ TestUtils.compareMatrices(dmlfile, rfile, epsilon, \"DML\", \"R\");\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/nary/NaryListRBindTest.java",
"diff": "+/*\n+ * Copyright 2019 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.nary;\n+\n+import java.util.HashMap;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.api.DMLScript;\n+import org.tugraz.sysds.common.Types.ExecMode;\n+import org.tugraz.sysds.lops.LopProperties.ExecType;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+public class NaryListRBindTest extends AutomatedTestBase\n+{\n+ private final static String TEST_NAME = \"NaryListRbind\";\n+ private final static String TEST_DIR = \"functions/nary/\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + NaryListRBindTest.class.getSimpleName() + \"/\";\n+\n+ private final static double epsilon=0.0000000001;\n+\n+ private final static int cols = 101;\n+ private final static int rows1 = 1101;\n+ private final static int rows2 = 1179;\n+ private final static int rows3 = 1123;\n+\n+ private final static double sparsity1 = 0.7;\n+ private final static double sparsity2 = 0.07;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {\"R\"}));\n+ }\n+\n+ @Test\n+ public void testNaryRbindDenseDenseDenseCP() {\n+ runRbindTest(false, false, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryRbindDenseDenseSparseCP() {\n+ runRbindTest(false, false, true, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryRbindDenseSparseDenseCP() {\n+ runRbindTest(false, true, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryRbindDenseSparseSparseCP() {\n+ runRbindTest(false, true, true, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryRbindSparseDenseDenseCP() {\n+ runRbindTest(true, false, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryRbindSparseDenseSparseCP() {\n+ runRbindTest(true, false, true, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryRbindSparseSparseDenseCP() {\n+ runRbindTest(true, true, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testNaryRbindSparseSparseSparseCP() {\n+ runRbindTest(true, true, true, ExecType.CP);\n+ }\n+\n+ public void runRbindTest(boolean sparse1, boolean sparse2, boolean sparse3, ExecType et)\n+ {\n+ ExecMode platformOld = rtplatform;\n+ switch( et ) {\n+ case SPARK: rtplatform = ExecMode.SPARK; break;\n+ default: rtplatform = ExecMode.HYBRID; break;\n+ }\n+\n+ boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\n+ if( rtplatform == ExecMode.SPARK || rtplatform == ExecMode.HYBRID )\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+\n+ try\n+ {\n+ TestConfiguration config = getAndLoadTestConfiguration(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ String RI_HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = RI_HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{\"-explain\", \"-stats\", \"-args\", input(\"A\"),\n+ input(\"B\"), input(\"C\"), output(\"R\") };\n+ fullRScriptName = RI_HOME + TEST_NAME + \".R\";\n+ rCmd = \"Rscript\" + \" \" + fullRScriptName + \" \" +\n+ inputDir() + \" \"+ expectedDir();\n+\n+ //generate input data\n+ double sp1 = sparse1 ? sparsity2 : sparsity1;\n+ double sp2 = sparse2 ? sparsity2 : sparsity1;\n+ double sp3 = sparse3 ? sparsity2 : sparsity1;\n+ double[][] A = getRandomMatrix(rows1, cols, -1, 1, sp1, 711);\n+ double[][] B = getRandomMatrix(rows2, cols, -1, 1, sp2, 722);\n+ double[][] C = getRandomMatrix(rows3, cols, -1, 1, sp3, 733);\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+ writeInputMatrixWithMTD(\"B\", B, true);\n+ writeInputMatrixWithMTD(\"C\", C, true);\n+\n+ //run tests\n+ runTest(true, false, null, -1);\n+ runRScript(true);\n+\n+ //compare result data\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"R\");\n+ HashMap<CellIndex, Double> rfile = readRMatrixFromFS(\"R\");\n+ TestUtils.compareMatrices(dmlfile, rfile, epsilon, \"DML\", \"R\");\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\n+ }\n+ }\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/nary/NaryListCbind.R",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+args <- commandArgs(TRUE)\n+options(digits=22)\n+library(\"Matrix\")\n+\n+A = as.matrix(readMM(paste(args[1], \"A.mtx\", sep=\"\")))\n+B = as.matrix(readMM(paste(args[1], \"B.mtx\", sep=\"\")))\n+C = as.matrix(readMM(paste(args[1], \"C.mtx\", sep=\"\")))\n+\n+R = cbind(cbind(A, B), C);\n+\n+writeMM(as(R,\"CsparseMatrix\"), paste(args[2], \"R\", sep=\"\"))\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/nary/NaryListCbind.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+A = read($1);\n+B = read($2);\n+C = read($3);\n+List = list(A, B, C);\n+R = cbind(List);\n+write(R, $4)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/nary/NaryListRbind.R",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+args <- commandArgs(TRUE)\n+options(digits=22)\n+library(\"Matrix\")\n+\n+A = as.matrix(readMM(paste(args[1], \"A.mtx\", sep=\"\")))\n+B = as.matrix(readMM(paste(args[1], \"B.mtx\", sep=\"\")))\n+C = as.matrix(readMM(paste(args[1], \"C.mtx\", sep=\"\")))\n+\n+R = rbind(rbind(A, B), C);\n+\n+writeMM(as(R,\"CsparseMatrix\"), paste(args[2], \"R\", sep=\"\"))\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/nary/NaryListRbind.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+A = read($1);\n+B = read($2);\n+C = read($3);\n+List = list(A, B, C);\n+R = rbind(List);\n+write(R, $4)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-211] Append operations (rbind/cbind) over lists of matrices
Initial version of rbind/cbind of List of matrices
Single list of only matrices
Only local execution
Closes #63. |
49,738 | 07.12.2019 22:57:20 | -3,600 | 13472964c8f6ff2fc233ed1c9ca425d87acef9cf | Creation of empty lists for append in loops
This patch generalizes the constructions of lists (compiler/runtime) to
support zero inputs, which is useful for appending parts in a loop. | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -147,5 +147,11 @@ SYSTEMDS-200 Various Fixes\n* 201 Fix spark append instruction zero columns OK\n* 202 Fix rewrite split DAG multiple removeEmpty (pending op)\n+SYSTEMDS-210 Extended lists Operations\n+ * 211 Cbind and Rbind over lists of matrices OK\n+ * 212 Creation of empty lists OK\n+ * 213 Add entries to lists\n+ * 214 Removal of entries from lists\n+\nOthers:\n* Break append instruction to cbind and rbind\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/BuiltinFunctionExpression.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/BuiltinFunctionExpression.java",
"diff": "@@ -493,6 +493,11 @@ public class BuiltinFunctionExpression extends DataIdentifier\nreturn paramExpression;\n}\n+ private boolean isValidNoArgumentFunction() {\n+ return getOpCode() == Builtins.TIME\n+ || getOpCode() == Builtins.LIST;\n+ }\n+\n/**\n* Validate parse tree : Process BuiltinFunction Expression in an assignment\n* statement\n@@ -512,7 +517,7 @@ public class BuiltinFunctionExpression extends DataIdentifier\nDataIdentifier output = new DataIdentifier(outputName);\noutput.setParseInfo(this);\n- if (getFirstExpr() == null && getOpCode() != Builtins.TIME) { // time has no arguments\n+ if (getFirstExpr() == null && !isValidNoArgumentFunction()) { // time has no arguments\nraiseValidateError(\"Function \" + this + \" has no arguments.\", false);\n}\nIdentifier id = (_args.length != 0) ?\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ScalarBuiltinNaryCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ScalarBuiltinNaryCPInstruction.java",
"diff": "@@ -92,8 +92,8 @@ public class ScalarBuiltinNaryCPInstruction extends BuiltinNaryCPInstruction {\n}\nelse if( \"list\".equals(getOpcode()) ) {\n//obtain all input data objects, incl handling of literals\n- List<Data> data = Arrays.stream(inputs)\n- .map(in -> ec.getVariable(in)).collect(Collectors.toList());\n+ List<Data> data = (inputs== null) ? new ArrayList<>() :\n+ Arrays.stream(inputs).map(in -> ec.getVariable(in)).collect(Collectors.toList());\n//create list object over all inputs\nListObject list = new ListObject(data);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/TestUtils.java",
"new_path": "src/test/java/org/tugraz/sysds/test/TestUtils.java",
"diff": "@@ -911,19 +911,11 @@ public class TestUtils\n}\n- /**\n- *\n- * @param matrix\n- * @param rows\n- * @param cols\n- * @return\n- */\npublic static double[][] convertHashMapToDoubleArray(HashMap <CellIndex, Double> matrix, int rows, int cols)\n{\ndouble [][] ret_arr = new double[rows][cols];\n- for(CellIndex ci:matrix.keySet())\n- {\n+ for(CellIndex ci:matrix.keySet()) {\nint i = ci.row-1;\nint j = ci.column-1;\nret_arr[i][j] = matrix.get(ci);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/ListAppendRemove.java",
"diff": "+/*\n+ * Copyright 2019 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.misc;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.hops.OptimizerUtils;\n+import org.tugraz.sysds.lops.LopProperties.ExecType;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+import org.tugraz.sysds.utils.Statistics;\n+\n+public class ListAppendRemove extends AutomatedTestBase\n+{\n+ private static final String TEST_NAME1 = \"ListAppendRemove\";\n+\n+ private static final String TEST_DIR = \"functions/misc/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + ListAppendRemove.class.getSimpleName() + \"/\";\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { \"R\" }) );\n+ }\n+\n+ @Test\n+ public void testListAppendRemoveRewriteCP() {\n+ runListAppendRemove(TEST_NAME1, ExecType.CP, true, false);\n+ }\n+\n+ @Test\n+ public void testListAppendRemoveRewriteSP() {\n+ runListAppendRemove(TEST_NAME1, ExecType.SPARK, true, false);\n+ }\n+\n+ @Test\n+ public void testListAppendRemoveNoRewriteCP() {\n+ runListAppendRemove(TEST_NAME1, ExecType.CP, false, false);\n+ }\n+\n+ @Test\n+ public void testListAppendRemoveNoRewriteSP() {\n+ runListAppendRemove(TEST_NAME1, ExecType.SPARK, false, false);\n+ }\n+\n+ @Test\n+ public void testListAppendRemoveRewriteCondCP() {\n+ runListAppendRemove(TEST_NAME1, ExecType.CP, true, true);\n+ }\n+\n+ @Test\n+ public void testListAppendRemoveRewriteCondSP() {\n+ runListAppendRemove(TEST_NAME1, ExecType.SPARK, true, true);\n+ }\n+\n+ @Test\n+ public void testListAppendRemoveNoRewriteCondCP() {\n+ runListAppendRemove(TEST_NAME1, ExecType.CP, false, true);\n+ }\n+\n+ @Test\n+ public void testListAppendRemoveNoRewriteCondSP() {\n+ runListAppendRemove(TEST_NAME1, ExecType.SPARK, false, true);\n+ }\n+\n+\n+ private void runListAppendRemove(String testname, ExecType type, boolean rewrites, boolean conditional)\n+ {\n+ Types.ExecMode platformOld = setExecMode(type);\n+ boolean rewriteOld = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+\n+ try {\n+ TestConfiguration config = getTestConfiguration(testname);\n+ loadTestConfiguration(config);\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = true;\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + testname + \".dml\";\n+ programArgs = new String[]{ \"-stats\",\"-explain\",\"-args\",\n+ String.valueOf(conditional).toUpperCase(), output(\"R\") };\n+ fullRScriptName = HOME + testname + \".R\";\n+ rCmd = getRCmd(expectedDir());\n+\n+ //run test\n+ runTest(true, false, null, -1);\n+\n+ //compare matrices\n+ double[][] ret = TestUtils.convertHashMapToDoubleArray(\n+ readDMLMatrixFromHDFS(\"R\"), 4, 1);\n+ Assert.assertEquals(new Double(ret[0][0]), new Double(0)); //empty list\n+ //Assert.assertEquals(new Double(ret[1][0]), new Double(7)); //append list\n+ //Assert.assertEquals(new Double(ret[2][0]), new Double(3)); //remove list\n+\n+ //check for properly compiled CP operations for list\n+ //(but spark instructions for sum, indexing, write)\n+ int numExpected = (type == ExecType.CP) ? 0 :\n+ conditional ? 3 : 2;\n+ Assert.assertTrue(Statistics.getNoOfExecutedSPInst()==numExpected);\n+ Assert.assertTrue(Statistics.getNoOfExecutedSPInst()==numExpected);\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewriteOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/misc/ListAppendRemove.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+cond = $1\n+R = as.matrix(list(0,0,0,-1));\n+\n+# empty list construction\n+L = list();\n+if( cond & sum(R) > 0 )\n+ L = list(R, R);\n+R[1,] = length(L);\n+\n+\n+write(R, $2);\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-212] Creation of empty lists for append in loops
This patch generalizes the constructions of lists (compiler/runtime) to
support zero inputs, which is useful for appending parts in a loop. |
49,738 | 08.12.2019 00:02:06 | -3,600 | e201c9b042656ddb66aa741f6afbc0aeb412349d | Extended binary append operations for list append
This patch adds the functionality of appending arbitrary data objects to
lists, which is useful for constructing collections of matrices (e.g.,
CV). Furthermore, this also includes a cleanup of all CP append
instructions. | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -150,7 +150,7 @@ SYSTEMDS-200 Various Fixes\nSYSTEMDS-210 Extended lists Operations\n* 211 Cbind and Rbind over lists of matrices OK\n* 212 Creation of empty lists OK\n- * 213 Add entries to lists\n+ * 213 Add entries to lists OK\n* 214 Removal of entries from lists\nOthers:\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/BinaryOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/BinaryOp.java",
"diff": "@@ -339,10 +339,12 @@ public class BinaryOp extends MultiThreadedHop\n//sanity check for input data types\nif( !((dt1==DataType.MATRIX && dt2==DataType.MATRIX)\n||(dt1==DataType.FRAME && dt2==DataType.FRAME)\n+ ||(dt1==DataType.LIST)\n||(dt1==DataType.SCALAR && dt2==DataType.SCALAR\n&& vt1==ValueType.STRING && vt2==ValueType.STRING )) )\n{\n- throw new HopsException(\"Append can only apply to two matrices, two frames, or two scalar strings!\");\n+ throw new HopsException(\"Append can only apply to two matrices, \"\n+ + \"two frames, two scalar strings, or anything to a list!\");\n}\nLop append = null;\n@@ -365,6 +367,13 @@ public class BinaryOp extends MultiThreadedHop\nappend.getOutputParameters().setDimensions(rlen, clen, getBlocksize(), getNnz());\n}\n}\n+ else if( dt1==DataType.LIST ) {\n+ // list append is always in CP\n+ long len = getInput().get(0).getLength()+1;\n+ append = new Append(getInput().get(0).constructLops(), getInput().get(1).constructLops(),\n+ new LiteralOp(-1).constructLops(), getDataType(), getValueType(), cbind, et);\n+ append.getOutputParameters().setDimensions(1, len, getBlocksize(), len);\n+ }\nelse //SCALAR-STRING and SCALAR-STRING (always CP)\n{\nappend = new Append(getInput().get(0).constructLops(), getInput().get(1).constructLops(),\n@@ -745,9 +754,6 @@ public class BinaryOp extends MultiThreadedHop\n_etype = ExecType.SPARK;\n}\n- //mark for recompile (forever)\n- setRequiresRecompileIfNecessary();\n-\n//ensure cp exec type for single-node operations\nif ( op == OpOp2.SOLVE ) {\nif (isGPUEnabled())\n@@ -755,6 +761,12 @@ public class BinaryOp extends MultiThreadedHop\nelse\n_etype = ExecType.CP;\n}\n+ else if( op == OpOp2.CBIND && getDataType().isList() ) {\n+ _etype = ExecType.CP;\n+ }\n+\n+ //mark for recompile (forever)\n+ setRequiresRecompileIfNecessary();\nreturn _etype;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/BuiltinFunctionExpression.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/BuiltinFunctionExpression.java",
"diff": "@@ -759,17 +759,22 @@ public class BuiltinFunctionExpression extends DataIdentifier\nelse if( getAllExpr().length == 1 ) {\ncheckDataTypeParam(getFirstExpr(), DataType.LIST);\n}\n- //matrix append (rbind/cbind)\nelse {\nif( getAllExpr().length < 2 )\nraiseValidateError(\"Invalid number of arguments for \"+getOpCode(), conditional);\n+ //list append\n+ if(getFirstExpr().getOutput().getDataType().isList() )\n+ for(int i=1; i<getAllExpr().length; i++)\n+ checkDataTypeParam(getExpr(i), DataType.SCALAR, DataType.MATRIX, DataType.FRAME);\n+ //matrix append (rbind/cbind)\n+ else\nfor(int i=0; i<getAllExpr().length; i++)\ncheckMatrixFrameParam(getExpr(i));\n}\noutput.setDataType(id.getDataType());\noutput.setValueType(id.getValueType());\n- if (id.getDataType() == DataType.LIST) {\n+ if( id.getDataType() == DataType.LIST && getAllExpr().length == 1) {\noutput.setDataType(DataType.MATRIX);\noutput.setValueType(ValueType.FP64);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/ExecutionContext.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/ExecutionContext.java",
"diff": "@@ -472,6 +472,10 @@ public class ExecutionContext {\nsetVariable(varName, so);\n}\n+ public ListObject getListObject(CPOperand input) {\n+ return getListObject(input.getName());\n+ }\n+\npublic ListObject getListObject(String name) {\nData dat = getVariable(name);\n//error handling if non existing or no list\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/AppendCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/AppendCPInstruction.java",
"diff": "@@ -33,12 +33,13 @@ public abstract class AppendCPInstruction extends BinaryCPInstruction\nCBIND,\nRBIND,\nSTRING,\n+ LIST,\n}\n//type (matrix cbind / scalar string concatenation)\nprotected final AppendType _type;\n- protected AppendCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out,\n+ protected AppendCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out,\nAppendType type, String opcode, String istr) {\nsuper(CPType.Append, op, in1, in2, out, opcode, istr);\n_type = type;\n@@ -51,22 +52,24 @@ public abstract class AppendCPInstruction extends BinaryCPInstruction\nString opcode = parts[0];\nCPOperand in1 = new CPOperand(parts[1]);\nCPOperand in2 = new CPOperand(parts[2]);\n- CPOperand in3 = new CPOperand(parts[3]);\nCPOperand out = new CPOperand(parts[4]);\nboolean cbind = Boolean.parseBoolean(parts[5]);\nAppendType type = (in1.getDataType()!=DataType.MATRIX && in1.getDataType()!=DataType.FRAME) ?\n- AppendType.STRING : cbind ? AppendType.CBIND : AppendType.RBIND;\n+ in1.getDataType()==DataType.LIST ? AppendType.LIST : AppendType.STRING :\n+ cbind ? AppendType.CBIND : AppendType.RBIND;\nif(!opcode.equalsIgnoreCase(\"append\"))\nthrow new DMLRuntimeException(\"Unknown opcode while parsing a AppendCPInstruction: \" + str);\nOperator op = new ReorgOperator(OffsetColumnIndex.getOffsetColumnIndexFnObject(-1));\nif( type == AppendType.STRING )\n- return new ScalarAppendCPInstruction(op, in1, in2, in3, out, type, opcode, str);\n+ return new ScalarAppendCPInstruction(op, in1, in2, out, type, opcode, str);\n+ else if( type == AppendType.LIST )\n+ return new ListAppendRemoveCPInstruction(op, in1, in2, out, type, opcode, str);\nelse if( in1.getDataType()==DataType.MATRIX )\n- return new MatrixAppendCPInstruction(op, in1, in2, in3, out, type, opcode, str);\n+ return new MatrixAppendCPInstruction(op, in1, in2, out, type, opcode, str);\nelse //DataType.FRAME\n- return new FrameAppendCPInstruction(op, in1, in2, in3, out, type, opcode, str);\n+ return new FrameAppendCPInstruction(op, in1, in2, out, type, opcode, str);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/FrameAppendCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/FrameAppendCPInstruction.java",
"diff": "@@ -26,9 +26,9 @@ import org.tugraz.sysds.runtime.matrix.operators.Operator;\npublic final class FrameAppendCPInstruction extends AppendCPInstruction {\n- protected FrameAppendCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out,\n+ protected FrameAppendCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out,\nAppendType type, String opcode, String istr) {\n- super(op, in1, in2, in3, out, type, opcode, istr);\n+ super(op, in1, in2, out, type, opcode, istr);\n}\n@Override\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListAppendRemoveCPInstruction.java",
"diff": "+/*\n+ * Copyright 2019 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.runtime.instructions.cp;\n+\n+import org.tugraz.sysds.runtime.DMLRuntimeException;\n+import org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\n+import org.tugraz.sysds.runtime.matrix.operators.Operator;\n+\n+public final class ListAppendRemoveCPInstruction extends AppendCPInstruction {\n+\n+ protected ListAppendRemoveCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out,\n+ AppendType type, String opcode, String istr) {\n+ super(op, in1, in2, out, type, opcode, istr);\n+ }\n+\n+ @Override\n+ public void processInstruction(ExecutionContext ec) {\n+ //get input list and data\n+ ListObject lo = ec.getListObject(input1);\n+ Data dat2 = ec.getVariable(input2);\n+\n+ //list append instruction\n+ if( getOpcode().equals(\"append\") ) {\n+ //copy on write and append unnamed argument\n+ ListObject tmp = lo.copy().append(dat2);\n+ //set output variable\n+ ec.setVariable(output.getName(), tmp);\n+ }\n+ else {\n+ throw new DMLRuntimeException(\"Unsupported list operation: \"+getOpcode());\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListObject.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListObject.java",
"diff": "@@ -192,6 +192,19 @@ public class ListObject extends Data {\nreturn set(pos1, pos2, data);\n}\n+ public ListObject append(Data dat) {\n+ append(null, dat);\n+ return this;\n+ }\n+\n+ public ListObject append(String name, Data dat) {\n+ if( _names != null && name == null )\n+ throw new DMLRuntimeException(\"Cannot append to a named list\");\n+ //otherwise append and ignore name\n+ _data.add(dat);\n+ return this;\n+ }\n+\nprivate int getPosForName(String name) {\n//check for existing named list\nif ( _names == null )\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/MatrixAppendCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/MatrixAppendCPInstruction.java",
"diff": "@@ -29,9 +29,9 @@ import org.tugraz.sysds.runtime.matrix.operators.Operator;\npublic final class MatrixAppendCPInstruction extends AppendCPInstruction implements LineageTraceable {\n- protected MatrixAppendCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out,\n+ protected MatrixAppendCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out,\nAppendType type, String opcode, String istr) {\n- super(op, in1, in2, in3, out, type, opcode, istr);\n+ super(op, in1, in2, out, type, opcode, istr);\n}\n@Override\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ScalarAppendCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ScalarAppendCPInstruction.java",
"diff": "@@ -24,9 +24,9 @@ import org.tugraz.sysds.runtime.matrix.operators.Operator;\npublic final class ScalarAppendCPInstruction extends AppendCPInstruction {\n- protected ScalarAppendCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out,\n+ protected ScalarAppendCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out,\nAppendType type, String opcode, String istr) {\n- super(op, in1, in2, in3, out, type, opcode, istr);\n+ super(op, in1, in2, out, type, opcode, istr);\n}\n@Override\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/transform/encode/EncoderFeatureHash.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/transform/encode/EncoderFeatureHash.java",
"diff": "@@ -44,7 +44,7 @@ public class EncoderFeatureHash extends Encoder\n* @return K value\n* @throws JSONException\n*/\n- private long getK(JSONObject parsedSpec) throws JSONException {\n+ private static long getK(JSONObject parsedSpec) throws JSONException {\n//TODO generalize to different k per feature\nreturn parsedSpec.getLong(\"K\");\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/misc/ListAppendRemove.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/ListAppendRemove.java",
"diff": "@@ -105,13 +105,13 @@ public class ListAppendRemove extends AutomatedTestBase\ndouble[][] ret = TestUtils.convertHashMapToDoubleArray(\nreadDMLMatrixFromHDFS(\"R\"), 4, 1);\nAssert.assertEquals(new Double(ret[0][0]), new Double(0)); //empty list\n- //Assert.assertEquals(new Double(ret[1][0]), new Double(7)); //append list\n+ Assert.assertEquals(new Double(ret[1][0]), new Double(7)); //append list\n//Assert.assertEquals(new Double(ret[2][0]), new Double(3)); //remove list\n//check for properly compiled CP operations for list\n//(but spark instructions for sum, indexing, write)\nint numExpected = (type == ExecType.CP) ? 0 :\n- conditional ? 3 : 2;\n+ conditional ? 4 : 3;\nAssert.assertTrue(Statistics.getNoOfExecutedSPInst()==numExpected);\nAssert.assertTrue(Statistics.getNoOfExecutedSPInst()==numExpected);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/misc/ListAppendRemove.dml",
"new_path": "src/test/scripts/functions/misc/ListAppendRemove.dml",
"diff": "@@ -25,5 +25,10 @@ if( cond & sum(R) > 0 )\nL = list(R, R);\nR[1,] = length(L);\n+# list append\n+for(i in 1:7)\n+ L = append(L, as.matrix(i))\n+R[2,] = length(L);\n+\nwrite(R, $2);\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-213] Extended binary append operations for list append
This patch adds the functionality of appending arbitrary data objects to
lists, which is useful for constructing collections of matrices (e.g.,
CV). Furthermore, this also includes a cleanup of all CP append
instructions. |
49,738 | 08.12.2019 01:05:41 | -3,600 | bc1a6a1985a8df7c68bd46cb3acbf073fd5e44a0 | New remove builtin function for list entry removals
This patch adds a new multi-return builtin function of the following
pattern, that removes the ith entry from list L and returns the modified
list L2 (without the entry) and x (the removed entry).
[L2, x] = remove(L, i); | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -151,7 +151,7 @@ SYSTEMDS-210 Extended lists Operations\n* 211 Cbind and Rbind over lists of matrices OK\n* 212 Creation of empty lists OK\n* 213 Add entries to lists OK\n- * 214 Removal of entries from lists\n+ * 214 Removal of entries from lists OK\nOthers:\n* Break append instruction to cbind and rbind\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"diff": "@@ -126,6 +126,7 @@ public enum Builtins {\nQUANTILE(\"quantile\", false),\nRANGE(\"range\", false),\nRBIND(\"rbind\", false),\n+ REMOVE(\"remove\", false, ReturnType.MULTI_RETURN),\nREV(\"rev\", false),\nROUND(\"round\", false),\nROWINDEXMAX(\"rowIndexMax\", false),\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/lops/FunctionCallCP.java",
"new_path": "src/main/java/org/tugraz/sysds/lops/FunctionCallCP.java",
"diff": "@@ -26,6 +26,7 @@ import org.tugraz.sysds.hops.FunctionOp;\nimport org.tugraz.sysds.hops.Hop;\nimport org.tugraz.sysds.lops.LopProperties.ExecType;\nimport org.tugraz.sysds.parser.DMLProgram;\n+import org.tugraz.sysds.common.Builtins;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.ValueType;\n@@ -79,6 +80,10 @@ public class FunctionCallCP extends Lop\nreturn _outputLops;\n}\n+ public boolean requiresOutputCreateVar() {\n+ return !_fname.equalsIgnoreCase(Builtins.REMOVE.getName());\n+ }\n+\n@Override\npublic String toString() {\nreturn \"function call: \" + DMLProgram.constructFunctionKey(_fnamespace, _fname);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/lops/compile/Dag.java",
"new_path": "src/main/java/org/tugraz/sysds/lops/compile/Dag.java",
"diff": "@@ -819,8 +819,9 @@ public class Dag<N extends Lop>\nelse {\n// If the function call is set with output lops (e.g., multi return builtin),\n// generate a createvar instruction for each function output\n+ // (except for remove, which creates list outputs, i.e., meta data objects)\nFunctionCallCP fcall = (FunctionCallCP) node;\n- if ( fcall.getFunctionOutputs() != null ) {\n+ if ( fcall.getFunctionOutputs() != null && fcall.requiresOutputCreateVar() ) {\nfor( Lop fnOut: fcall.getFunctionOutputs()) {\nOutputParameters fnOutParams = fnOut.getOutputParameters();\n//OutputInfo oinfo = getOutputInfo((N)fnOut, false);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/BuiltinFunctionExpression.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/BuiltinFunctionExpression.java",
"diff": "@@ -328,7 +328,7 @@ public class BuiltinFunctionExpression extends DataIdentifier\nsetDimensions(dBias, getThirdExpr());\nbreak;\n}\n- case EIGEN:\n+ case EIGEN: {\ncheckNumParameters(1);\ncheckMatrixParam(getFirstExpr());\n@@ -353,7 +353,29 @@ public class BuiltinFunctionExpression extends DataIdentifier\neigenOut2.setBlocksize(getFirstExpr().getOutput().getBlocksize());\nbreak;\n+ }\n+ case REMOVE: {\n+ checkNumParameters(2);\n+ checkListParam(getFirstExpr());\n+\n+ // setup output properties\n+ DataIdentifier out1 = (DataIdentifier) getOutputs()[0];\n+ DataIdentifier out2 = (DataIdentifier) getOutputs()[1];\n+ // Output1 - Eigen Values\n+ out1.setDataType(DataType.LIST);\n+ out1.setValueType(getFirstExpr().getOutput().getValueType());\n+ out1.setDimensions(getFirstExpr().getOutput().getDim1()-1, 1);\n+ out1.setBlocksize(getFirstExpr().getOutput().getBlocksize());\n+\n+ // Output2 - Eigen Vectors\n+ out2.setDataType(DataType.LIST);\n+ out2.setValueType(getFirstExpr().getOutput().getValueType());\n+ out2.setDimensions(1, 1);\n+ out2.setBlocksize(getFirstExpr().getOutput().getBlocksize());\n+\n+ break;\n+ }\ncase SVD:\ncheckNumParameters(1);\ncheckMatrixParam(getFirstExpr());\n@@ -1770,14 +1792,20 @@ public class BuiltinFunctionExpression extends DataIdentifier\nprivate void checkScalarParam(Expression e) { //always unconditional\nif (e.getOutput().getDataType() != DataType.SCALAR) {\n- raiseValidateError(\"Expecting scalar parameter for function \" + this.getOpCode(), false, LanguageErrorCodes.UNSUPPORTED_PARAMETERS);\n+ raiseValidateError(\"Expecting scalar parameter for function \" + getOpCode(), false, LanguageErrorCodes.UNSUPPORTED_PARAMETERS);\n+ }\n+ }\n+\n+ private void checkListParam(Expression e) { //always unconditional\n+ if (e.getOutput().getDataType() != DataType.LIST) {\n+ raiseValidateError(\"Expecting scalar parameter for function \" + getOpCode(), false, LanguageErrorCodes.UNSUPPORTED_PARAMETERS);\n}\n}\n@SuppressWarnings(\"unused\")\nprivate void checkScalarFrameParam(Expression e) { //always unconditional\nif (e.getOutput().getDataType() != DataType.SCALAR && e.getOutput().getDataType() != DataType.FRAME) {\n- raiseValidateError(\"Expecting scalar parameter for function \" + this.getOpCode(), false, LanguageErrorCodes.UNSUPPORTED_PARAMETERS);\n+ raiseValidateError(\"Expecting scalar parameter for function \" + getOpCode(), false, LanguageErrorCodes.UNSUPPORTED_PARAMETERS);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/DMLTranslator.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/DMLTranslator.java",
"diff": "@@ -2122,6 +2122,7 @@ public class DMLTranslator\ncase LSTM_BACKWARD:\ncase BATCH_NORM2D:\ncase BATCH_NORM2D_BACKWARD:\n+ case REMOVE:\ncase SVD:\n// Number of outputs = size of targetList = #of identifiers in source.getOutputs\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/CPInstructionParser.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/CPInstructionParser.java",
"diff": "@@ -265,6 +265,7 @@ public class CPInstructionParser extends InstructionParser\nString2CPInstructionType.put( \"extfunct\", CPType.External);\nString2CPInstructionType.put( Append.OPCODE, CPType.Append);\n+ String2CPInstructionType.put( \"remove\", CPType.Append);\n// data generation opcodes\nString2CPInstructionType.put( DataGen.RAND_OPCODE , CPType.Rand);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/AppendCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/AppendCPInstruction.java",
"diff": "@@ -47,19 +47,19 @@ public abstract class AppendCPInstruction extends BinaryCPInstruction\npublic static AppendCPInstruction parseInstruction ( String str ) {\nString[] parts = InstructionUtils.getInstructionPartsWithValueType(str);\n- InstructionUtils.checkNumFields (parts, 5);\n+ InstructionUtils.checkNumFields (parts, 5, 4);\nString opcode = parts[0];\nCPOperand in1 = new CPOperand(parts[1]);\nCPOperand in2 = new CPOperand(parts[2]);\n- CPOperand out = new CPOperand(parts[4]);\n- boolean cbind = Boolean.parseBoolean(parts[5]);\n+ CPOperand out = new CPOperand(parts[parts.length-2]);\n+ boolean cbind = Boolean.parseBoolean(parts[parts.length-1]);\nAppendType type = (in1.getDataType()!=DataType.MATRIX && in1.getDataType()!=DataType.FRAME) ?\nin1.getDataType()==DataType.LIST ? AppendType.LIST : AppendType.STRING :\ncbind ? AppendType.CBIND : AppendType.RBIND;\n- if(!opcode.equalsIgnoreCase(\"append\"))\n+ if(!opcode.equalsIgnoreCase(\"append\") && !opcode.equalsIgnoreCase(\"remove\"))\nthrow new DMLRuntimeException(\"Unknown opcode while parsing a AppendCPInstruction: \" + str);\nOperator op = new ReorgOperator(OffsetColumnIndex.getOffsetColumnIndexFnObject(-1));\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListAppendRemoveCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListAppendRemoveCPInstruction.java",
"diff": "@@ -18,28 +18,44 @@ package org.tugraz.sysds.runtime.instructions.cp;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\n+import org.tugraz.sysds.runtime.instructions.InstructionUtils;\nimport org.tugraz.sysds.runtime.matrix.operators.Operator;\npublic final class ListAppendRemoveCPInstruction extends AppendCPInstruction {\n+ private CPOperand output2 = null;\n+\nprotected ListAppendRemoveCPInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out,\nAppendType type, String opcode, String istr) {\nsuper(op, in1, in2, out, type, opcode, istr);\n+ if( opcode.equals(\"remove\") )\n+ output2 = new CPOperand(InstructionUtils.getInstructionPartsWithValueType(istr)[4]);\n}\n@Override\npublic void processInstruction(ExecutionContext ec) {\n//get input list and data\nListObject lo = ec.getListObject(input1);\n- Data dat2 = ec.getVariable(input2);\n//list append instruction\nif( getOpcode().equals(\"append\") ) {\n//copy on write and append unnamed argument\n- ListObject tmp = lo.copy().append(dat2);\n+ Data dat2 = ec.getVariable(input2);\n+ ListObject tmp = lo.copy().add(dat2);\n//set output variable\nec.setVariable(output.getName(), tmp);\n}\n+ //list remove instruction\n+ else if( getOpcode().equals(\"remove\") ) {\n+ //copy on write and remove by position\n+ ScalarObject dat2 = ec.getScalarInput(input2);\n+ ListObject tmp1 = lo.copy();\n+ ListObject tmp2 = tmp1.remove((int)dat2.getLongValue()-1);\n+\n+ //set output variables\n+ ec.setVariable(output.getName(), tmp1);\n+ ec.setVariable(output2.getName(), tmp2);\n+ }\nelse {\nthrow new DMLRuntimeException(\"Unsupported list operation: \"+getOpcode());\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListObject.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListObject.java",
"diff": "@@ -192,19 +192,27 @@ public class ListObject extends Data {\nreturn set(pos1, pos2, data);\n}\n- public ListObject append(Data dat) {\n- append(null, dat);\n+ public ListObject add(Data dat) {\n+ add(null, dat);\nreturn this;\n}\n- public ListObject append(String name, Data dat) {\n+ public ListObject add(String name, Data dat) {\nif( _names != null && name == null )\n- throw new DMLRuntimeException(\"Cannot append to a named list\");\n+ throw new DMLRuntimeException(\"Cannot add to a named list\");\n//otherwise append and ignore name\n_data.add(dat);\nreturn this;\n}\n+ public ListObject remove(int pos) {\n+ ListObject ret = new ListObject(Arrays.asList(_data.get(pos)));\n+ _data.remove(pos);\n+ if( _names != null )\n+ _names.remove(pos);\n+ return ret;\n+ }\n+\nprivate int getPosForName(String name) {\n//check for existing named list\nif ( _names == null )\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/misc/ListAppendRemove.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/ListAppendRemove.java",
"diff": "@@ -111,7 +111,7 @@ public class ListAppendRemove extends AutomatedTestBase\n//check for properly compiled CP operations for list\n//(but spark instructions for sum, indexing, write)\nint numExpected = (type == ExecType.CP) ? 0 :\n- conditional ? 4 : 3;\n+ conditional ? 5 : 4;\nAssert.assertTrue(Statistics.getNoOfExecutedSPInst()==numExpected);\nAssert.assertTrue(Statistics.getNoOfExecutedSPInst()==numExpected);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/misc/ListAppendRemove.dml",
"new_path": "src/test/scripts/functions/misc/ListAppendRemove.dml",
"diff": "@@ -30,5 +30,11 @@ for(i in 1:7)\nL = append(L, as.matrix(i))\nR[2,] = length(L);\n+# list remove\n+for(i in 1:4) {\n+ [L,x] = remove(L, 2);\n+ print(toString(as.matrix(x)));\n+}\n+R[3,] = length(L);\nwrite(R, $2);\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-214] New remove builtin function for list entry removals
This patch adds a new multi-return builtin function of the following
pattern, that removes the ith entry from list L and returns the modified
list L2 (without the entry) and x (the removed entry).
[L2, x] = remove(L, i); |
49,738 | 10.12.2019 20:51:49 | -3,600 | 0421b6d21359dccc2a4d780c684005357299fa39 | Fix exec type selection rbind/cbind over lists
This patch fixes an issue of invalid execution type selection as rbind
and cbind over lists are currently only supported in CP. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/BinaryOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/BinaryOp.java",
"diff": "@@ -761,7 +761,8 @@ public class BinaryOp extends MultiThreadedHop\nelse\n_etype = ExecType.CP;\n}\n- else if( op == OpOp2.CBIND && getDataType().isList() ) {\n+ else if( (op == OpOp2.CBIND && getDataType().isList())\n+ || (op == OpOp2.RBIND && getDataType().isList())) {\n_etype = ExecType.CP;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/NaryOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/NaryOp.java",
"diff": "@@ -173,7 +173,10 @@ public class NaryOp extends Hop {\nsetRequiresRecompileIfNecessary();\n//ensure cp exec type for single-node operations\n- if ( _op == OpOpN.PRINTF || _op == OpOpN.EVAL || _op == OpOpN.LIST)\n+ if ( _op == OpOpN.PRINTF || _op == OpOpN.EVAL || _op == OpOpN.LIST\n+ //TODO: cbind/rbind of lists only support in CP right now\n+ || (_op == OpOpN.CBIND && getInput().get(0).getDataType().isList())\n+ || (_op == OpOpN.RBIND && getInput().get(0).getDataType().isList()))\n_etype = ExecType.CP;\nreturn _etype;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RewriteListTsmmCVTest.java",
"diff": "+/*\n+ * Licensed to the Apache Software Foundation (ASF) under one\n+ * or more contributor license agreements. See the NOTICE file\n+ * distributed with this work for additional information\n+ * regarding copyright ownership. The ASF licenses this file\n+ * to you under the Apache License, Version 2.0 (the\n+ * \"License\"); you may not use this file except in compliance\n+ * with the License. You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing,\n+ * software distributed under the License is distributed on an\n+ * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+ * KIND, either express or implied. See the License for the\n+ * specific language governing permissions and limitations\n+ * under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.misc;\n+\n+import java.util.HashMap;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types.ExecMode;\n+import org.tugraz.sysds.hops.OptimizerUtils;\n+import org.tugraz.sysds.lops.LopProperties.ExecType;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+import org.tugraz.sysds.utils.Statistics;\n+\n+/**\n+ * Regression test for function recompile-once issue with literal replacement.\n+ *\n+ */\n+public class RewriteListTsmmCVTest extends AutomatedTestBase\n+{\n+ private static final String TEST_NAME1 = \"RewriteListTsmmCV\";\n+\n+ private static final String TEST_DIR = \"functions/misc/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + RewriteListTsmmCVTest.class.getSimpleName() + \"/\";\n+\n+ private static final int rows = 10001;\n+ private static final int cols = 100;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { \"R\" }) );\n+ }\n+\n+ @Test\n+ public void testListTsmmRewriteCP() {\n+ testListTsmmCV(TEST_NAME1, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testListTsmmRewriteSP() {\n+ testListTsmmCV(TEST_NAME1, false, ExecType.SPARK);\n+ }\n+\n+ //TODO lineage\n+ //TODO rewrites\n+\n+ private void testListTsmmCV( String testname, boolean rewrites, ExecType instType )\n+ {\n+ ExecMode platformOld = setExecMode(instType);\n+\n+ boolean rewritesOld = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewrites;\n+\n+ try\n+ {\n+ TestConfiguration config = getTestConfiguration(testname);\n+ loadTestConfiguration(config);\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + testname + \".dml\";\n+ programArgs = new String[]{\"-explain\", \"-stats\",\"-args\",\n+ String.valueOf(rows), String.valueOf(cols), output(\"S\") };\n+\n+ fullRScriptName = HOME + testname + \".R\";\n+ rCmd = getRCmd(inputDir(), expectedDir());\n+\n+ runTest(true, false, null, -1);\n+\n+ //compare matrices\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"S\");\n+ Assert.assertEquals(new Double(cols*7), dmlfile.get(new CellIndex(1,1)));\n+\n+ if( rewrites ) {\n+ String[] codes = (instType==ExecType.CP) ?\n+ new String[]{\"rbind\",\"tsmm\",\"ba+*\",\"+\"} :\n+ new String[]{\"sp_append\",\"sp_tsmm\",\"sp_mapmm\",\"sp_map+\"};\n+ Assert.assertTrue(!heavyHittersContainsString(codes[0]));\n+ Assert.assertTrue(Statistics.getCPHeavyHitterCount(codes[1]) == 4);\n+ Assert.assertTrue(Statistics.getCPHeavyHitterCount(codes[2]) == 4);\n+ Assert.assertTrue(Statistics.getCPHeavyHitterCount(codes[3]) == 4);\n+ }\n+ }\n+ finally {\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewritesOld;\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/misc/RewriteListTsmmCV.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+crossV = function(Matrix[double] X, Matrix[double] y, double lamda, Integer k) return (Matrix[double] R)\n+{\n+ #create empty lists\n+ dataset_X = list(); #empty list\n+ dataset_y = list();\n+ fs = ceil(nrow(X)/k);\n+ off = fs - 1;\n+ #devide X, y into lists of k matrices\n+ for (i in seq(1, k)) {\n+ dataset_X = append(dataset_X, X[i*fs-off : min(i*fs, nrow(X)),]);\n+ dataset_y = append(dataset_y, y[i*fs-off : min(i*fs, nrow(y)),]);\n+ }\n+\n+ beta_list = list();\n+ #keep one fold for testing in each iteration\n+ for (i in seq(1, k)) {\n+ [tmpX, testX] = remove(dataset_X, i);\n+ [tmpy, testy] = remove(dataset_y, i);\n+ trainX = rbind(tmpX);\n+ trainy = rbind(tmpy);\n+ beta = SimlinRegDS(trainX, trainy, lamda, ncol(X));\n+ beta_list = append(beta_list, beta);\n+ #FIXME: transpose is not getting picked\n+ }\n+\n+ R = cbind(beta_list);\n+}\n+\n+SimlinRegDS = function(Matrix[Double] X, Matrix[Double] y, Double lamda, Integer N) return (Matrix[double] beta)\n+{\n+ A = (t(X) %*% X) + diag(matrix(lamda, rows=N, cols=1));\n+ b = t(X) %*% y;\n+ beta = solve(A, b);\n+}\n+\n+\n+X = rand(rows=$1, cols=$2);\n+y = X %*% rand(rows=$2, cols=1);\n+\n+R = crossV(X, y, 0.001, 7);\n+\n+r = as.matrix(sum(R!=0));\n+write(r, $3);\n+#expected: \"Result: $2*7\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-211] Fix exec type selection rbind/cbind over lists
This patch fixes an issue of invalid execution type selection as rbind
and cbind over lists are currently only supported in CP. |
49,720 | 14.12.2019 11:40:21 | -3,600 | 60d16f6d69e901e9ff1025bdcc378ba89fbce8cf | New built-in function multiLogReg algorithm, incl tests
Builtin Multinomial Logistic Regression using Trust Region methods
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -142,6 +142,7 @@ SYSTEMDS-180 New Builtin Functions II OK\n* 189 Builtin function mice (chained equation imputation) OK\nSYSTEMDS-190 New Builtin Functions III\n+ * 191 Builtin function multi logreg OK\nSYSTEMDS-200 Various Fixes\n* 201 Fix spark append instruction zero columns OK\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/builtin/multiLogReg.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Modifications Copyright 2019 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#\n+#-------------------------------------------------------------\n+\n+# Solves Multinomial Logistic Regression using Trust Region method.\n+# (See: Trust Region Newton Method for Logistic Regression, Lin, Weng and Keerthi, JMLR 9 (2008) 627-650)\n+\n+# INPUT PARAMETERS:\n+# --------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# --------------------------------------------------------------------------------------------\n+# X String --- Location to read the matrix of feature vectors\n+# Y String --- Location to read the matrix with category labels\n+# icpt Int 0 Intercept presence, shifting and rescaling X columns:\n+# 0 = no intercept, no shifting, no rescaling;\n+# 1 = add intercept, but neither shift nor rescale X;\n+# 2 = add intercept, shift & rescale X columns to mean = 0, variance = 1\n+# reg Double 0.0 regularization parameter (lambda = 1/C); intercept is not regularized\n+# tol Double 0.000001 tolerance (\"epsilon\")\n+# maxi Int 100 max. number of outer (Newton) iterations\n+# maxii Int 0 max. number of inner (conjugate gradient) iterations, 0 = no max\n+\n+# --------------------------------------------------------------------------------------------\n+# The largest label represents the baseline category; if label -1 or 0 is present, then it is\n+# the baseline label (and it is converted to the largest label).\n+#\n+# NAME TYPE MEANING\n+# -------------------------------------------------------------------------------------------\n+# betas Double regression betas as output for prediction\n+# -------------------------------------------------------------------------------------------\n+\n+m_multiLogReg = function(Matrix[Double] X, Matrix[Double] Y, Integer icpt = 2, Double tol = 0.000001,\n+ Double reg = 1.0, Integer maxi = 100, Integer maxii = 20, Boolean verbose = TRUE)\n+ return(Matrix[Double] betas)\n+{\n+\n+ eta0 = 0.0001;\n+ eta1 = 0.25;\n+ eta2 = 0.75;\n+ sigma1 = 0.25;\n+ sigma2 = 0.5;\n+ sigma3 = 4.0;\n+ psi = 0.1;\n+\n+ N = nrow (X);\n+ D = ncol (X);\n+\n+ # Introduce the intercept, shift and rescale the columns of X if needed\n+ if (icpt == 1 | icpt == 2) { # add the intercept column\n+ X = cbind (X, matrix (1, N, 1));\n+ D = ncol (X);\n+ }\n+\n+ scale_lambda = matrix (1, D, 1);\n+ if (icpt == 1 | icpt == 2)\n+ scale_lambda [D, 1] = 0;\n+\n+ if (icpt == 2) # scale-&-shift X columns to mean 0, variance 1\n+ { # Important assumption: X [, D] = matrix (1, N, 1)\n+ avg_X_cols = t(colSums(X)) / N;\n+ var_X_cols = (t(colSums (X ^ 2)) - N * (avg_X_cols ^ 2)) / (N - 1);\n+ is_unsafe = var_X_cols <= 0;\n+ scale_X = 1.0 / sqrt (var_X_cols * (1 - is_unsafe) + is_unsafe);\n+ scale_X [D, 1] = 1;\n+ shift_X = - avg_X_cols * scale_X;\n+ shift_X [D, 1] = 0;\n+ rowSums_X_sq = (X ^ 2) %*% (scale_X ^ 2) + X %*% (2 * scale_X * shift_X) + sum (shift_X ^ 2);\n+ }\n+ else {\n+ scale_X = matrix (1, D, 1);\n+ shift_X = matrix (0, D, 1);\n+ rowSums_X_sq = rowSums (X ^ 2);\n+ }\n+\n+ # Henceforth we replace \"X\" with \"X %*% (SHIFT/SCALE TRANSFORM)\" and rowSums(X ^ 2)\n+ # with \"rowSums_X_sq\" in order to preserve the sparsity of X under shift and scale.\n+ # The transform is then associatively applied to the other side of the expression,\n+ # and is rewritten via \"scale_X\" and \"shift_X\" as follows:\n+ # ssX_A = (SHIFT/SCALE TRANSFORM) %*% A --- is rewritten as:\n+ # ssX_A = diag (scale_X) %*% A;\n+ # ssX_A [D, ] = ssX_A [D, ] + t(shift_X) %*% A;\n+ # tssX_A = t(SHIFT/SCALE TRANSFORM) %*% A --- is rewritten as:\n+ # tssX_A = diag (scale_X) %*% A + shift_X %*% A [D, ];\n+\n+ # Convert \"Y\" into indicator matrix:\n+ max_y = max (Y);\n+ if (min (Y) <= 0) {\n+ # Category labels \"0\", \"-1\" etc. are converted into the largest label\n+ Y = Y + (- Y + max_y + 1) * (Y <= 0);\n+ max_y = max_y + 1;\n+ }\n+ Y = table (seq (1, N, 1), Y, N, max_y);\n+ K = ncol (Y) - 1; # The number of non-baseline categories\n+\n+ lambda = (scale_lambda %*% matrix (1, 1, K)) * reg;\n+ delta = 0.5 * sqrt (D) / max (sqrt (rowSums_X_sq));\n+\n+ B = matrix (0, D, K); ### LT = X %*% (SHIFT/SCALE TRANSFORM) %*% B;\n+ ### LT = cbind (LT, matrix (0, rows = N, cols = 1));\n+ ### LT = LT - rowMaxs (LT) %*% matrix (1, rows = 1, cols = K+1);\n+ P = matrix (1, N, K+1); ### exp_LT = exp (LT);\n+ P = P / (K + 1); ### P = exp_LT / (rowSums (exp_LT) %*% matrix (1, rows = 1, cols = K+1));\n+ obj = N * log (K + 1); ### obj = - sum (Y * LT) + sum (log (rowSums (exp_LT))) + 0.5 * sum (lambda * (B_new ^ 2));\n+\n+ Grad = t(X) %*% (P [, 1:K] - Y [, 1:K]);\n+ if (icpt == 2)\n+ Grad = diag (scale_X) %*% Grad + shift_X %*% Grad [D, ];\n+\n+ Grad = Grad + lambda * B;\n+ norm_Grad = sqrt (sum (Grad ^ 2));\n+ norm_Grad_initial = norm_Grad;\n+\n+ if (maxii == 0)\n+ maxii = D * K;\n+\n+ iter = 1;\n+\n+ # boolean for convergence check\n+ converge = (norm_Grad < tol) | (iter > maxi);\n+ if(verbose)\n+ print (\"-- Initially: Objective = \" + obj + \", Gradient Norm = \" + norm_Grad + \", Trust Delta = \" + delta);\n+\n+ while (! converge)\n+ {\n+ # SOLVE TRUST REGION SUB-PROBLEM\n+ S = matrix (0, D, K);\n+ R = - Grad;\n+ V = R;\n+ delta2 = delta ^ 2;\n+ inneriter = 1;\n+ norm_R2 = sum (R ^ 2);\n+ innerconverge = (sqrt (norm_R2) <= psi * norm_Grad);\n+ is_trust_boundary_reached = 0;\n+\n+ while (! innerconverge)\n+ {\n+ if (icpt == 2) {\n+ ssX_V = diag (scale_X) %*% V;\n+ ssX_V [D, ] = ssX_V [D, ] + t(shift_X) %*% V;\n+ }\n+ else\n+ ssX_V = V;\n+\n+ Q = P [, 1:K] * (X %*% ssX_V);\n+ HV = t(X) %*% (Q - P [, 1:K] * (rowSums (Q) %*% matrix (1, 1, K)));\n+\n+ if (icpt == 2)\n+ HV = diag (scale_X) %*% HV + shift_X %*% HV [D, ];\n+\n+ HV = HV + lambda * V;\n+ alpha = norm_R2 / sum (V * HV);\n+ Snew = S + alpha * V;\n+ norm_Snew2 = sum (Snew ^ 2);\n+ if (norm_Snew2 <= delta2) {\n+ S = Snew;\n+ R = R - alpha * HV;\n+ old_norm_R2 = norm_R2\n+ norm_R2 = sum (R ^ 2);\n+ V = R + (norm_R2 / old_norm_R2) * V;\n+ innerconverge = (sqrt (norm_R2) <= psi * norm_Grad);\n+ }\n+ else {\n+ is_trust_boundary_reached = 1;\n+ sv = sum (S * V);\n+ v2 = sum (V ^ 2);\n+ s2 = sum (S ^ 2);\n+ rad = sqrt (sv ^ 2 + v2 * (delta2 - s2));\n+ if (sv >= 0)\n+ alpha = (delta2 - s2) / (sv + rad);\n+ else\n+ alpha = (rad - sv) / v2;\n+ S = S + alpha * V;\n+ R = R - alpha * HV;\n+ innerconverge = TRUE;\n+ }\n+ inneriter = inneriter + 1;\n+ innerconverge = innerconverge | (inneriter > maxii);\n+ }\n+ # END TRUST REGION SUB-PROBLEM\n+ # compute rho, update B, obtain delta\n+ gs = sum (S * Grad);\n+ qk = - 0.5 * (gs - sum (S * R));\n+ B_new = B + S;\n+ if (icpt == 2) {\n+ ssX_B_new = diag (scale_X) %*% B_new;\n+ ssX_B_new [D, ] = ssX_B_new [D, ] + t(shift_X) %*% B_new;\n+ }\n+ else\n+ ssX_B_new = B_new;\n+\n+ LT = cbind ((X %*% ssX_B_new), matrix (0, N, 1));\n+ LT = LT - rowMaxs (LT) %*% matrix (1, 1, K+1);\n+ exp_LT = exp (LT);\n+ P_new = exp_LT / (rowSums (exp_LT) %*% matrix (1, 1, K+1));\n+ obj_new = - sum (Y * LT) + sum (log (rowSums (exp_LT))) + 0.5 * sum (lambda * (B_new ^ 2));\n+\n+ # Consider updating LT in the inner loop\n+ # Consider the big \"obj\" and \"obj_new\" rounding-off their small difference below:\n+\n+ actred = (obj - obj_new);\n+ rho = actred / qk;\n+ is_rho_accepted = (rho > eta0);\n+ snorm = sqrt (sum (S ^ 2));\n+\n+ if (iter == 1)\n+ delta = min (delta, snorm);\n+\n+ alpha2 = obj_new - obj - gs;\n+ alpha = ifelse(alpha2 <= 0, sigma3, max(sigma1, -0.5 * gs / alpha2));\n+\n+ if (rho < eta0)\n+ delta = min (max (alpha, sigma1) * snorm, sigma2 * delta);\n+ else if (rho < eta1)\n+ delta = max (sigma1 * delta, min (alpha * snorm, sigma2 * delta));\n+ else if (rho < eta2)\n+ delta = max (sigma1 * delta, min (alpha * snorm, sigma3 * delta));\n+ else\n+ delta = max (delta, min (alpha * snorm, sigma3 * delta));\n+\n+ if(verbose) {\n+ if (is_trust_boundary_reached == 1)\n+ print (\"-- Outer Iteration \" + iter + \": Had \" + (inneriter - 1) + \" CG iterations, trust bound REACHED\");\n+ else print (\"-- Outer Iteration \" + iter + \": Had \" + (inneriter - 1) + \" CG iterations\");\n+ print (\" -- Obj.Reduction: Actual = \" + actred + \", Predicted = \" + qk +\n+ \" (A/P: \" + (round (10000.0 * rho) / 10000.0) + \"), Trust Delta = \" + delta);\n+ }\n+\n+ if (is_rho_accepted) {\n+ B = B_new;\n+ P = P_new;\n+ Grad = t(X) %*% (P [, 1:K] - Y [, 1:K]);\n+ if (icpt == 2)\n+ Grad = diag (scale_X) %*% Grad + shift_X %*% Grad [D, ];\n+\n+ Grad = Grad + lambda * B;\n+ norm_Grad = sqrt (sum (Grad ^ 2));\n+ obj = obj_new;\n+\n+ if(verbose)\n+ print (\" -- New Objective = \" + obj + \", Beta Change Norm = \" + snorm + \", Gradient Norm = \" + norm_Grad);\n+ }\n+ iter = iter + 1;\n+ converge = ((norm_Grad < (tol * norm_Grad_initial)) | (iter > maxi) |\n+ ((is_trust_boundary_reached == 0) & (abs (actred) < (abs (obj) + abs (obj_new)) * 0.00000000000001)));\n+ if (converge) { print (\"Termination / Convergence condition satisfied.\"); }\n+ }\n+\n+ if (icpt == 2) {\n+ B_out = diag (scale_X) %*% B;\n+ B_out [D, ] = B_out [D, ] + t(shift_X) %*% B;\n+ }\n+ else {\n+ B_out = B;\n+ }\n+\n+ betas = B_out\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"diff": "@@ -93,7 +93,6 @@ public enum Builtins {\nIQM(\"interQuartileMean\", false),\nKMEANS(\"kmeans\", true),\nL2SVM(\"l2svm\", true),\n- MSVM(\"msvm\", true),\nLENGTH(\"length\", false),\nLINEAGE(\"lineage\", false),\nLIST(\"list\", false), //note: builtin and parbuiltin\n@@ -106,13 +105,15 @@ public enum Builtins {\nLSTM_BACKWARD(\"lstm_backward\", false, ReturnType.MULTI_RETURN),\nLU(\"lu\", false, ReturnType.MULTI_RETURN),\nMEAN(\"mean\", \"avg\", false),\n+ MICE_LM(\"mice_lm\", true),\nMIN(\"min\", \"pmin\", false),\nMAX(\"max\", \"pmax\", false),\nMAX_POOL(\"max_pool\", false),\nMAX_POOL_BACKWARD(\"max_pool_backward\", false),\nMEDIAN(\"median\", false),\nMOMENT(\"moment\", \"centralMoment\", false),\n- MICE_LM(\"mice_lm\", true),\n+ MSVM(\"msvm\", true),\n+ MULTILOGREG(\"multiLogReg\", true),\nNCOL(\"ncol\", false),\nNORMALIZE(\"normalize\", true),\nNROW(\"nrow\", false),\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinMultiLogRegTest.java",
"diff": "+/*\n+ * Copyright 2018 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.builtin;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.api.DMLScript;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.hops.OptimizerUtils;\n+import org.tugraz.sysds.lops.LopProperties;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+public class BuiltinMultiLogRegTest extends AutomatedTestBase {\n+\n+ private final static String TEST_NAME = \"multiLogReg\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinMultiLogRegTest.class.getSimpleName() + \"/\";\n+\n+ private final static double tol = 0.1;\n+ private final static int rows = 1500;\n+ private final static int colsX = 300;\n+ private final static double sparse = 0.3;\n+ private final static int maxIter = 10;\n+ private final static int maxInnerIter = 2;\n+\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[]{\"C\"}));\n+ }\n+\n+ @Test\n+ public void testMultiLogRegInterceptCP0() {\n+ runMultiLogeRegTest( 0, tol, 1.0, maxIter, maxInnerIter, LopProperties.ExecType.CP);\n+ }\n+ @Test\n+ public void testMultiLogRegInterceptCP1() {\n+ runMultiLogeRegTest( 1, tol, 1.0, maxIter, maxInnerIter, LopProperties.ExecType.CP);\n+ }\n+ @Test\n+ public void testMultiLogRegInterceptCP2() {\n+ runMultiLogeRegTest( 2, tol, 1.0, maxIter, maxInnerIter, LopProperties.ExecType.CP);\n+ }\n+ @Test\n+ public void testMultiLogRegInterceptSpark0() {\n+ runMultiLogeRegTest( 0, tol, 1.0, maxIter, maxInnerIter, LopProperties.ExecType.SPARK);\n+ }\n+ @Test\n+ public void testMultiLogRegInterceptSpark1() {\n+ runMultiLogeRegTest( 1, tol, 1.0, maxIter, maxInnerIter, LopProperties.ExecType.SPARK);\n+ }\n+ @Test\n+ public void testMultiLogRegInterceptSpark2() {\n+ runMultiLogeRegTest(2, tol, 1.0, maxIter, maxInnerIter, LopProperties.ExecType.SPARK);\n+ }\n+\n+ private void runMultiLogeRegTest( int inc, double tol, double reg, int maxOut, int maxIn, LopProperties.ExecType instType) {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+\n+ boolean oldFlag = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\n+\n+ try {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+\n+ programArgs = new String[]{\"-nvargs\", \"X=\" + input(\"X\"), \"Y=\" + input(\"Y\"), \"output=\" + output(\"betas\"),\n+ \"inc=\" + String.valueOf(inc).toUpperCase(), \"tol=\" + tol, \"reg=\" + reg, \"maxOut=\" + maxOut, \"maxIn=\"+maxIn, \"verbose=FALSE\"};\n+\n+ double[][] X = getRandomMatrix(rows, colsX, 0, 1, sparse, -1);\n+ double[][] Y = getRandomMatrix(rows, 1, 0, 5, 1, -1);\n+ Y = TestUtils.round(Y);\n+\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+ writeInputMatrixWithMTD(\"Y\", Y, true);\n+ runTest(true, false, null, -1);\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = oldFlag;\n+ OptimizerUtils.ALLOW_AUTO_VECTORIZATION = true;\n+ OptimizerUtils.ALLOW_OPERATOR_FUSION = true;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/builtin/MultiLogReg.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = read($X)\n+Y = read($Y)\n+betas= multiLogReg(X=X, Y=Y, icpt = $inc, tol = $tol, reg = $reg, maxi = $maxOut, maxii=$maxIn, verbose=$verbose)\n+write(betas, $output)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-191] New built-in function multiLogReg algorithm, incl tests
Builtin Multinomial Logistic Regression using Trust Region methods
Closes #73. |
49,689 | 14.12.2019 14:27:39 | -3,600 | 3ec19628e582db9d59938d3831fb5a9438a9f1d4 | Lineage handling for lists during dynamic recompilation
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -129,6 +129,7 @@ SYSTEMDS-170 Lineage full and partial reuse\n* 176 Reuse rewrite for cbind/rbind-elementwise */+\n* 177 Reuse rewrite for aggregate OK\n* 178 Compiler assisted reuse (eg. CV, lmCG)\n+ * 179 Lineage handling for lists OK\nSYSTEMDS-180 New Builtin Functions II OK\n* 181 Builtin function for naive bayes OK\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/recompile/LiteralReplacement.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/recompile/LiteralReplacement.java",
"diff": "@@ -41,6 +41,7 @@ import org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.LocalVariableMap;\nimport org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\n+import org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.tugraz.sysds.runtime.instructions.cp.Data;\nimport org.tugraz.sysds.runtime.instructions.cp.ListObject;\nimport org.tugraz.sysds.runtime.instructions.cp.ScalarObject;\n@@ -54,8 +55,7 @@ public class LiteralReplacement\nprivate static final long REPLACE_LITERALS_MAX_MATRIX_SIZE = 1000000; //10^6 cells (8MB)\nprivate static final boolean REPORT_LITERAL_REPLACE_OPS_STATS = true;\n- @SuppressWarnings(\"null\")\n- protected static void rReplaceLiterals( Hop hop, LocalVariableMap vars, boolean scalarsOnly )\n+ protected static void rReplaceLiterals( Hop hop, ExecutionContext ec, boolean scalarsOnly )\n{\nif( hop.isVisited() )\nreturn;\n@@ -63,6 +63,7 @@ public class LiteralReplacement\nif( hop.getInput() != null )\n{\n//indexed access to allow parent-child modifications\n+ LocalVariableMap vars = ec.getVariables();\nfor( int i=0; i<hop.getInput().size(); i++ )\n{\nHop c = hop.getInput().get(i);\n@@ -77,8 +78,8 @@ public class LiteralReplacement\nlit = (lit==null) ? replaceLiteralValueTypeCastRightIndexing(c, vars) : lit;\nlit = (lit==null) ? replaceLiteralFullUnaryAggregate(c, vars) : lit;\nlit = (lit==null) ? replaceLiteralFullUnaryAggregateRightIndexing(c, vars) : lit;\n- lit = (lit==null) ? replaceTReadMatrixFromList(c, vars) : lit;\n- lit = (lit==null) ? replaceTReadMatrixFromListAppend(c, vars) : lit;\n+ lit = (lit==null) ? replaceTReadMatrixFromList(c, ec) : lit;\n+ lit = (lit==null) ? replaceTReadMatrixFromListAppend(c, ec) : lit;\nlit = (lit==null) ? replaceTReadMatrixLookupFromList(c, vars) : lit;\nlit = (lit==null) ? replaceTReadScalarLookupFromList(c, vars) : lit;\n}\n@@ -103,7 +104,7 @@ public class LiteralReplacement\n}\n//recursively process children\nelse {\n- rReplaceLiterals(c, vars, scalarsOnly);\n+ rReplaceLiterals(c, ec, scalarsOnly);\n}\n}\n}\n@@ -111,7 +112,6 @@ public class LiteralReplacement\nhop.setVisited();\n}\n-\n///////////////////////////////\n// Literal replacement rules\n///////////////////////////////\n@@ -337,40 +337,44 @@ public class LiteralReplacement\nreturn ret;\n}\n- private static DataOp replaceTReadMatrixFromList( Hop c, LocalVariableMap vars ) {\n+ private static DataOp replaceTReadMatrixFromList( Hop c, ExecutionContext ec ) {\n//pattern: as.matrix(X) or as.matrix(X) with X being a list\nDataOp ret = null;\nif( HopRewriteUtils.isUnary(c, OpOp1.CAST_AS_MATRIX) ) {\nHop in = c.getInput().get(0);\nif( in.getDataType() == DataType.LIST\n&& HopRewriteUtils.isData(in, DataOpTypes.TRANSIENTREAD) ) {\n- ListObject list = (ListObject)vars.get(in.getName());\n+ ListObject list = (ListObject)ec.getVariables().get(in.getName());\nif( list.getLength() == 1 ) {\nString varname = Dag.getNextUniqueVarname(DataType.MATRIX);\nMatrixObject mo = (MatrixObject) list.slice(0);\n- vars.put(varname, mo);\n+ ec.getVariables().put(varname, mo);\nret = HopRewriteUtils.createTransientRead(varname, c);\n+ if (DMLScript.LINEAGE)\n+ ec.getLineage().set(varname, list.getLineageItem(0));\n}\n}\n}\nreturn ret;\n}\n- private static NaryOp replaceTReadMatrixFromListAppend( Hop c, LocalVariableMap vars ) {\n+ private static NaryOp replaceTReadMatrixFromListAppend( Hop c, ExecutionContext ec ) {\n//pattern: cbind(X) or rbind(X) with X being a list\nNaryOp ret = null;\nif( HopRewriteUtils.isNary(c, OpOpN.CBIND, OpOpN.RBIND)) {\nHop in = c.getInput().get(0);\nif( in.getDataType() == DataType.LIST\n&& HopRewriteUtils.isData(in, DataOpTypes.TRANSIENTREAD) ) {\n- ListObject list = (ListObject)vars.get(in.getName());\n+ ListObject list = (ListObject)ec.getVariables().get(in.getName());\nif( list.getLength() <= 128 ) {\nArrayList<Hop> tmp = new ArrayList<>();\nfor( int i=0; i < list.getLength(); i++ ) {\nString varname = Dag.getNextUniqueVarname(DataType.MATRIX);\nMatrixObject mo = (MatrixObject) list.slice(i);\n- vars.put(varname, mo);\n+ ec.getVariables().put(varname, mo);\ntmp.add(HopRewriteUtils.createTransientRead(varname, mo));\n+ if (DMLScript.LINEAGE)\n+ ec.getLineage().set(varname, list.getLineageItem(i));\n}\nret = HopRewriteUtils.createNary(\n((NaryOp)c).getOp(), tmp.toArray(new Hop[0]));\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/recompile/Recompiler.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/recompile/Recompiler.java",
"diff": "@@ -146,14 +146,14 @@ public class Recompiler\n}\npublic static ArrayList<Instruction> recompileHopsDag( StatementBlock sb, ArrayList<Hop> hops,\n- LocalVariableMap vars, RecompileStatus status, boolean inplace, boolean replaceLit, long tid )\n+ ExecutionContext ec, RecompileStatus status, boolean inplace, boolean replaceLit, long tid )\n{\nArrayList<Instruction> newInst = null;\n//need for synchronization as we do temp changes in shared hops/lops\n//however, we create deep copies for most dags to allow for concurrent recompile\nsynchronized( hops ) {\n- newInst = recompile(sb, hops, vars, status, inplace, replaceLit, true, false, false, null, tid);\n+ newInst = recompile(sb, hops, ec, status, inplace, replaceLit, true, false, false, null, tid);\n}\n// replace thread ids in new instructions\n@@ -161,8 +161,8 @@ public class Recompiler\nnewInst = ProgramConverter.createDeepCopyInstructionSet(newInst, tid, -1, null, null, null, false, false);\n// remove writes if called through mlcontext or jmlc\n- if( vars.getRegisteredOutputs() != null )\n- newInst = JMLCUtils.cleanupRuntimeInstructions(newInst, vars.getRegisteredOutputs());\n+ if( ec.getVariables().getRegisteredOutputs() != null )\n+ newInst = JMLCUtils.cleanupRuntimeInstructions(newInst, ec.getVariables().getRegisteredOutputs());\n// explain recompiled hops / instructions\nif( DMLScript.EXPLAIN == ExplainType.RECOMPILE_RUNTIME )\n@@ -171,6 +171,34 @@ public class Recompiler\nreturn newInst;\n}\n+ public static ArrayList<Instruction> recompileHopsDag( StatementBlock sb, ArrayList<Hop> hops,\n+ LocalVariableMap vars, RecompileStatus status, boolean inplace, boolean replaceLit, long tid )\n+ {\n+ return recompileHopsDag(sb, hops, new ExecutionContext(vars), status, inplace, replaceLit, tid);\n+ }\n+\n+ public static ArrayList<Instruction> recompileHopsDag( Hop hop, ExecutionContext ec,\n+ RecompileStatus status, boolean inplace, boolean replaceLit, long tid )\n+ {\n+ ArrayList<Instruction> newInst = null;\n+\n+ //need for synchronization as we do temp changes in shared hops/lops\n+ synchronized( hop ) {\n+ newInst = recompile(null, new ArrayList<>(Arrays.asList(hop)),\n+ ec, status, inplace, replaceLit, true, false, true, null, tid);\n+ }\n+\n+ // replace thread ids in new instructions\n+ if( tid != 0 ) //only in parfor context\n+ newInst = ProgramConverter.createDeepCopyInstructionSet(newInst, tid, -1, null, null, null, false, false);\n+\n+ // explain recompiled instructions\n+ if( DMLScript.EXPLAIN == ExplainType.RECOMPILE_RUNTIME )\n+ logExplainPred(hop, newInst);\n+\n+ return newInst;\n+ }\n+\npublic static ArrayList<Instruction> recompileHopsDag( Hop hop, LocalVariableMap vars,\nRecompileStatus status, boolean inplace, boolean replaceLit, long tid )\n{\n@@ -201,7 +229,7 @@ public class Recompiler\n//however, we create deep copies for most dags to allow for concurrent recompile\nsynchronized( hops ) {\n//always in place, no stats update/rewrites, but forced exec type\n- newInst = recompile(sb, hops, null, null, true, false, false, true, false, et, tid);\n+ newInst = recompile(sb, hops, (LocalVariableMap)null, null, true, false, false, true, false, et, tid);\n}\n// replace thread ids in new instructions\n@@ -223,7 +251,7 @@ public class Recompiler\nsynchronized( hop ) {\n//always in place, no stats update/rewrites, but forced exec type\nnewInst = recompile(null, new ArrayList<>(Arrays.asList(hop)),\n- null, null, true, false, false, true, true, et, tid);\n+ (LocalVariableMap)null, null, true, false, false, true, true, et, tid);\n}\n// replace thread ids in new instructions\n@@ -245,7 +273,7 @@ public class Recompiler\n//however, we create deep copies for most dags to allow for concurrent recompile\nsynchronized( hops ) {\n//always in place, no stats update/rewrites\n- newInst = recompile(sb, hops, null, null, true, false, false, false, false, null, 0);\n+ newInst = recompile(sb, hops, (LocalVariableMap)null, null, true, false, false, false, false, null, 0);\n}\n// explain recompiled hops / instructions\n@@ -263,13 +291,14 @@ public class Recompiler\nsynchronized( hop ) {\n//always in place, no stats update/rewrites\nnewInst = recompile(null, new ArrayList<>(Arrays.asList(hop)),\n- null, null, true, false, false, false, true, null, 0);\n+ (LocalVariableMap)null, null, true, false, false, false, true, null, 0);\n}\n// explain recompiled instructions\nif( DMLScript.EXPLAIN == ExplainType.RECOMPILE_RUNTIME )\nlogExplainPred(hop, newInst);\n+\nreturn newInst;\n}\n@@ -279,7 +308,7 @@ public class Recompiler\n*\n* @param sb statement block of DAG, null for predicates\n* @param hops list of DAG root nodes\n- * @param vars symbol table\n+ * @param ec Execution context\n* @param status recompilation status\n* @param inplace modify DAG in place, otherwise deep copy\n* @param replaceLit replace literals (only applicable on deep copy)\n@@ -290,7 +319,7 @@ public class Recompiler\n* @param tid thread id, 0 for main or before worker creation\n* @return modified list of instructions\n*/\n- private static ArrayList<Instruction> recompile(StatementBlock sb, ArrayList<Hop> hops, LocalVariableMap vars, RecompileStatus status,\n+ private static ArrayList<Instruction> recompile(StatementBlock sb, ArrayList<Hop> hops, ExecutionContext ec, RecompileStatus status,\nboolean inplace, boolean replaceLit, boolean updateStats, boolean forceEt, boolean pred, ExecType et, long tid )\n{\nboolean codegen = ConfigurationManager.isCodegenEnabled()\n@@ -317,7 +346,7 @@ public class Recompiler\nif( !inplace && replaceLit ) {\nHop.resetVisitStatus(hops);\nfor( Hop hopRoot : hops )\n- rReplaceLiterals( hopRoot, vars, false );\n+ rReplaceLiterals( hopRoot, ec, false );\n}\n// force exec type (et=null for reset)\n@@ -333,7 +362,7 @@ public class Recompiler\n// refresh matrix characteristics (update stats)\nHop.resetVisitStatus(hops);\nfor( Hop hopRoot : hops )\n- rUpdateStatistics( hopRoot, vars );\n+ rUpdateStatistics( hopRoot, ec.getVariables() );\n// dynamic hop rewrites\nif( !inplace ) {\n@@ -342,7 +371,7 @@ public class Recompiler\n//update stats after rewrites\nHop.resetVisitStatus(hops);\nfor( Hop hopRoot : hops )\n- rUpdateStatistics( hopRoot, vars );\n+ rUpdateStatistics( hopRoot, ec.getVariables() );\n}\n// refresh memory estimates (based on updated stats,\n@@ -395,6 +424,13 @@ public class Recompiler\nreturn newInst;\n}\n+ private static ArrayList<Instruction> recompile(StatementBlock sb, ArrayList<Hop> hops, LocalVariableMap vars, RecompileStatus status,\n+ boolean inplace, boolean replaceLit, boolean updateStats, boolean forceEt, boolean pred, ExecType et, long tid )\n+ {\n+ return recompile(sb, hops, new ExecutionContext(vars), status, inplace, replaceLit,\n+ updateStats, forceEt, pred, et, tid);\n+ }\n+\nprivate static void logExplainDAG(StatementBlock sb, ArrayList<Hop> hops, ArrayList<Instruction> inst) {\nParseInfo pi = (sb != null) ? sb : hops.get(0);\nif( DMLScript.EXPLAIN == ExplainType.RECOMPILE_HOPS ) {\n@@ -1411,14 +1447,20 @@ public class Recompiler\n* public interface to package local literal replacement\n*\n* @param hop high-level operator\n- * @param vars local variable map\n+ * @param ec Execution context\n* @param scalarsOnly if true, replace only scalar variables but no matrix operations;\n* if false, apply full literal replacement\n*/\n+ public static void rReplaceLiterals( Hop hop, ExecutionContext ec, boolean scalarsOnly )\n+ {\n+ //public interface\n+ LiteralReplacement.rReplaceLiterals(hop, ec, scalarsOnly);\n+ }\n+\npublic static void rReplaceLiterals( Hop hop, LocalVariableMap vars, boolean scalarsOnly )\n{\n//public interface\n- LiteralReplacement.rReplaceLiterals(hop, vars, scalarsOnly);\n+ LiteralReplacement.rReplaceLiterals(hop, new ExecutionContext(vars), scalarsOnly);\n}\npublic static void rSetExecType( Hop hop, ExecType etype ) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/BasicProgramBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/BasicProgramBlock.java",
"diff": "@@ -83,7 +83,7 @@ public class BasicProgramBlock extends ProgramBlock\n&& _sb.requiresRecompilation() )\n{\ntmp = Recompiler.recompileHopsDag(\n- _sb, _sb.getHops(), ec.getVariables(), null, false, true, _tid);\n+ _sb, _sb.getHops(), ec, null, false, true, _tid);\n}\nif( DMLScript.STATISTICS ){\nlong t1 = System.nanoTime();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/ExecutionContext.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/ExecutionContext.java",
"diff": "@@ -93,6 +93,12 @@ public class ExecutionContext {\n_prog = prog;\n}\n+ public ExecutionContext(LocalVariableMap vars) {\n+ _variables = vars;\n+ _lineage = null;\n+ _prog = null;\n+ }\n+\npublic Program getProgram(){\nreturn _prog;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListAppendRemoveCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListAppendRemoveCPInstruction.java",
"diff": "package org.tugraz.sysds.runtime.instructions.cp;\n+import org.tugraz.sysds.api.DMLScript;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.tugraz.sysds.runtime.instructions.InstructionUtils;\n+import org.tugraz.sysds.runtime.lineage.LineageItem;\nimport org.tugraz.sysds.runtime.matrix.operators.Operator;\npublic final class ListAppendRemoveCPInstruction extends AppendCPInstruction {\n@@ -41,7 +43,8 @@ public final class ListAppendRemoveCPInstruction extends AppendCPInstruction {\nif( getOpcode().equals(\"append\") ) {\n//copy on write and append unnamed argument\nData dat2 = ec.getVariable(input2);\n- ListObject tmp = lo.copy().add(dat2);\n+ LineageItem li = DMLScript.LINEAGE ? ec.getLineage().get(input2):null;\n+ ListObject tmp = lo.copy().add(dat2, li);\n//set output variable\nec.setVariable(output.getName(), tmp);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListObject.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ListObject.java",
"diff": "@@ -27,6 +27,7 @@ import org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.caching.CacheableData;\n+import org.tugraz.sysds.runtime.lineage.LineageItem;\npublic class ListObject extends Data {\nprivate static final long serialVersionUID = 3652422061598967358L;\n@@ -35,22 +36,29 @@ public class ListObject extends Data {\nprivate boolean[] _dataState = null;\nprivate List<String> _names = null;\nprivate int _nCacheable;\n+ private List<LineageItem> _lineage = null;\npublic ListObject(List<Data> data) {\n- this(data, null);\n+ this(data, null, null);\n}\npublic ListObject(List<Data> data, List<String> names) {\n+ this(data, names, null);\n+ }\n+\n+ public ListObject(List<Data> data, List<String> names, List<LineageItem> lineage) {\nsuper(DataType.LIST, ValueType.UNKNOWN);\n_data = data;\n_names = names;\n+ _lineage = lineage;\n_nCacheable = (int) data.stream().filter(\nd -> d instanceof CacheableData).count();\n}\npublic ListObject(ListObject that) {\nthis(new ArrayList<>(that._data), (that._names != null) ?\n- new ArrayList<>(that._names) : null);\n+ new ArrayList<>(that._names) : null, (that._lineage != null) ?\n+ new ArrayList<>(that._lineage) : null);\nif( that._dataState != null )\n_dataState = Arrays.copyOf(that._dataState, getLength());\n}\n@@ -96,6 +104,10 @@ public class ListObject extends Data {\nreturn _data;\n}\n+ public List<LineageItem> getLineageItems() {\n+ return _lineage;\n+ }\n+\npublic long getDataSize() {\nreturn _data.stream().filter(data -> data instanceof CacheableData)\n.mapToLong(data -> ((CacheableData<?>) data).getDataSize()).sum();\n@@ -109,9 +121,15 @@ public class ListObject extends Data {\nreturn _data.get(ix);\n}\n+ public LineageItem getLineageItem(int ix) {\n+ LineageItem li = _lineage != null ? _lineage.get(ix):null;\n+ return li;\n+ }\n+\npublic ListObject slice(int ix1, int ix2) {\nListObject ret = new ListObject(_data.subList(ix1, ix2 + 1),\n- (_names != null) ? _names.subList(ix1, ix2 + 1) : null);\n+ (_names != null) ? _names.subList(ix1, ix2 + 1) : null,\n+ (_lineage != null) ? _lineage.subList(ix1, ix2 + 1) : null);\nif( _dataState != null )\nret.setStatus(Arrays.copyOfRange(_dataState, ix2, ix2 + 1));\nreturn ret;\n@@ -135,9 +153,9 @@ public class ListObject extends Data {\n}\npublic ListObject copy() {\n- ListObject ret = isNamedList() ?\n- new ListObject(new ArrayList<>(getData()), new ArrayList<>(getNames())) :\n- new ListObject(new ArrayList<>(getData()));\n+ List<String> names = isNamedList() ? new ArrayList<>(getNames()) : null;\n+ List<LineageItem> LineageItems = getLineageItems() != null ? new ArrayList<>(getLineageItems()) : null;\n+ ListObject ret = new ListObject(new ArrayList<>(getData()), names, LineageItems);\nif( getStatus() != null )\nret.setStatus(Arrays.copyOf(getStatus(), getLength()));\nreturn ret;\n@@ -192,22 +210,29 @@ public class ListObject extends Data {\nreturn set(pos1, pos2, data);\n}\n- public ListObject add(Data dat) {\n- add(null, dat);\n+ public ListObject add(Data dat, LineageItem li) {\n+ add(null, dat, li);\nreturn this;\n}\n- public ListObject add(String name, Data dat) {\n+ public ListObject add(String name, Data dat, LineageItem li) {\nif( _names != null && name == null )\nthrow new DMLRuntimeException(\"Cannot add to a named list\");\n//otherwise append and ignore name\n_data.add(dat);\n+ if (_lineage == null && li!= null)\n+ _lineage = new ArrayList<>();\n+ if (li != null)\n+ _lineage.add(li);\nreturn this;\n}\npublic ListObject remove(int pos) {\n- ListObject ret = new ListObject(Arrays.asList(_data.get(pos)));\n+ ListObject ret = new ListObject(Arrays.asList(_data.get(pos)),\n+ null, _lineage != null?Arrays.asList(_lineage.get(pos)):null);\n_data.remove(pos);\n+ if (_lineage != null)\n+ _lineage.remove(pos);\nif( _names != null )\n_names.remove(pos);\nreturn ret;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ScalarBuiltinNaryCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/ScalarBuiltinNaryCPInstruction.java",
"diff": "@@ -28,6 +28,8 @@ import org.tugraz.sysds.api.DMLScript;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\n+import org.tugraz.sysds.runtime.lineage.LineageItem;\n+import org.tugraz.sysds.runtime.lineage.LineageTraceable;\nimport org.tugraz.sysds.runtime.matrix.operators.Operator;\n/**\n@@ -37,7 +39,7 @@ import org.tugraz.sysds.runtime.matrix.operators.Operator;\n* string.\n*\n*/\n-public class ScalarBuiltinNaryCPInstruction extends BuiltinNaryCPInstruction {\n+public class ScalarBuiltinNaryCPInstruction extends BuiltinNaryCPInstruction implements LineageTraceable {\nprotected ScalarBuiltinNaryCPInstruction(Operator op, String opcode, String istr, CPOperand output, CPOperand[] inputs) {\nsuper(op, opcode, istr, output, inputs);\n@@ -108,4 +110,10 @@ public class ScalarBuiltinNaryCPInstruction extends BuiltinNaryCPInstruction {\n}\n+ @Override\n+ public LineageItem[] getLineageItems(ExecutionContext ec) {\n+ return new LineageItem[]{new LineageItem(output.getName(),\n+ instString, getOpcode())};\n+ }\n+\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RewriteListTsmmCVTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RewriteListTsmmCVTest.java",
"diff": "@@ -26,6 +26,7 @@ import org.junit.Test;\nimport org.tugraz.sysds.common.Types.ExecMode;\nimport org.tugraz.sysds.hops.OptimizerUtils;\nimport org.tugraz.sysds.lops.LopProperties.ExecType;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixValue.CellIndex;\nimport org.tugraz.sysds.test.AutomatedTestBase;\nimport org.tugraz.sysds.test.TestConfiguration;\n@@ -62,15 +63,15 @@ public class RewriteListTsmmCVTest extends AutomatedTestBase\ntestListTsmmCV(TEST_NAME1, true, false, ExecType.SPARK);\n}\n-// @Test\n-// public void testListTsmmRewriteLineageCP() {\n-// testListTsmmCV(TEST_NAME1, true, true, ExecType.CP);\n-// }\n-//\n-// @Test\n-// public void testListTsmmRewriteLineageSP() {\n-// testListTsmmCV(TEST_NAME1, true, true, ExecType.SPARK);\n-// }\n+ @Test\n+ public void testListTsmmRewriteLineageCP() {\n+ testListTsmmCV(TEST_NAME1, true, true, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testListTsmmRewriteLineageSP() {\n+ testListTsmmCV(TEST_NAME1, true, true, ExecType.SPARK);\n+ }\nprivate void testListTsmmCV( String testname, boolean rewrites, boolean lineage, ExecType instType )\n{\n@@ -87,11 +88,10 @@ public class RewriteListTsmmCVTest extends AutomatedTestBase\nString HOME = SCRIPT_DIR + TEST_DIR;\nfullDMLScriptName = HOME + testname + \".dml\";\n- //TODO lineage list\n-// ReuseCacheType ltype = lineage ? ReuseCacheType.REUSE_FULL : ReuseCacheType.NONE;\n-// programArgs = new String[]{\"-explain\", \"-lineage\", ltype.name(), \"-stats\",\"-args\",\n-// String.valueOf(rows), String.valueOf(cols), output(\"S\") };\n-\n+ if (lineage)\n+ programArgs = new String[]{\"-explain\",\"recompile_runtime\", \"-lineage\", ReuseCacheType.REUSE_FULL.name().toLowerCase(),\n+ \"-stats\",\"-args\", String.valueOf(rows), String.valueOf(cols), output(\"S\") };\n+ else\nprogramArgs = new String[]{\"-explain\", \"-stats\",\"-args\",\nString.valueOf(rows), String.valueOf(cols), output(\"S\") };\n@@ -116,7 +116,7 @@ public class RewriteListTsmmCVTest extends AutomatedTestBase\nStatistics.getCPHeavyHitterCount(codes[1]));\nAssert.assertEquals( (lineage ? 7 : 7*6) + 1, //per fold\nStatistics.getCPHeavyHitterCount(codes[2]));\n- Assert.assertEquals( 7*5 + (instType==ExecType.CP?7*6:0), //for intermediates\n+ Assert.assertEquals( 7*5 + (instType==ExecType.CP?7*6:7), //for intermediates\nStatistics.getCPHeavyHitterCount(codes[3]));\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/misc/RewriteListTsmmCV.dml",
"new_path": "src/test/scripts/functions/misc/RewriteListTsmmCV.dml",
"diff": "@@ -38,7 +38,6 @@ crossV = function(Matrix[double] X, Matrix[double] y, double lamda, Integer k) r\ntrainy = rbind(tmpy);\nbeta = SimlinRegDS(trainX, trainy, lamda, ncol(X));\nbeta_list = append(beta_list, beta);\n- #FIXME: transpose is not getting picked\n}\nR = cbind(beta_list);\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-179] Lineage handling for lists during dynamic recompilation
Closes #75. |
49,738 | 14.12.2019 15:02:43 | -3,600 | 9bdd3583b07a4f13611db1c5b5123459e77b44cb | [MINOR] Fix missing lineage tracing spark nary builtin / write | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/api/DMLOptions.java",
"new_path": "src/main/java/org/tugraz/sysds/api/DMLOptions.java",
"diff": "@@ -124,6 +124,8 @@ public class DMLOptions {\ndmlOptions.linReuseType = ReuseCacheType.REUSE_PARTIAL;\nelse if (lineageType.equalsIgnoreCase(\"reuse_hybrid\"))\ndmlOptions.linReuseType = ReuseCacheType.REUSE_HYBRID;\n+ else if (lineageType.equalsIgnoreCase(\"none\"))\n+ dmlOptions.linReuseType = ReuseCacheType.NONE;\nelse\nthrow new org.apache.commons.cli.ParseException(\n\"Invalid argument specified for -lineage option: \" + lineageType);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/recompile/LiteralReplacement.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/recompile/LiteralReplacement.java",
"diff": "@@ -70,7 +70,7 @@ public class LiteralReplacement\nHop lit = null;\n//conditional apply of literal replacements\n- lit = (lit==null) ? replaceLiteralScalarRead(c, vars) : lit;\n+ lit = replaceLiteralScalarRead(c, vars);\nlit = (lit==null) ? replaceLiteralValueTypeCastScalarRead(c, vars) : lit;\nlit = (lit==null) ? replaceLiteralValueTypeCastLiteral(c, vars) : lit;\nif( !scalarsOnly ) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/spark/BuiltinNarySPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/spark/BuiltinNarySPInstruction.java",
"diff": "@@ -35,6 +35,9 @@ import org.tugraz.sysds.runtime.instructions.spark.functions.MapInputSignature;\nimport org.tugraz.sysds.runtime.instructions.spark.functions.MapJoinSignature;\nimport org.tugraz.sysds.runtime.instructions.spark.utils.RDDAggregateUtils;\nimport org.tugraz.sysds.runtime.instructions.spark.utils.SparkUtils;\n+import org.tugraz.sysds.runtime.lineage.LineageItem;\n+import org.tugraz.sysds.runtime.lineage.LineageItemUtils;\n+import org.tugraz.sysds.runtime.lineage.LineageTraceable;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixIndexes;\nimport org.tugraz.sysds.runtime.matrix.operators.SimpleOperator;\n@@ -45,7 +48,7 @@ import scala.Tuple2;\nimport java.util.List;\n-public class BuiltinNarySPInstruction extends SPInstruction\n+public class BuiltinNarySPInstruction extends SPInstruction implements LineageTraceable\n{\nprivate CPOperand[] inputs;\nprivate CPOperand output;\n@@ -195,4 +198,10 @@ public class BuiltinNarySPInstruction extends SPInstruction\nreturn MatrixBlock.naryOperations(_op, v1, _scalars, new MatrixBlock());\n}\n}\n+\n+ @Override\n+ public LineageItem[] getLineageItems(ExecutionContext ec) {\n+ return new LineageItem[]{new LineageItem(output.getName(), getOpcode(),\n+ LineageItemUtils.getLineage(ec, inputs))};\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/spark/WriteSPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/spark/WriteSPInstruction.java",
"diff": "package org.tugraz.sysds.runtime.instructions.spark;\n+import org.apache.commons.lang.ArrayUtils;\nimport org.apache.hadoop.io.LongWritable;\nimport org.apache.hadoop.mapred.SequenceFileOutputFormat;\nimport org.apache.spark.api.java.JavaPairRDD;\n@@ -39,6 +40,9 @@ import org.tugraz.sysds.runtime.instructions.spark.utils.FrameRDDConverterUtils.\nimport org.tugraz.sysds.runtime.instructions.spark.utils.RDDConverterUtils;\nimport org.tugraz.sysds.runtime.io.FileFormatProperties;\nimport org.tugraz.sysds.runtime.io.FileFormatPropertiesCSV;\n+import org.tugraz.sysds.runtime.lineage.LineageItem;\n+import org.tugraz.sysds.runtime.lineage.LineageItemUtils;\n+import org.tugraz.sysds.runtime.lineage.LineageTraceable;\nimport org.tugraz.sysds.runtime.matrix.data.FrameBlock;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixIndexes;\n@@ -50,7 +54,7 @@ import java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Random;\n-public class WriteSPInstruction extends SPInstruction {\n+public class WriteSPInstruction extends SPInstruction implements LineageTraceable {\nprivate CPOperand input1 = null;\nprivate CPOperand input2 = null;\nprivate CPOperand input3 = null;\n@@ -290,4 +294,12 @@ public class WriteSPInstruction extends SPInstruction {\nrdd.saveAsTextFile(fname);\n}\n}\n+\n+ @Override\n+ public LineageItem[] getLineageItems(ExecutionContext ec) {\n+ LineageItem[] ret = LineageItemUtils.getLineage(ec, input1, input2, input3, input4);\n+ if (formatProperties != null && formatProperties.getDescription() != null && !formatProperties.getDescription().isEmpty())\n+ ret = (LineageItem[])ArrayUtils.add(ret, new LineageItem(formatProperties.getDescription()));\n+ return new LineageItem[]{new LineageItem(input1.getName(), getOpcode(), ret)};\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RewriteListTsmmCVTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RewriteListTsmmCVTest.java",
"diff": "@@ -88,12 +88,10 @@ public class RewriteListTsmmCVTest extends AutomatedTestBase\nString HOME = SCRIPT_DIR + TEST_DIR;\nfullDMLScriptName = HOME + testname + \".dml\";\n- if (lineage)\n- programArgs = new String[]{\"-explain\",\"recompile_runtime\", \"-lineage\", ReuseCacheType.REUSE_FULL.name().toLowerCase(),\n+ //lineage tracing with and without reuse\n+ ReuseCacheType reuse = lineage ? ReuseCacheType.REUSE_FULL : ReuseCacheType.NONE;\n+ programArgs = new String[]{\"-explain\",\"recompile_runtime\", \"-lineage\", reuse.name().toLowerCase(),\n\"-stats\",\"-args\", String.valueOf(rows), String.valueOf(cols), output(\"S\") };\n- else\n- programArgs = new String[]{\"-explain\", \"-stats\",\"-args\",\n- String.valueOf(rows), String.valueOf(cols), output(\"S\") };\nfullRScriptName = HOME + testname + \".R\";\nrCmd = getRCmd(inputDir(), expectedDir());\n@@ -108,15 +106,17 @@ public class RewriteListTsmmCVTest extends AutomatedTestBase\nif( instType == ExecType.CP )\nAssert.assertEquals(0, Statistics.getNoOfExecutedSPInst());\nif( rewrites ) {\n+ boolean expectedReuse = lineage && instType == ExecType.CP;\nString[] codes = (instType==ExecType.CP) ?\nnew String[]{\"rbind\",\"tsmm\",\"ba+*\",\"+\"} :\nnew String[]{\"sp_append\",\"sp_tsmm\",\"sp_mapmm\",\"sp_+\"};\nAssert.assertTrue(!heavyHittersContainsString(codes[0]));\n- Assert.assertEquals( (lineage ? 7 : 7*6), //per fold\n+ Assert.assertEquals( (expectedReuse ? 7 : 7*6), //per fold\nStatistics.getCPHeavyHitterCount(codes[1]));\n- Assert.assertEquals( (lineage ? 7 : 7*6) + 1, //per fold\n+ Assert.assertEquals( (expectedReuse ? 7 : 7*6) + 1, //per fold\nStatistics.getCPHeavyHitterCount(codes[2]));\n- Assert.assertEquals( 7*5 + (instType==ExecType.CP?7*6:7), //for intermediates\n+ //for intermediates tsmm/ba+* + 7 diag (in spark sp_map+ vs sp_+)\n+ Assert.assertEquals( 7*5 + (instType==ExecType.CP?7*6:7),\nStatistics.getCPHeavyHitterCount(codes[3]));\n}\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix missing lineage tracing spark nary builtin / write |
49,738 | 14.12.2019 15:14:50 | -3,600 | 6b514d740bb8d09443fd244a02b0e325f0e4bc0f | [MINOR] Robustness lineage cache handling (large objects, mem frac)
This patch improves the robustness of the lineage cache by gracefully
ignoring large objects (instead of throwing exceptions) and using a
cache size of 5% relative to the max heap configuration. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "@@ -24,6 +24,7 @@ import org.tugraz.sysds.parser.Statement;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\n+import org.tugraz.sysds.runtime.controlprogram.parfor.stat.InfrastructureAnalyzer;\nimport org.tugraz.sysds.runtime.instructions.CPInstructionParser;\nimport org.tugraz.sysds.runtime.instructions.Instruction;\nimport org.tugraz.sysds.runtime.instructions.cp.BinaryMatrixMatrixCPInstruction;\n@@ -44,12 +45,18 @@ public class LineageCache {\nprivate static final Map<LineageItem, Entry> _cache = new HashMap<>();\nprivate static final Map<LineageItem, SpilledItem> _spillList = new HashMap<>();\nprivate static final HashSet<LineageItem> _removelist = new HashSet<>();\n- private static final long CACHELIMIT= (long)512*1024*1024; // 500MB\n+ private static final double CACHE_FRAC = 0.05; // 5% of JVM mem\n+ private static final long CACHE_LIMIT; //limit in bytes\nprivate static String outdir = null;\nprivate static long _cachesize = 0;\nprivate static Entry _head = null;\nprivate static Entry _end = null;\n+ static {\n+ long maxMem = InfrastructureAnalyzer.getLocalMaxMemory();\n+ CACHE_LIMIT = (long)(CACHE_FRAC * maxMem);\n+ }\n+\n//--------------------- CACHE LOGIC METHODS ----------------------\npublic static boolean reuse(Instruction inst, ExecutionContext ec) {\n@@ -117,6 +124,8 @@ public class LineageCache {\n// Make space by removing or spilling LRU entries.\nif( value != null ) {\n+ if( value.getInMemorySize() > CACHE_LIMIT )\n+ return; //not applicable\nif( !isBelowThreshold(value) )\nmakeSpace(value);\nupdateSize(value, true);\n@@ -183,16 +192,13 @@ public class LineageCache {\n//---------------- CACHE SPACE MANAGEMENT METHODS -----------------\nprivate static boolean isBelowThreshold(MatrixBlock value) {\n- //FIXME: we cannot throw such an exception here, instead need to gracefully ignore\n- if (value.getInMemorySize() > CACHELIMIT)\n- throw new RuntimeException(\"Single item larger than the size of lineage cache\");\n- return ((value.getInMemorySize() + _cachesize) <= CACHELIMIT);\n+ return ((value.getInMemorySize() + _cachesize) <= CACHE_LIMIT);\n}\nprivate static void makeSpace(MatrixBlock value) {\ndouble valSize = value.getInMemorySize();\n// cost based eviction\n- while ((valSize+_cachesize) > CACHELIMIT)\n+ while ((valSize+_cachesize) > CACHE_LIMIT)\n{\ndouble reduction = _cache.get(_end._key).getValue().getInMemorySize();\nif (_cache.get(_end._key)._compEst > getDiskSpillEstimate()\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Robustness lineage cache handling (large objects, mem frac)
This patch improves the robustness of the lineage cache by gracefully
ignoring large objects (instead of throwing exceptions) and using a
cache size of 5% relative to the max heap configuration. |
49,738 | 15.12.2019 16:24:48 | -3,600 | 5236e4dcd8d016dca4631555f26420d5c59c25f8 | [MINOR] Remove non-default systemds-config from conf directory | [
{
"change_type": "DELETE",
"old_path": "conf/SystemDS-config.xml",
"new_path": null,
"diff": "-<!--\n- ********************************************************************\n- *\n- * Copyright 2019 Graz University of Technology\n- *\n- * Licensed under the Apache License, Version 2.0 (the \"License\");\n- * you may not use this file except in compliance with the License.\n- * You may obtain a copy of the License at\n- *\n- * http://www.apache.org/licenses/LICENSE-2.0\n- *\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- *\n- ********************************************************************\n- -->\n-\n-\n-<root>\n- <!-- local fs tmp working directory-->\n- <sysds.localtmpdir>/tmp/systemds</sysds.localtmpdir>\n-\n- <!-- hdfs tmp working directory-->\n- <sysds.scratch>scratch_space</sysds.scratch>\n-\n- <!-- compiler optimization level, valid values: 0 | 1 | 2 | 3 | 4, default: 2 -->\n- <sysds.optlevel>2</sysds.optlevel>\n-\n- <!-- default block dim for binary block files -->\n- <sysds.defaultblocksize>1000</sysds.defaultblocksize>\n-\n- <!-- enables multi-threaded operations in singlenode control program -->\n- <sysds.cp.parallel.ops>true</sysds.cp.parallel.ops>\n-\n- <!-- enables multi-threaded read/write in singlenode control program -->\n- <sysds.cp.parallel.io>true</sysds.cp.parallel.io>\n-\n- <!-- enables compressed linear algebra, experimental feature -->\n- <sysds.compressed.linalg>auto</sysds.compressed.linalg>\n-\n- <!-- enables operator fusion via code generation, experimental feature -->\n- <sysds.codegen.enabled>true</sysds.codegen.enabled>\n-\n- <!-- set the codegen java compiler (auto, janino, javac) -->\n- <sysds.codegen.compiler>auto</sysds.codegen.compiler>\n-\n- <!-- set the codegen optimizer (fuse_all, fuse_no_redundancy, fuse_cost_based_v2) -->\n- <sysds.codegen.compiler>fuse_cost_based_v2</sysds.codegen.compiler>\n-\n- <!-- if codegen.enabled, enables source code caching of fused operators -->\n- <sysds.codegen.plancache>true</sysds.codegen.plancache>\n-\n- <!-- if codegen.enabled, compile literals as constants: 1..heuristic, 2..always -->\n- <sysds.codegen.literals>1</sysds.codegen.literals>\n-\n- <!-- enables native blas for matrix multiplication and convolution, experimental feature (options: auto, mkl, openblas, none) -->\n- <sysds.native.blas>none</sysds.native.blas>\n-\n- <!-- custom directory where BLAS libraries are available, experimental feature (options: absolute directory path or none). If set to none, we use standard LD_LIBRARY_PATH. -->\n- <sysds.native.blas.directory>none</sysds.native.blas.directory>\n-\n- <!-- sets the GPUs to use per process, -1 for all GPUs, a specific GPU number (5), a range (eg: 0-2) or a comma separated list (eg: 0,2,4)-->\n- <sysds.gpu.availableGPUs>-1</sysds.gpu.availableGPUs>\n-\n- <!-- whether to synchronize GPUs after every GPU instruction -->\n- <sysds.gpu.sync.postProcess>false</sysds.gpu.sync.postProcess>\n-\n- <!-- whether to perform eager CUDA free on rmvar instruction -->\n- <sysds.gpu.eager.cudaFree>false</sysds.gpu.eager.cudaFree>\n-\n- <!-- Developer flag used to debug GPU memory leaks. This has huge performance overhead and should be only turned on for debugging purposes. -->\n- <sysds.gpu.print.memoryInfo>false</sysds.gpu.print.memoryInfo>\n-\n- <!-- the floating point precision. supported values are double, single -->\n- <sysds.floating.point.precision>double</sysds.floating.point.precision>\n-\n- <!-- the eviction policy for the GPU bufferpool. Supported values are lru, mru, lfu, min_evict, align_memory -->\n- <sysds.gpu.eviction.policy>min_evict</sysds.gpu.eviction.policy>\n-\n- <!-- maximum wrap length for instruction and miscellaneous timer column of statistics -->\n- <sysds.stats.maxWrapLength>30</sysds.stats.maxWrapLength>\n-\n- <!-- Advanced optimization: fraction of driver memory to use for GPU shadow buffer. This optimization is ignored for double precision.\n- By default, it is disabled (hence set to 0.0). If you intend to train network larger than GPU memory size, consider using single precision and setting this to 0.1 -->\n- <sysds.gpu.eviction.shadow.bufferSize>0.0</sysds.gpu.eviction.shadow.bufferSize>\n-\n- <!-- Fraction of available GPU memory to use. This is similar to TensorFlow's per_process_gpu_memory_fraction configuration property. (default: 0.9) -->\n- <sysds.gpu.memory.util.factor>0.9</sysds.gpu.memory.util.factor>\n-\n- <!-- Allocator to use to allocate GPU device memory. Supported values are cuda, unified_memory (default: cuda) -->\n- <sysds.gpu.memory.allocator>cuda</sysds.gpu.memory.allocator>\n-</root>\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Remove non-default systemds-config from conf directory |
49,720 | 18.12.2019 13:24:52 | -3,600 | b825b3126e873d12feac4d49ecc39aaac72c7911 | Fix cTable error on writing at (0,1) | [
{
"change_type": "MODIFY",
"old_path": "scripts/builtin/mice_lm.dml",
"new_path": "scripts/builtin/mice_lm.dml",
"diff": "@@ -62,20 +62,19 @@ m_mice_lm = function(Matrix[Double] X, Integer iter = 3, Integer complete = 3)\n{\nMask_Filled = Mask;\n- parfor(i in 1:col)\n+ for(i in 1:col)\n{\n# construct column selector\nsel = cbind(matrix(1,1,i-1), as.matrix(0), matrix(1,1,col-i));\n# prepare train data set X and Y\nslice1 = removeEmpty(target = X2, margin = \"rows\", select = inverseMask[,i])\n- while(FALSE){}\ntrain_X = removeEmpty(target = slice1, margin = \"cols\", select = sel);\ntrain_Y = slice1[,i]\n+ while(FALSE){}\n# prepare score data set X and Y for imputing Y\nslice2 = removeEmpty(target = X2, margin = \"rows\", select = Mask[,i])\n- while(FALSE){}\ntest_X = removeEmpty(target = slice2, margin = \"cols\", select = sel);\ntest_Y = slice2[,i]\n@@ -87,6 +86,8 @@ m_mice_lm = function(Matrix[Double] X, Integer iter = 3, Integer complete = 3)\n# imputing missing column values (assumes Mask_Filled being 0/1-matrix)\nR = removeEmpty(target=Mask_Filled[,i] * seq(1,n), margin=\"rows\");\n+ #TODO modify removeEmpty to return zero row and n columns\n+ if(!(nrow(R) == 1 & as.scalar(R[1,1] == 0)))\nMask_Filled[,i] = table(R, 1, pred, n, 1);\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-189] Fix cTable error on writing at (0,1) |
49,738 | 19.12.2019 21:36:24 | -3,600 | d7aa404037a60d85dd23314c198a5cb43c36aa91 | Fix corrupted xml license header main config template
This patch fixes invalid '--' characters in the license header of our
main systemds-config template, which was introduced with
commit | [
{
"change_type": "MODIFY",
"old_path": "conf/SystemDS-config.xml.template",
"new_path": "conf/SystemDS-config.xml.template",
"diff": "-<!---------------------------------------------------------------\n+<!--\n+ * Modifications Copyright 2019 Graz University of Technology\n*\n- * Copyright 2019 Graz University of Technology\n- *\n- * Licensed under the Apache License, Version 2.0 (the \"License\");\n- * you may not use this file except in compliance with the License.\n- * You may obtain a copy of the License at\n+ * Licensed to the Apache Software Foundation (ASF) under one\n+ * or more contributor license agreements. See the NOTICE file\n+ * distributed with this work for additional information\n+ * regarding copyright ownership. The ASF licenses this file\n+ * to you under the Apache License, Version 2.0 (the\n+ * \"License\"); you may not use this file except in compliance\n+ * with the License. You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n- * Unless required by applicable law or agreed to in writing, software\n- * distributed under the License is distributed on an \"AS IS\" BASIS,\n- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n- * See the License for the specific language governing permissions and\n- * limitations under the License.\n- *\n- * --------------------------------------------------------------->\n-\n+ * Unless required by applicable law or agreed to in writing,\n+ * software distributed under the License is distributed on an\n+ * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+ * KIND, either express or implied. See the License for the\n+ * specific language governing permissions and limitations\n+ * under the License.\n+-->\n<root>\n<!-- local fs tmp working directory-->\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/config/SystemDS-config.xml",
"new_path": "src/test/config/SystemDS-config.xml",
"diff": "<!--\n- ********************************************************************\n- *\n* Copyright 2019 Graz University of Technology\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n- *\n- ********************************************************************\n-->\n<root>\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-31] Fix corrupted xml license header main config template
This patch fixes invalid '--' characters in the license header of our
main systemds-config template, which was introduced with
commit ceaa6ea664589104bb4e5fbee829bbcafac8458d. |
49,720 | 22.12.2019 22:48:27 | -3,600 | e3daa283d655342e3d119d3c20a7c62d19474912 | [Minor] Fix function description | [
{
"change_type": "MODIFY",
"old_path": "scripts/builtin/mice_lm.dml",
"new_path": "scripts/builtin/mice_lm.dml",
"diff": "# 1. The data is continous/numerical\n# 2. The missing values are denoted by zeros\n-# Builtin function Implements binary-class SVM with squared slack variables\n+# Builtin function Implements Multiple Imputations using Chained Equations for continous/numerical data\n#\n# INPUT PARAMETERS:\n# ---------------------------------------------------------------------------------------------\n"
}
] | Java | Apache License 2.0 | apache/systemds | [Minor] Fix function description |
49,689 | 07.01.2020 00:49:31 | -3,600 | 0f3cbe827f572021df8e4d09676294853509efd6 | Lineage caching transpose operation.
This patch includes changes to save r' results into lineage cache | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "@@ -186,7 +186,8 @@ public class LineageCache {\n|| (inst.getOpcode().equalsIgnoreCase(\"*\") &&\ninst instanceof BinaryMatrixMatrixCPInstruction) //TODO support scalar\n|| inst.getOpcode().equalsIgnoreCase(\"rightIndex\")\n- || inst.getOpcode().equalsIgnoreCase(\"groupedagg\");\n+ || inst.getOpcode().equalsIgnoreCase(\"groupedagg\")\n+ || inst.getOpcode().equalsIgnoreCase(\"r'\");\n}\n//---------------- CACHE SPACE MANAGEMENT METHODS -----------------\n@@ -324,6 +325,18 @@ public class LineageCache {\nbreak;\n}\n+ case Reorg: //r'\n+ {\n+ MatrixObject mo = ec.getMatrixObject(((ComputationCPInstruction)inst).input1);\n+ long r = mo.getNumRows();\n+ long c = mo.getNumColumns();\n+ long nnz = mo.getNnz();\n+ double s = OptimizerUtils.getSparsity(r, c, nnz);\n+ boolean sparse = MatrixBlock.evalSparseFormatInMemory(r, c, nnz);\n+ nflops = sparse ? r*c*s : r*c;\n+ break;\n+ }\n+\ndefault:\nthrow new DMLRuntimeException(\"Lineage Cache: unsupported instruction: \"+inst.getOpcode());\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | Lineage caching transpose operation.
This patch includes changes to save r' results into lineage cache |
49,719 | 16.01.2020 15:57:42 | 28,800 | cac53a97d087541c80c0aa9fdc25b7c8b267b25e | [MINOR] Upgrade log4j from 1.2.15 to 2.13.0
Official support for 1.2.x ended in 2015. And 1.2.15 has public
vulnerabilities. Hence, we want to upgrade. | [
{
"change_type": "MODIFY",
"old_path": "pom.xml",
"new_path": "pom.xml",
"diff": "<version>3.4.1</version>\n</dependency>\n- <dependency>\n- <groupId>log4j</groupId>\n- <artifactId>log4j</artifactId>\n- <version>1.2.15</version>\n- <exclusions>\n- <exclusion>\n- <groupId>com.sun.jmx</groupId>\n- <artifactId>jmxri</artifactId>\n- </exclusion>\n- <exclusion>\n- <groupId>com.sun.jdmk</groupId>\n- <artifactId>jmxtools</artifactId>\n- </exclusion>\n- <exclusion>\n- <groupId>javax.jms</groupId>\n- <artifactId>jms</artifactId>\n- </exclusion>\n- </exclusions>\n- </dependency>\n<dependency>\n<groupId>org.apache.wink</groupId>\n<version>1.9.5</version>\n<scope>test</scope>\n</dependency>\n+ <dependency>\n+ <groupId>org.apache.logging.log4j</groupId>\n+ <artifactId>log4j-api</artifactId>\n+ <version>2.13.0</version>\n+ </dependency>\n+ <dependency>\n+ <groupId>org.apache.logging.log4j</groupId>\n+ <artifactId>log4j-core</artifactId>\n+ <version>2.13.0</version>\n+ </dependency>\n</dependencies>\n</project>\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Upgrade log4j from 1.2.15 to 2.13.0
Official support for 1.2.x ended in 2015. And 1.2.15 has public
vulnerabilities. Hence, we want to upgrade. |
49,738 | 18.01.2020 17:00:54 | -3,600 | 08679376066c62fd2f41b783d4a4384d9d5abb38 | Fix travis CI integration (enabled ~1000 tests) | [
{
"change_type": "MODIFY",
"old_path": "pom.xml",
"new_path": "pom.xml",
"diff": "</plugin>\n- <!-- Currently, all tests are integration tests. -->\n- <plugin>\n+ <plugin> <!-- unit tests -->\n<groupId>org.apache.maven.plugins</groupId>\n<artifactId>maven-surefire-plugin</artifactId>\n<version>2.18</version><!--$NO-MVN-MAN-VER$ -->\n<configuration>\n-\n- <!-- STDERR/STDOUT to individual .txt files instead of console -->\n- <redirectTestOutputToFile>true</redirectTestOutputToFile>\n-\n<includes>\n<include>**/component/*.java</include>\n-\n</includes>\n-\n<excludes>\n<exclude>**/functions/**.java</exclude>\n<exclude>**/applications/**.java</exclude>\n</excludes>\n-\n</configuration>\n</plugin>\n- <plugin>\n+ <plugin> <!-- integration tests -->\n<groupId>org.apache.maven.plugins</groupId>\n<artifactId>maven-failsafe-plugin</artifactId>\n</execution>\n</executions>\n<configuration>\n-\n+ <!-- STDERR/STDOUT to individual .txt files instead of console -->\n<redirectTestOutputToFile>true</redirectTestOutputToFile>\n-\n<includes>\n- <include>**/component/*.java</include>\n-\n+ <include>**/component/*/*.java</include>\n+ <include>**/functions/jmlc/*.java</include>\n+ <include>**/functions/lineage/*.java</include>\n</includes>\n-\n<excludes>\n<exclude>**/functions/**.java</exclude>\n<exclude>**/applications/**.java</exclude>\n</excludes>\n-\n</configuration>\n</plugin>\n</build>\n</profile>\n- <!-- profile to enable running tests on the GPU -->\n- <profile>\n- <id>gpuTests</id>\n- <properties>\n- <gpuTestsPath>**/integration/gpu/**/*Suite.java</gpuTestsPath>\n- </properties>\n- </profile>\n-\n<profile>\n<!-- Can be used to ignore doclint javadoc issues -->\n<id>ignore-doclint</id>\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-15] Fix travis CI integration (enabled ~1000 tests) |
49,738 | 18.01.2020 17:12:18 | -3,600 | abd083096f65152c6d559553ea6834c3a6b8b1d2 | Fix travis CI integration (install R incl packages) | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -23,11 +23,11 @@ jdk:\n- openjdk8\naddons:\n-# apt:\n-# sources:\n-# - r-packages-trusty\n-# packages:\n-# - r-base-dev\n+ apt:\n+ sources:\n+ - r-packages-trusty\n+ packages:\n+ - r-base-dev\ncache:\napt: true\n@@ -38,7 +38,7 @@ cache:\n# - /usr/local/lib/R/site-library\ninstall:\n-# - sudo Rscript ./src/test/scripts/installDependencies.R\n+ - sudo Rscript ./src/test/scripts/installDependencies.R\nbefore_script:\n# this is not needed anymore since adding authentication object in code for running hadoop/spark local\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -9,7 +9,7 @@ SYSTEMDS-10 Compiler Rework / Misc\n* 12 Remove unnecessary HOP/LOP indirections\n* 13 Refactoring test cases into component/integration OK\n* 14 Complete removal of external functions from all scripts\n- * 15 Travis integration w/ subset of tests\n+ * 15 Travis integration w/ subset of tests OK\n* 16 Remove instruction patching\n* 17 Refactoring of program block hierarchy OK\n* 18 Improve API for new dml-bodied builtin functions OK\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-15] Fix travis CI integration (install R incl packages) |
49,738 | 18.01.2020 17:25:39 | -3,600 | b46dcf046e2da81b1942255d5445c5e8b76110bb | Fix travis CI integration (restricted to component tests) | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -23,11 +23,11 @@ jdk:\n- openjdk8\naddons:\n- apt:\n- sources:\n- - r-packages-trusty\n- packages:\n- - r-base-dev\n+# apt:\n+# sources:\n+# - r-packages-trusty\n+# packages:\n+# - r-base-dev\ncache:\napt: true\n@@ -38,7 +38,7 @@ cache:\n# - /usr/local/lib/R/site-library\ninstall:\n- - sudo Rscript ./src/test/scripts/installDependencies.R\n+# - sudo Rscript ./src/test/scripts/installDependencies.R\nbefore_script:\n# this is not needed anymore since adding authentication object in code for running hadoop/spark local\n"
},
{
"change_type": "MODIFY",
"old_path": "pom.xml",
"new_path": "pom.xml",
"diff": "<redirectTestOutputToFile>true</redirectTestOutputToFile>\n<includes>\n<include>**/component/*/*.java</include>\n- <include>**/functions/jmlc/*.java</include>\n- <include>**/functions/lineage/*.java</include>\n</includes>\n<excludes>\n<exclude>**/functions/**.java</exclude>\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-15] Fix travis CI integration (restricted to component tests) |
49,738 | 20.01.2020 10:27:23 | -3,600 | 1a5cd082c9e019a86c224a5fba30754b04663eec | [MINOR] Fix missing support for INT32 handling in frame types | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/util/UtilFunctions.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/util/UtilFunctions.java",
"diff": "@@ -459,6 +459,7 @@ public class UtilFunctions\nswitch( vt ) {\ncase STRING: return in;\ncase BOOLEAN: return Boolean.parseBoolean(in);\n+ case INT32: return Integer.parseInt(in);\ncase INT64: return Long.parseLong(in);\ncase FP64: return Double.parseDouble(in);\ndefault: throw new RuntimeException(\"Unsupported value type: \"+vt);\n@@ -499,6 +500,8 @@ public class UtilFunctions\nreturn null;\nelse if(in instanceof Long && ((Long)in).longValue() == 0)\nreturn null;\n+ else if(in instanceof Long && ((Integer)in).intValue() == 0)\n+ return null;\nelse if(in instanceof Boolean && ((Boolean)in).booleanValue() == false)\nreturn null;\nelse if(in instanceof String && ((String)in).trim().length() == 0)\n@@ -513,6 +516,7 @@ public class UtilFunctions\npublic static Object objectToObject(ValueType vt, Object in) {\nif( in instanceof Double && vt == ValueType.FP64\n|| in instanceof Long && vt == ValueType.INT64\n+ || in instanceof Integer && vt == ValueType.INT32\n|| in instanceof Boolean && vt == ValueType.BOOLEAN\n|| in instanceof String && vt == ValueType.STRING )\nreturn in; //quick path to avoid double parsing\n@@ -537,6 +541,7 @@ public class UtilFunctions\ncase STRING: return ((String)in1).compareTo((String)in2);\ncase BOOLEAN: return ((Boolean)in1).compareTo((Boolean)in2);\ncase INT64: return ((Long)in1).compareTo((Long)in2);\n+ case INT32: return ((Integer)in1).compareTo((Integer)in2);\ncase FP64: return ((Double)in1).compareTo((Double)in2);\ndefault: throw new RuntimeException(\"Unsupported value type: \"+vt);\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix missing support for INT32 handling in frame types |
49,720 | 22.01.2020 10:36:07 | -3,600 | 7c1f86992d93db82827e49193f49605cbe735741 | Minor Fix in for loop iteration | [
{
"change_type": "MODIFY",
"old_path": "scripts/builtin/mice_lm.dml",
"new_path": "scripts/builtin/mice_lm.dml",
"diff": "@@ -102,7 +102,7 @@ m_mice_lm = function(Matrix[Double] X, Integer iter = 3, Integer complete = 3)\n# aggregating the results\nAgg_Matrix = Mask_Result[index:row, ]\n- for(d in 1:(iter-1))\n+ for(d in seq(1, (iter-1), 1))\nAgg_Matrix = Agg_Matrix + Mask_Result[(((d-1)*n)+1):(n*d),]\nAgg_Matrix =(Agg_Matrix/iter)\n"
}
] | Java | Apache License 2.0 | apache/systemds | Minor Fix in for loop iteration |
49,720 | 22.01.2020 13:58:21 | -3,600 | e1ec0b0a8daf0677c15240f6cd4ff2011bf7db5b | [Minor Fix]: Fix DetectSchema sample size | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/FrameBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/FrameBlock.java",
"diff": "@@ -1781,11 +1781,7 @@ public class FrameBlock implements Writable, CacheBlock, Externalizable\nint rows = this.getNumRows();\nint cols = this.getNumColumns();\nString[] schemaInfo = new String[cols];\n-\n- int sample = (int) (sampleFraction * rows);\n- if (sample <= 0)\n- sample = rows;\n-\n+ int sample = (int)Math.min(Math.max(sampleFraction*rows, 1024), rows);\nfor (int i = 0; i < cols; i++) {\nValueType state = ValueType.UNKNOWN;\nArray obj = this.getColumn(i);\n"
}
] | Java | Apache License 2.0 | apache/systemds | [Minor Fix]: Fix DetectSchema sample size |
49,716 | 13.12.2019 19:01:32 | -3,600 | a753bcc42d1e834f794ab582de43ae9974dd5edc | Hidden Markov Models for Missing Value Imputation
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -171,5 +171,8 @@ SYSTEMDS-230 Lineage Integration\n* 231 Use lineage in buffer pool\n* 232 Lineage of generated operators\n+ SYSTEMDS-240 Student Projects\n+ * 241 Hidden Markov Models for Missing Value Imputation OK\n+\nOthers:\n* Break append instruction to cbind and rbind\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/hmm/HMM Training.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+# String generation using Hidden Markov Model\n+#Author: Afan Secic\n+\n+\n+import numpy as np\n+import pandas as pd\n+import random\n+from itertools import combinations\n+\n+def add2dict(dictionary, key, value):\n+ if key not in dictionary:\n+ dictionary[key] = []\n+ dictionary[key].append(value)\n+\n+def list2probabilitydict(given_list):\n+ probability_dict = {}\n+ given_list_length = len(given_list)\n+ for item in given_list:\n+ probability_dict[item] = probability_dict.get(item, 0) + 1\n+ for key, value in probability_dict.items():\n+ probability_dict[key] = value / given_list_length\n+ return probability_dict\n+\n+def sample_word(dictionary):\n+ p0 = np.random.random()\n+ cumulative = 0\n+ for key, value in dictionary.items():\n+ cumulative += value\n+ if p0 < cumulative:\n+ return key\n+\n+def generate_generic(sentence, no_of_words_to_generate = 1, previous_words = 3):\n+ sentence = sentence.split()\n+ if len(sentence) < previous_words:\n+ previous_words = len(sentence)\n+ if len(sentence) == 0:\n+ sentence.append(sample_word(initial_word))\n+ no_of_words_to_generate = no_of_words_to_generate - 1\n+ if len(sentence) == 1:\n+ word0 = sentence[0]\n+ if word0 in second_word.keys():\n+ word1 = sample_word(second_word[word0])\n+ else:\n+ word1 = np.random.choice(list(second_word[word0].keys()), 1, p = list(second_word[word0].values()))[0]\n+ sentence.append(word1)\n+ no_of_words_to_generate = no_of_words_to_generate - 1\n+\n+ while no_of_words_to_generate > 0:\n+ existing_keys = []\n+ previous_words_temp = previous_words\n+ found_keys = False\n+ while previous_words_temp != 0:\n+ words = list(combinations(sentence, previous_words_temp))\n+ previous_words_temp = previous_words_temp - 1\n+ existing_keys = list(set(words).intersection(transitions))\n+ if(len(existing_keys) != 0):\n+ found_keys = True\n+ break\n+ if found_keys:\n+ existing_keys = np.array(existing_keys)\n+ chosen_key = tuple(existing_keys[np.random.choice(len(existing_keys),1)][0])\n+ word = np.random.choice(list(transitions[chosen_key].keys()), 1, p = list(transitions[chosen_key].values()))[0]\n+ sentence.append(word)\n+ no_of_words_to_generate = no_of_words_to_generate - 1\n+ else:\n+ chosen_key = np.random.choice(list(transitions.keys()), 1)[0]\n+ word = np.random.choice(list(transitions[chosen_key].keys()), 1, p = list(transitions[chosen_key].values()))[0]\n+ sentence.append(word)\n+ no_of_words_to_generate = no_of_words_to_generate - 1\n+\n+ print(' '.join(sentence))\n+\n+def train_markov_model_generic(data, no_of_words):\n+ if no_of_words > 3:\n+ no_of_words = 3\n+ for line in data:\n+ line_length = len(line)\n+ first_token = line[0]\n+ initial_word[first_token] = initial_word.get(first_token, 0) + 1\n+ for i in range(1,line_length-1):\n+ for j in range(len(line[:i+1]) if len(line[:i+1]) < no_of_words + 1 else no_of_words + 1):\n+ word_combinations = combinations(line[:i+1], j)\n+ for combination in list(word_combinations):\n+ if len(combination) > 0:\n+ if i == 1:\n+ add2dict(second_word, combination if len(combination) > 1 else combination[0], line[i+1])\n+ else:\n+ add2dict(transitions, combination if len(combination) > 1 else combination[0], line[i+1])\n+\n+ initial_word_total = sum(initial_word.values())\n+ for key, value in initial_word.items():\n+ initial_word[key] = value / initial_word_total\n+\n+ for prev_word, next_word_list in second_word.items():\n+ second_word[prev_word] = list2probabilitydict(next_word_list)\n+\n+ for word_pair, next_word_list in transitions.items():\n+ transitions[word_pair] = list2probabilitydict(next_word_list)\n+\n+data = pd.read_csv('text_matrix.csv', dtype=type('string') ,header=None).values\n+data = np.array([row[~pd.isnull(row)] for row in data])\n+initial_word = {}\n+second_word = {}\n+transitions = {}\n+\n+#Second parameter is to determine how many previous words algorithm takes when learning\n+train_markov_model_generic(data, 5)\n+sentence = 'drought smith say'\n+generate_generic(sentence)\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/hmm/HMM.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+\n+#Author: Afan Secic\n+\n+from bs4 import BeautifulSoup,SoupStrainer\n+import nltk\n+from nltk.tokenize import sent_tokenize, word_tokenize\n+from nltk.stem import WordNetLemmatizer\n+from nltk.corpus import stopwords\n+import string\n+import numpy as np\n+import csv\n+import os\n+\n+def create_dataset(input_file_name, output_file_name):\n+ f = open(input_file_name, 'r')\n+ data= f.read()\n+ lemmatizer = WordNetLemmatizer()\n+ soup = BeautifulSoup(data,'html.parser')\n+ sentences = []\n+ text_matrix = []\n+ for item in soup.findAll('body'):\n+ sentences = sent_tokenize(item.text)\n+ for sentence in sentences:\n+ text_matrix.append([token for token in word_tokenize(sentence) if token.lower() not in stopwords.words('english') and token not in string.punctuation])\n+ for i in range(len(text_matrix)):\n+ for j in range(len(text_matrix[i])):\n+ text_matrix[i][j] = lemmatizer.lemmatize(text_matrix[i][j].lower(), pos='v')\n+ length = max(map(len, text_matrix))\n+ text_matrix=np.array([row + [None] * (length - len(row)) for row in text_matrix])\n+ try:\n+ with open(output_file_name) as csvFile:\n+ os.remove(output_file_name)\n+ csvFile = open(output_file_name, 'w')\n+ for row in text_matrix:\n+ writer = csv.writer(csvFile)\n+ writer.writerow(row)\n+ csvFile.close()\n+ except IOError:\n+ with open(output_file_name, 'w') as csvFile:\n+ for row in text_matrix:\n+ writer = csv.writer(csvFile)\n+ writer.writerow(row)\n+ csvFile.close()\n+\n+create_dataset('reut2-000.sgm', 'text_matrix.csv')\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-241] Hidden Markov Models for Missing Value Imputation
Closes #74 |
49,730 | 25.01.2020 15:02:54 | -3,600 | fc7ac56c6f2ccc70ca1b6a7db42b15dd27e4b1c2 | Initial slice finding implementation
Closes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/slicing/base/node.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+def logic_comparator(list_a, list_b, attributes):\n+ result = [int(x) == y for (x, y) in zip(list_a, list_b)]\n+ counter = 0\n+ for item in result:\n+ if item:\n+ counter = counter + 1\n+ return counter == attributes\n+\n+\n+class Node:\n+ name: \"\"\n+ attributes: []\n+ parents: []\n+ children: []\n+ size: int\n+ l2_error: float\n+ score: float\n+ e_max: float\n+ s_upper: int\n+ s_lower: int\n+ e_upper: float\n+ c_upper: float\n+ e_max_upper: float\n+\n+ def __init__(self, enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test):\n+ self.parents = []\n+ self.attributes = []\n+ self.size = 0\n+ self.score = 0\n+ self.enc = enc\n+ self.model = model\n+ self.complete_x = complete_x\n+ self.complete_y = complete_y\n+ self.f_l2 = f_l2\n+ self.x_size = x_size\n+ self.x_test = x_test\n+ self.y_test = y_test\n+ self.all_features = enc.get_feature_names()\n+\n+ def calc_c_upper(self, w):\n+ upper_score = w * (self.e_upper / self.s_lower) / (self.f_l2 / self.x_size) + (1 - w) * self.s_upper\n+ return float(upper_score)\n+\n+ def eval_c_upper(self, w):\n+ upper_score = w * (self.e_max_upper / (self.f_l2 / self.x_size)) + (1 - w) * self.s_upper\n+ return upper_score\n+\n+ def make_slice_mask(self):\n+ mask = []\n+ attributes_indexes = []\n+ for feature in self.attributes:\n+ attributes_indexes.append(feature[1])\n+ i = 0\n+ while i < len(list(self.all_features)):\n+ if i in attributes_indexes:\n+ mask.append(1)\n+ else:\n+ mask.append(-1)\n+ i = i + 1\n+ return mask\n+\n+ def make_slice(self):\n+ mask = self.make_slice_mask()\n+ subset = list(filter(lambda row: logic_comparator(list(row[1]), mask, len(self.attributes)) == True,\n+ self.complete_x))\n+ return subset\n+\n+ def calc_s_upper(self, cur_lvl):\n+ cur_min = self.parents[0].size\n+ for parent in self.parents:\n+ if cur_lvl == 1:\n+ cur_min = min(cur_min, parent.size)\n+ else:\n+ cur_min = min(cur_min, parent.s_upper)\n+ return cur_min\n+\n+ def calc_e_max_upper(self, cur_lvl):\n+ if cur_lvl == 1:\n+ e_max_min = self.parents[0].e_max\n+ else:\n+ e_max_min = self.parents[0].e_max_upper\n+ for parent in self.parents:\n+ if cur_lvl == 1:\n+ e_max_min = min(e_max_min, parent.e_max)\n+ else:\n+ e_max_min = min(e_max_min, parent.e_max_upper)\n+ return e_max_min\n+\n+ def calc_s_lower(self, cur_lvl):\n+ size_value = self.x_size\n+ for parent in self.parents:\n+ if cur_lvl == 1:\n+ size_value = size_value - (self.x_size - parent.size)\n+ else:\n+ size_value = size_value - (self.x_size - parent.s_lower)\n+ return max(size_value, 1)\n+\n+ def calc_e_upper(self):\n+ prev_e_uppers = []\n+ for parent in self.parents:\n+ prev_e_uppers.append(parent.e_upper)\n+ return float(min(prev_e_uppers))\n+\n+ def make_name(self):\n+ name = \"\"\n+ for attribute in self.attributes:\n+ name = name + str(attribute[0]) + \" && \"\n+ name = name[0: len(name) - 4]\n+ return name\n+\n+ def make_key(self, new_id):\n+ return new_id, self.name\n+\n+ def calc_l2_error(self, subset):\n+ fi_l2 = 0\n+ for i in range(0, len(subset)):\n+ fi_l2_sample = (self.model.predict(subset[i][1].reshape(1, -1)) - self.complete_y[subset[i][0]][1]) ** 2\n+ fi_l2 = fi_l2 + float(fi_l2_sample)\n+ if len(subset) > 0:\n+ fi_l2 = fi_l2 / len(subset)\n+ else:\n+ fi_l2 = 0\n+ return float(fi_l2)\n+\n+ def print_debug(self, topk, level):\n+ print(\"new node has been added: \" + self.make_name() + \"\\n\")\n+ if level >= 1:\n+ print(\"s_upper = \" + str(self.s_upper))\n+ print(\"s_lower = \" + str(self.s_lower))\n+ print(\"e_upper = \" + str(self.e_upper))\n+ print(\"c_upper = \" + str(self.c_upper))\n+ print(\"size = \" + str(self.size))\n+ print(\"score = \" + str(self.score))\n+ print(\"current topk min score = \" + str(topk.min_score))\n+ print(\"-------------------------------------------------------------------------------------\")\n+\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/slicing/base/slicer.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+from slicing.node import Node\n+from slicing.top_k import Topk\n+\n+\n+def opt_fun(fi, si, f, x_size, w):\n+ formula = w * (fi/f) + (1 - w) * (si/x_size)\n+ return float(formula)\n+\n+\n+def slice_name_nonsense(node_i, node_j, cur_lvl):\n+ commons = 0\n+ for attr1 in node_i.attributes:\n+ for attr2 in node_j.attributes:\n+ if attr1 == attr2:\n+ commons = commons + 1\n+ return commons != cur_lvl - 1\n+\n+\n+def union(lst1, lst2):\n+ final_list = sorted(set(list(lst1) + list(lst2)))\n+ return final_list\n+\n+\n+def check_for_slicing(node, w, topk, x_size, alpha):\n+ return node.s_upper >= x_size / alpha and node.eval_c_upper(w) >= topk.min_score\n+\n+\n+def check_for_excluding(node, topk, x_size, alpha, w):\n+ return node.s_upper >= x_size / alpha or node.eval_c_upper(w) >= topk.min_score\n+\n+\n+def process(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test, debug, alpha, k, w):\n+ # forming pairs of encoded features\n+ all_features = enc.get_feature_names()\n+ features_indexes = []\n+ counter = 0\n+ # First level slices are enumerated in a \"classic way\" (getting data and not analyzing bounds\n+ first_level = []\n+ levels = []\n+ all_nodes = {}\n+ top_k = Topk(k)\n+ for feature in all_features:\n+ features_indexes.append((feature, counter))\n+ new_node = Node(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test)\n+ new_node.parents = [(feature, counter)]\n+ new_node.attributes.append((feature, counter))\n+ new_node.name = new_node.make_name()\n+ new_id = len(all_nodes)\n+ new_node.key = new_node.make_key(new_id)\n+ all_nodes[new_node.key] = new_node\n+ subset = new_node.make_slice()\n+ new_node.size = len(subset)\n+ fi_l2 = 0\n+ tuple_errors = []\n+ for j in range(0, len(subset)):\n+ fi_l2_sample = (model.predict(subset[j][1].reshape(1, -1)) -\n+ complete_y[subset[j][0]][1]) ** 2\n+ tuple_errors.append(fi_l2_sample)\n+ fi_l2 = fi_l2 + fi_l2_sample\n+ new_node.e_max = max(tuple_errors)\n+ new_node.l2_error = fi_l2 / new_node.size\n+ new_node.score = opt_fun(new_node.l2_error, new_node.size, f_l2, x_size, w)\n+ new_node.e_upper = max(tuple_errors)\n+ new_node.c_upper = new_node.score\n+ first_level.append(new_node)\n+ counter = counter + 1\n+ levels.append(first_level)\n+ candidates = []\n+ for sliced in first_level:\n+ if sliced.score > 1 and sliced.size >= x_size / alpha:\n+ candidates.append(sliced)\n+ # cur_lvl - index of current level, correlates with number of slice forming features\n+ cur_lvl = 1 # currently filled level after first init iteration\n+ for candidate in candidates:\n+ top_k.add_new_top_slice(candidate)\n+ while cur_lvl < len(all_features):\n+ cur_lvl_nodes = []\n+ for node_i in range(len(levels[cur_lvl - 1]) - 1):\n+ for node_j in range(node_i + 1, len(levels[cur_lvl - 1]) - 1):\n+ flag = slice_name_nonsense(levels[cur_lvl - 1][node_i], levels[cur_lvl - 1][node_j], cur_lvl)\n+ if not flag:\n+ new_node = Node(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test)\n+ parents_set = set(new_node.parents)\n+ parents_set.add(levels[cur_lvl - 1][node_i])\n+ parents_set.add(levels[cur_lvl - 1][node_j])\n+ new_node.parents = list(parents_set)\n+ parent1_attr = levels[cur_lvl - 1][node_i].attributes\n+ parent2_attr = levels[cur_lvl - 1][node_j].attributes\n+ new_node_attr = union(parent1_attr, parent2_attr)\n+ new_node.attributes = new_node_attr\n+ new_node.name = new_node.make_name()\n+ new_id = len(all_nodes)\n+ new_node.key = new_node.make_key(new_id)\n+ if new_node.key in all_nodes:\n+ existing_item = all_nodes[new_node.key]\n+ parents_set = set(existing_item.parents)\n+ parents_set.add(node_i)\n+ parents_set.add(node_j)\n+ existing_item.parents = parents_set\n+ else:\n+ new_node.s_upper = new_node.calc_s_upper(cur_lvl)\n+ new_node.s_lower = new_node.calc_s_lower(cur_lvl)\n+ new_node.e_upper = new_node.calc_e_upper()\n+ new_node.e_max_upper = new_node.calc_e_max_upper(cur_lvl)\n+ new_node.c_upper = new_node.calc_c_upper(w)\n+ all_nodes[new_node.key] = new_node\n+ to_slice = check_for_slicing(new_node, w, top_k, x_size, alpha)\n+ # we make data slicing basing on score upper bound\n+ if to_slice:\n+ subset = new_node.make_slice()\n+ new_node.size = len(subset)\n+ new_node.l2_error = new_node.calc_l2_error(subset)\n+ new_node.score = opt_fun(new_node.l2_error, new_node.size, f_l2, x_size, w)\n+ # we decide to add node to current level nodes (in order to make new combinations\n+ # on the next one or not basing on its score value calculated according to actual size and\n+ # L2 error of a sliced subset\n+ if new_node.score >= top_k.min_score:\n+ cur_lvl_nodes.append(new_node)\n+ top_k.add_new_top_slice(new_node)\n+ if debug:\n+ new_node.print_debug(top_k, cur_lvl)\n+ cur_lvl = cur_lvl + 1\n+ levels.append(cur_lvl_nodes)\n+ top_k.print_topk()\n+\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/slicing/base/tests/salary_test_ex.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+import pandas as pd\n+from sklearn.linear_model import LinearRegression\n+from sklearn.model_selection import train_test_split\n+from sklearn.preprocessing import OneHotEncoder\n+\n+import slicing.slicer as slicer\n+\n+file_name = 'salary.csv'\n+dataset = pd.read_csv(file_name)\n+attributes_amount = len(dataset.values[0])\n+# for now working with regression datasets, assuming that target attribute is the last one\n+# currently non-categorical features are not supported and should be binned\n+y = dataset.iloc[:, attributes_amount - 1:attributes_amount].values\n+# starting with one not including id field\n+x = dataset.iloc[:, 1:attributes_amount - 1].values\n+# list of numerical columns\n+non_categorical = [4, 5]\n+for row in x:\n+ for attribute in non_categorical:\n+ # <attribute - 2> as we already excluded from x id column\n+ row[attribute - 2] = int(row[attribute - 2] / 5)\n+# hot encoding of categorical features\n+enc = OneHotEncoder(handle_unknown='ignore')\n+x = enc.fit_transform(x).toarray()\n+complete_x = []\n+complete_y = []\n+counter = 0\n+for item in x:\n+ complete_row = (counter, item)\n+ complete_x.append(complete_row)\n+ complete_y.append((counter, y[counter]))\n+ counter = counter + 1\n+x_size = counter\n+# train model on a whole dataset\n+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)\n+model = LinearRegression()\n+model.fit(x_train, y_train)\n+f_l2 = sum((model.predict(x_test) - y_test) ** 2)/x_size\n+# alpha is size significance coefficient\n+# verbose option is for returning debug info while creating slices and printing it\n+# k is number of top-slices we want\n+# w is a weight of error function significance (1 - w) is a size significance propagated into optimization function\n+slicer.process(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test, debug=True, alpha=4, k=10, w=0.5)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/slicing/base/top_k.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+class Topk:\n+ k: int\n+ min_score: float\n+ slices: []\n+\n+ def __init__(self, k):\n+ self.k = k\n+ self.slices = []\n+ self.min_score = 1\n+\n+ def top_k_min_score(self):\n+ self.slices.sort(key=lambda x: x.score, reverse=True)\n+ self.min_score = self.slices[len(self.slices) - 1].score\n+ return self.min_score\n+\n+ def add_new_top_slice(self, new_top_slice):\n+ self.min_score = new_top_slice.score\n+ if len(self.slices) < self.k:\n+ self.slices.append(new_top_slice)\n+ return self.top_k_min_score()\n+ else:\n+ self.slices[len(self.slices) - 1] = new_top_slice\n+ return self.top_k_min_score()\n+\n+ def print_topk(self):\n+ for candidate in self.slices:\n+ print(candidate.name + \": \" + \"score = \" + str(candidate.score) + \"; size = \" + str(candidate.size))\n+\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-251] Initial slice finding implementation
Closes #71. |
49,693 | 25.01.2020 15:16:36 | -3,600 | 2536e36e8c725a169a3278dff006871622cf9060 | Fix codegen outer template compilation
codegen fixes:
* opening condition on outer()
* merge condition to allow row vectors (fixes RMSE test case
(OuterProdTmplTest #10))
Closes | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/codegen/template/TemplateOuterProduct.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/codegen/template/TemplateOuterProduct.java",
"diff": "@@ -57,8 +57,10 @@ public class TemplateOuterProduct extends TemplateBase {\n@Override\npublic boolean open(Hop hop) {\n- //open on outer product like matrix mult (output larger than common dim)\n- return HopRewriteUtils.isOuterProductLikeMM(hop)\n+ //open on (1) outer product like matrix mult (output larger than common dim)\n+ //or (2) binary outer operation\n+ return (HopRewriteUtils.isOuterProductLikeMM(hop)\n+ || HopRewriteUtils.isOuterBinary(hop))\n&& hop.getDim1() > 256 && hop.getDim2() > 256;\n}\n@@ -67,8 +69,10 @@ public class TemplateOuterProduct extends TemplateBase {\nreturn !isClosed()\n&& ((hop instanceof UnaryOp && TemplateUtils.isOperationSupported(hop))\n|| (hop instanceof BinaryOp && TemplateUtils.isOperationSupported(hop)\n- && (TemplateUtils.isBinaryMatrixColVector(hop) || HopRewriteUtils.isBinaryMatrixScalarOperation(hop)\n- || (HopRewriteUtils.isBinaryMatrixMatrixOperation(hop)) ))\n+ && (TemplateUtils.isBinaryMatrixColVector(hop)\n+ || HopRewriteUtils.isBinaryMatrixScalarOperation(hop)\n+ || HopRewriteUtils.isBinaryMatrixMatrixOperation(hop)\n+ || TemplateUtils.isBinaryMatrixRowVector(hop)))\n|| (HopRewriteUtils.isTransposeOperation(hop) && input instanceof AggBinaryOp\n&& !HopRewriteUtils.isOuterProductLikeMM(input))\n|| (hop instanceof AggBinaryOp && !HopRewriteUtils.isOuterProductLikeMM(hop)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/HopRewriteUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/HopRewriteUtils.java",
"diff": "@@ -903,6 +903,10 @@ public class HopRewriteUtils\n&& hop.getInput().get(1).getDim1() < hop.getInput().get(1).getDim2();\n}\n+ public static boolean isOuterBinary( Hop hop ) {\n+ return hop instanceof BinaryOp && ((BinaryOp) hop).isOuter();\n+ }\n+\npublic static boolean isValidOuterBinaryOp( OpOp2 op ) {\nString opcode = Hop.getBinaryOpCode(op);\nreturn (Hop.getOpOp2ForOuterVectorOperation(opcode) == op);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/codegen/rmseDist.dml",
"new_path": "src/test/scripts/functions/codegen/rmseDist.dml",
"diff": "#-------------------------------------------------------------\n#\n+# Modifications Copyright 2019 Graz University of Technology\n+#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n@@ -26,13 +28,7 @@ X[1:3500,] = matrix(0,3500,2000);\nwhile(FALSE){}\n-#TODO + rowSums(U^2) + colSums(V^2)\n-# requires broadcasting support in outer\n-\n-T1 = rowSums(U^2)%*%matrix(1,1,ncol(V));\n-T2 = matrix(1,nrow(U),1)%*%colSums(V^2)\n-\n-D = sqrt(-2 * U %*% V + T1 + T2);\n+D = sqrt(-2 * U %*% V + rowSums(U^2) + colSums(V^2));\nS = as.matrix(sum(rowSums((X != 0) * (X - D))^2));\nwrite(S,$1)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-203] Fix codegen outer template compilation
codegen fixes:
* opening condition on outer()
* merge condition to allow row vectors (fixes RMSE test case
(OuterProdTmplTest #10))
Closes #77. |
49,720 | 25.01.2020 16:19:18 | -3,600 | 0e549de1ae0c6621d99d728fe725b255ab916ef4 | New intersect builtin function (set intersection)
Closes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/builtin/intersect.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#\n+#-------------------------------------------------------------\n+\n+# Implements set intersection for numeric data\n+\n+\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Double --- matrix X, set A\n+# Y Double --- matrix Y, set B\n+# ---------------------------------------------------------------------------------------------\n+\n+# Output(s)\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# R Double --- intersection matrix, set of intersecting items\n+\n+m_intersect = function(Matrix[Double] X, Matrix[Double] Y)\n+ return(Matrix[Double] R)\n+{\n+ # compute indicator vector of intersection output\n+ X = (table(X, 1) != 0)\n+ Y = (table(Y, 1) != 0)\n+ n = min(nrow(X), nrow(Y))\n+ I = X[1:n,] * Y[1:n,]\n+\n+ # reconstruct integer values and create output\n+ Iv = I * seq(1,n)\n+ R = removeEmpty(target=Iv, margin=\"rows\", select=I)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"diff": "@@ -89,6 +89,7 @@ public enum Builtins {\nIMG_BRIGHTNESS(\"img_brightness\", true),\nIMG_CROP(\"img_crop\", true),\nINTERQUANTILE(\"interQuantile\", false),\n+ INTERSECT(\"intersect\", true),\nINVERSE(\"inv\", \"inverse\", false),\nIQM(\"interQuartileMean\", false),\nKMEANS(\"kmeans\", true),\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinIntersectionTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.builtin;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.lops.LopProperties;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+import java.util.Arrays;\n+import java.util.HashMap;\n+\n+public class BuiltinIntersectionTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"intersection\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinIntersectionTest.class.getSimpleName() + \"/\";\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{\"C\"}));\n+ }\n+\n+ @Test\n+ public void testIntersect1CP() {\n+ double[][] X = {{12},{22},{13},{4},{6},{7},{8},{9}, {12}, {12}};\n+ double[][] Y = {{1},{2},{11},{12},{13}, {18},{20},{21},{12}};\n+ X = TestUtils.round(X);\n+ Y = TestUtils.round(Y);\n+ runIntersectTest(X, Y, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testIntersect1Spark() {\n+ double[][] X = {{12},{22},{13},{4},{6},{7},{8},{9}, {12}, {12}};\n+ double[][] Y = {{1},{2},{11},{12},{13}, {18},{20},{21},{12}};\n+ X = TestUtils.round(X);\n+ Y = TestUtils.round(Y);\n+ runIntersectTest(X, Y, LopProperties.ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testIntersect2CP() {\n+ double[][] X = new double[50][1];\n+ double[][] Y = new double[50][1];\n+ for(int i =0, j=2; i<50; i++, j+=4)\n+ X[i][0] = j;\n+ for(int i =0, j=2; i<50; i++, j+=2)\n+ Y[i][0] = j;\n+ runIntersectTest(X, Y, LopProperties.ExecType.CP);\n+ HashMap<MatrixValue.CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"C\");\n+ Object[] out = dmlfile.values().toArray();\n+ Arrays.sort(out);\n+ for(int i = 0; i< out.length; i++)\n+ Assert.assertEquals(out[i], Double.valueOf(X[i][0]));\n+ }\n+\n+ @Test\n+ public void testIntersect2Spark() {\n+ double[][] X = new double[50][1];\n+ double[][] Y = new double[50][1];\n+ for(int i =0, j=2; i<50; i++, j+=4)\n+ X[i][0] = j;\n+ for(int i =0, j=2; i<50; i++, j+=2)\n+ Y[i][0] = j;\n+ runIntersectTest(X, Y, LopProperties.ExecType.SPARK);\n+ HashMap<MatrixValue.CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"C\");\n+ Object[] out = dmlfile.values().toArray();\n+ Arrays.sort(out);\n+ for(int i = 0; i< out.length; i++)\n+ Assert.assertEquals(out[i], Double.valueOf(X[i][0]));\n+ }\n+\n+\n+\n+ private void runIntersectTest(double X[][], double Y[][], LopProperties.ExecType instType)\n+ {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+ //TODO compare with R instead of custom output comparison\n+\n+ try\n+ {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{ \"-args\", input(\"X\"), input(\"Y\"), output(\"C\"), output(\"X\")};\n+\n+ //generate actual datasets\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+ writeInputMatrixWithMTD(\"Y\", Y, true);\n+\n+ runTest(true, false, null, -1);\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/builtin/intersection.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#\n+#-------------------------------------------------------------\n+\n+A = read($1)\n+B = read($2)\n+[set] = intersect(X = A, Y = B);\n+write(set, $3);\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-196] New intersect builtin function (set intersection)
Closes #85. |
49,738 | 25.01.2020 18:22:52 | -3,600 | fa897a13352319a48744cea3bf326af6f2043bcd | New rewrite for eliminating unnecessary rmEmpty ops
This patch adds a new rewrite that eliminates unneccessary removeEmpty
operations in expressions like nrow(removeEmpty(A)), which can be
obtained via sum(A!=0) and thus, nnz(A). This occurs for example, in the
new intersect function where nrow is used for discovering robust
inclusion dependencies. | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -146,11 +146,14 @@ SYSTEMDS-190 New Builtin Functions III\n* 191 Builtin function multi logreg OK\n* 192 Extended cmdline interface -b for calling builtin functions\n* 193 New outlierBySds builtin function (delete row/cell)\n- * 194 New outlierByIQR builtin function (delte row/cell)\n+ * 194 New outlierByIQR builtin function (delete row/cell)\n+ * 195 Builtin function mice for nominal features\n+ * 196 Builtin function intersect (set intersection)\nSYSTEMDS-200 Various Fixes\n* 201 Fix spark append instruction zero columns OK\n* 202 Fix rewrite split DAG multiple removeEmpty (pending op) OK\n+ * 203 Fix codegen outer compilation (MV operations)\nSYSTEMDS-210 Extended lists Operations\n* 211 Cbind and Rbind over lists of matrices OK\n@@ -171,8 +174,11 @@ SYSTEMDS-230 Lineage Integration\n* 231 Use lineage in buffer pool\n* 232 Lineage of generated operators\n- SYSTEMDS-240 Student Projects\n- * 241 Hidden Markov Models for Missing Value Imputation OK\n+SYSTEMDS-240 GPU Backend Improvements\n+ * 241 Dense GPU cumulative aggregates\n+\n+SYSTEMDS-250 Large-Scale Slice Finding\n+ * 251 Initial data slicing implementation Python\nOthers:\n* Break append instruction to cbind and rbind\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/HopRewriteUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/HopRewriteUtils.java",
"diff": "@@ -782,6 +782,11 @@ public class HopRewriteUtils\nreturn ternOp;\n}\n+ public static Hop createComputeNnz(Hop input) {\n+ //nnz = sum(A != 0) -> later rewritten to meta-data operation\n+ return createSum(createBinary(input, new LiteralOp(0), OpOp2.NOTEQUAL));\n+ }\n+\npublic static void setOutputParameters( Hop hop, long rlen, long clen, int blen, long nnz ) {\nhop.setDim1(rlen);\nhop.setDim2(clen);\n@@ -1129,6 +1134,12 @@ public class HopRewriteUtils\nreturn hop instanceof ParameterizedBuiltinOp && ((ParameterizedBuiltinOp) hop).getOp().equals(type);\n}\n+ public static boolean isRemoveEmpty(Hop hop, boolean rows) {\n+ return isParameterBuiltinOp(hop, ParamBuiltinOp.RMEMPTY)\n+ && HopRewriteUtils.isLiteralOfValue(\n+ ((ParameterizedBuiltinOp)hop).getParameterHop(\"margin\"), rows?\"rows\":\"cols\");\n+ }\n+\npublic static boolean isNary(Hop hop, OpOpN type) {\nreturn hop instanceof NaryOp && ((NaryOp)hop).getOp()==type;\n}\n@@ -1147,17 +1158,11 @@ public class HopRewriteUtils\n&& ArrayUtils.contains(types, ((DnnOp) hop).getOp()));\n}\n- public static boolean isNonZeroIndicator(Hop pred, Hop hop )\n- {\n- if( pred instanceof BinaryOp && ((BinaryOp)pred).getOp()==OpOp2.NOTEQUAL\n+ public static boolean isNonZeroIndicator(Hop pred, Hop hop ) {\n+ return ( pred instanceof BinaryOp && ((BinaryOp)pred).getOp()==OpOp2.NOTEQUAL\n&& pred.getInput().get(0) == hop //depend on common subexpression elimination\n&& pred.getInput().get(1) instanceof LiteralOp\n- && HopRewriteUtils.getDoubleValueSafe((LiteralOp)pred.getInput().get(1))==0 )\n- {\n- return true;\n- }\n-\n- return false;\n+ && HopRewriteUtils.getDoubleValueSafe((LiteralOp)pred.getInput().get(1))==0 );\n}\npublic static boolean checkInputDataTypes(Hop hop, DataType... dt) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"diff": "@@ -168,6 +168,7 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\nhi = simplifyOrderedSort(hop, hi, i); //e.g., order(matrix())->seq;\nhi = fuseOrderOperationChain(hi); //e.g., order(order(X,2),1) -> order(X,(12))\nhi = removeUnnecessaryReorgOperation(hop, hi, i); //e.g., t(t(X))->X; rev(rev(X))->X potentially introduced by other rewrites\n+ hi = removeUnnecessaryRemoveEmpty(hop, hi, i); //e.g., nrow(removeEmpty(A)) -> nnz(A) iff col vector\nhi = simplifyTransposeAggBinBinaryChains(hop, hi, i);//e.g., t(t(A)%*%t(B)+C) -> B%*%A+t(C)\nhi = simplifyReplaceZeroOperation(hop, hi, i); //e.g., X + (X==0) * s -> replace(X, 0, s)\nhi = removeUnnecessaryMinus(hop, hi, i); //e.g., -(-X)->X; potentially introduced by simplify binary or dyn rewrites\n@@ -1616,6 +1617,39 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\nreturn hi;\n}\n+ private static Hop removeUnnecessaryRemoveEmpty(Hop parent, Hop hi, int pos)\n+ {\n+ Hop hnew = null;\n+\n+ if( HopRewriteUtils.isUnary(hi, OpOp1.NROW)\n+ && HopRewriteUtils.isRemoveEmpty(hi.getInput().get(0), true)\n+ && hi.getInput().get(0).getParent().size() == 1 )\n+ {\n+ ParameterizedBuiltinOp rm = (ParameterizedBuiltinOp) hi.getInput().get(0);\n+ //obtain optional select vector or input if col vector\n+ //NOTE: part of static rewrites despite size dependence for phase\n+ //ordering before rewrite for DAG splits after table/removeEmpty\n+ Hop input = (rm.getParameterHop(\"select\") != null) ?\n+ rm.getParameterHop(\"select\") :\n+ (rm.getDim2() == 1) ? rm.getTargetHop() : null;\n+\n+ //create new expression w/o rmEmpty if applicable\n+ if( input != null ) {\n+ HopRewriteUtils.removeAllChildReferences(rm);\n+ hnew = HopRewriteUtils.createComputeNnz(input);\n+ }\n+ }\n+\n+ //modify dag if one of the above rules applied\n+ if( hnew != null ){\n+ HopRewriteUtils.replaceChildReference(parent, hi, hnew, pos);\n+ hi = hnew;\n+ LOG.debug(\"Applied removeUnnecessaryRemoveEmpty (line \" + hi.getBeginLine() + \")\");\n+ }\n+\n+ return hi;\n+ }\n+\nprivate static Hop removeUnnecessaryMinus(Hop parent, Hop hi, int pos)\n{\nif( hi.getDataType() == DataType.MATRIX && hi instanceof BinaryOp\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RewriteEliminateRemoveEmptyTest.java",
"diff": "+/*\n+ * Licensed to the Apache Software Foundation (ASF) under one\n+ * or more contributor license agreements. See the NOTICE file\n+ * distributed with this work for additional information\n+ * regarding copyright ownership. The ASF licenses this file\n+ * to you under the Apache License, Version 2.0 (the\n+ * \"License\"); you may not use this file except in compliance\n+ * with the License. You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing,\n+ * software distributed under the License is distributed on an\n+ * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+ * KIND, either express or implied. See the License for the\n+ * specific language governing permissions and limitations\n+ * under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.misc;\n+\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.tugraz.sysds.hops.OptimizerUtils;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+public class RewriteEliminateRemoveEmptyTest extends AutomatedTestBase\n+{\n+ private static final String TEST_NAME1 = \"RewriteEliminateRmEmpty1\";\n+ private static final String TEST_NAME2 = \"RewriteEliminateRmEmpty2\";\n+\n+ private static final String TEST_DIR = \"functions/misc/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + RewriteEliminateRemoveEmptyTest.class.getSimpleName() + \"/\";\n+\n+ private static final int rows = 1092;\n+ private static final double sparsity = 0.4;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { \"B\" }) );\n+ addTestConfiguration( TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] { \"B\" }) );\n+ }\n+\n+ @Test\n+ public void testEliminateRmEmpty1() {\n+ testRewriteEliminateRmEmpty(TEST_NAME1, false);\n+ }\n+\n+ @Test\n+ public void testEliminateRmEmpty2() {\n+ testRewriteEliminateRmEmpty(TEST_NAME2, false);\n+ }\n+\n+ @Test\n+ public void testEliminateRmEmpty1Rewrites() {\n+ testRewriteEliminateRmEmpty(TEST_NAME1, true);\n+ }\n+\n+ @Test\n+ public void testEliminateRmEmpty2Rewrites() {\n+ testRewriteEliminateRmEmpty(TEST_NAME2, true);\n+ }\n+\n+ private void testRewriteEliminateRmEmpty(String test, boolean rewrites)\n+ {\n+ boolean oldFlag = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+\n+ try\n+ {\n+ TestConfiguration config = getTestConfiguration(test);\n+ loadTestConfiguration(config);\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + test + \".dml\";\n+ programArgs = new String[]{ \"-explain\", \"-stats\",\n+ \"-args\", input(\"A\"), output(\"B\") };\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewrites;\n+\n+ //generate actual dataset\n+ double[][] A = getRandomMatrix(rows, 1, -10, 10, sparsity, 7);\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+ long nnz = TestUtils.computeNNZ(A);\n+\n+ //run test\n+ runTest(true, false, null, -1);\n+\n+ //compare scalars\n+ double ret1 = readDMLMatrixFromHDFS(\"B\").get(new CellIndex(1,1));\n+ TestUtils.compareScalars(ret1, nnz, 1e-10);\n+\n+ //check for applied rewrites\n+ if( rewrites )\n+ Assert.assertFalse(heavyHittersContainsSubString(\"rmempty\"));\n+ }\n+ finally {\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = oldFlag;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/misc/RewriteEliminateRmEmpty1.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+A = read($1);\n+\n+# test: removeEmpty unnecessary, so pick A\n+B = removeEmpty(target=A, margin=\"rows\");\n+\n+R = as.matrix(nrow(B))\n+write(R, $2);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/misc/RewriteEliminateRmEmpty2.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+A = read($1);\n+I = (A != 0);\n+\n+# test: removeEmpty unnecessary, so pick I\n+B = removeEmpty(target=A, margin=\"rows\", select=I);\n+\n+R = as.matrix(nrow(B))\n+write(R, $2);\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-196] New rewrite for eliminating unnecessary rmEmpty ops
This patch adds a new rewrite that eliminates unneccessary removeEmpty
operations in expressions like nrow(removeEmpty(A)), which can be
obtained via sum(A!=0) and thus, nnz(A). This occurs for example, in the
new intersect function where nrow is used for discovering robust
inclusion dependencies. |
49,738 | 25.01.2020 18:26:04 | -3,600 | acc21dd0c7ea418b94637edb7a666022ece19fb7 | Fix rewrite simplify sequence of binary comparisons
This patch fixes an issue where (A!=0)!=0 was rewritten to A==0,
although it should simply drop the redundant comparison: A!=0, which
created incorrect results. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"diff": "@@ -1848,19 +1848,23 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\nprivate static Hop simplifyBinaryComparisonChain(Hop parent, Hop hi, int pos) {\nif( HopRewriteUtils.isBinaryPPred(hi)\n&& HopRewriteUtils.isLiteralOfValue(hi.getInput().get(1), 0d, 1d)\n- && HopRewriteUtils.isBinaryPPred(hi.getInput().get(0)) ) {\n+ && HopRewriteUtils.isBinaryPPred(hi.getInput().get(0)) )\n+ {\nBinaryOp bop = (BinaryOp) hi;\nBinaryOp bop2 = (BinaryOp) hi.getInput().get(0);\n+ boolean one = HopRewriteUtils.isLiteralOfValue(hi.getInput().get(1), 0);\n//pattern: outer(v1,v2,\"!=\") == 1 -> outer(v1,v2,\"!=\")\n- if( HopRewriteUtils.isLiteralOfValue(bop.getInput().get(1), 1) ) {\n+ if( (one && bop.getOp() == OpOp2.EQUAL)\n+ || (!one && bop.getOp() == OpOp2.NOTEQUAL) )\n+ {\nHopRewriteUtils.replaceChildReference(parent, bop, bop2, pos);\nHopRewriteUtils.cleanupUnreferenced(bop);\nhi = bop2;\nLOG.debug(\"Applied simplifyBinaryComparisonChain1 (line \"+hi.getBeginLine()+\")\");\n}\n//pattern: outer(v1,v2,\"!=\") == 0 -> outer(v1,v2,\"==\")\n- else {\n+ else if( !one && bop.getOp() == OpOp2.EQUAL ) {\nOpOp2 optr = bop2.getComplementPPredOperation();\nBinaryOp tmp = HopRewriteUtils.createBinary(bop2.getInput().get(0),\nbop2.getInput().get(1), optr, bop2.isOuter());\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-204] Fix rewrite simplify sequence of binary comparisons
This patch fixes an issue where (A!=0)!=0 was rewritten to A==0,
although it should simply drop the redundant comparison: A!=0, which
created incorrect results. |
49,689 | 25.01.2020 19:10:09 | -3,600 | b9ed9cce9a939e57d7daaf3d979f1508396a48bc | Lineage cache and reuse of function results
Closes | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/FunctionCallCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/FunctionCallCPInstruction.java",
"diff": "@@ -28,16 +28,24 @@ import org.tugraz.sysds.lops.Lop;\nimport org.tugraz.sysds.parser.DMLProgram;\nimport org.tugraz.sysds.parser.DataIdentifier;\nimport org.tugraz.sysds.common.Types.DataType;\n+import org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.DMLScriptException;\nimport org.tugraz.sysds.runtime.controlprogram.FunctionProgramBlock;\nimport org.tugraz.sysds.runtime.controlprogram.LocalVariableMap;\n+import org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContextFactory;\nimport org.tugraz.sysds.runtime.instructions.Instruction;\nimport org.tugraz.sysds.runtime.instructions.InstructionUtils;\nimport org.tugraz.sysds.runtime.io.IOUtilFunctions;\nimport org.tugraz.sysds.runtime.lineage.Lineage;\n+import org.tugraz.sysds.runtime.lineage.LineageCache;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\n+import org.tugraz.sysds.runtime.lineage.LineageItem;\n+import org.tugraz.sysds.runtime.lineage.LineageItemUtils;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\n+import org.tugraz.sysds.runtime.meta.MetaData;\npublic class FunctionCallCPInstruction extends CPInstruction {\nprivate final String _functionName;\n@@ -109,6 +117,12 @@ public class FunctionCallCPInstruction extends CPInstruction {\n+ \"(\"+_boundInputs.length+\", but \"+fpb.getInputParams().size()+\" expected)\");\n}\n+ // check if function outputs can be reused from cache\n+ LineageItem[] liInputs = DMLScript.LINEAGE ?\n+ LineageItemUtils.getLineage(ec, _boundInputs) : null;\n+ if( reuseFunctionOutputs(liInputs, fpb, ec) )\n+ return; //only if all the outputs are found in cache\n+\n// create bindings to formal parameters for given function call\n// These are the bindings passed to the FunctionProgramBlock for function execution\nLocalVariableMap functionVariables = new LocalVariableMap();\n@@ -210,6 +224,16 @@ public class FunctionCallCPInstruction extends CPInstruction {\n//map lineage of function returns back to calling site\nif( lineage != null ) //unchanged ref\nec.getLineage().set(boundVarName, lineage.get(retVarName));\n+\n+ if (!ReuseCacheType.isNone()) {\n+ String opcode = _functionName + String.valueOf(i+1);\n+ LineageItem li = new LineageItem(_boundOutputNames.get(i), opcode, liInputs);\n+ if (boundValue instanceof ScalarObject) //TODO: cache scalar objects\n+ LineageCache.removeEntry(li); //remove the placeholder\n+ else\n+ LineageCache.putValue(li, lineage.get(retVarName), (MatrixObject)boundValue);\n+ //TODO: Unmark for caching in compiler if function contains rand()\n+ }\n}\n}\n@@ -244,4 +268,46 @@ public class FunctionCallCPInstruction extends CPInstruction {\nreturn sb.substring( 0, sb.length()-Lop.OPERAND_DELIMITOR.length() );\n}\n+\n+ private boolean reuseFunctionOutputs(LineageItem[] liInputs, FunctionProgramBlock fpb, ExecutionContext ec) {\n+ if( ReuseCacheType.isNone() )\n+ return false;\n+\n+ int numOutputs = Math.min(_boundOutputNames.size(), fpb.getOutputParams().size());\n+ boolean reuse = true;\n+ for (int i=0; i< numOutputs; i++) {\n+ //String opcode = _functionName + _boundOutputNames.get(i);\n+ String opcode = _functionName + String.valueOf(i+1);\n+ LineageItem li = new LineageItem(_boundOutputNames.get(i), opcode, liInputs);\n+ MatrixBlock cachedValue = LineageCache.reuse(li);\n+\n+ if (cachedValue != null) {\n+ String boundVarName = _boundOutputNames.get(i);\n+ //convert to matrix object\n+ MetaData md = new MetaData(cachedValue.getDataCharacteristics());\n+ MatrixObject boundValue = new MatrixObject(ValueType.FP64, boundVarName, md);\n+ boundValue.acquireModify(cachedValue);\n+ boundValue.release();\n+\n+ //cleanup existing data bound to output variable name\n+ Data exdata = ec.removeVariable(boundVarName);\n+ if( exdata != boundValue)\n+ ec.cleanupDataObject(exdata);\n+\n+ //add/replace data in symbol table\n+ ec.setVariable(boundVarName, boundValue);\n+\n+ // map original lineage of function return to the calling site\n+ LineageItem orig = LineageCache.getNext(li);\n+ ec.getLineage().set(boundVarName, orig);\n+ }\n+ else {\n+ // if one output cannot be reused, we need to execute the function\n+ // NOTE: all outputs need to be prepared for caching and hence,\n+ // we cannot directly return here\n+ reuse = false;\n+ }\n+ }\n+ return reuse;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "@@ -64,7 +64,7 @@ public class LineageCache {\nreturn false;\nboolean reuse = false;\n- if (inst instanceof ComputationCPInstruction && LineageCache.isReusable(inst)) {\n+ if (inst instanceof ComputationCPInstruction && LineageCache.isReusable(inst, ec)) {\nLineageItem item = ((ComputationCPInstruction) inst).getLineageItems(ec)[0];\nsynchronized( _cache ) {\n@@ -84,10 +84,35 @@ public class LineageCache {\nreturn reuse;\n}\n+ public static MatrixBlock reuse(LineageItem item) {\n+ if (ReuseCacheType.isNone())\n+ return null;\n+\n+ MatrixBlock d = null;\n+ synchronized( _cache ) {\n+ if (LineageCache.probe(item))\n+ d = LineageCache.get(item);\n+ else\n+ //create a placeholder if no reuse to avoid redundancy\n+ //(e.g., concurrent threads that try to start the computation)\n+ putIntern(item, null, 0);\n+ }\n+ return d;\n+ }\n+\n+ public static LineageItem getNext(LineageItem firstItem) {\n+ for(Map.Entry<LineageItem, Entry> entry : _cache.entrySet()) {\n+ if (!(entry.getKey().equals(firstItem)) && !entry.getValue().isNullVal() &&\n+ (entry.getValue().getValue() == _cache.get(firstItem).getValue()))\n+ return entry.getKey();\n+ }\n+ return null;\n+ }\n+\n//NOTE: safe to pin the object in memory as coming from CPInstruction\npublic static void put(Instruction inst, ExecutionContext ec) {\n- if (inst instanceof ComputationCPInstruction && isReusable(inst) ) {\n+ if (inst instanceof ComputationCPInstruction && isReusable(inst, ec) ) {\nLineageItem item = ((LineageTraceable) inst).getLineageItems(ec)[0];\nMatrixObject mo = ec.getMatrixObject(((ComputationCPInstruction) inst).output);\nsynchronized( _cache ) {\n@@ -99,7 +124,7 @@ public class LineageCache {\npublic static void putValue(Instruction inst, ExecutionContext ec) {\nif (ReuseCacheType.isNone())\nreturn;\n- if (inst instanceof ComputationCPInstruction && isReusable(inst) ) {\n+ if (inst instanceof ComputationCPInstruction && isReusable(inst, ec) ) {\nLineageItem item = ((LineageTraceable) inst).getLineageItems(ec)[0];\nMatrixObject mo = ec.getMatrixObject(((ComputationCPInstruction) inst).output);\nMatrixBlock value = mo.acquireReadAndRelease();\n@@ -113,6 +138,24 @@ public class LineageCache {\n}\n}\n+ public static void putValue(LineageItem item, LineageItem probeItem, MatrixObject mo) {\n+ if (ReuseCacheType.isNone())\n+ return;\n+ if (LineageCache.probe(probeItem)) {\n+ MatrixBlock value = LineageCache.get(probeItem);\n+ _cache.get(item).setValue(value, 0); //TODO: compute estimate for function\n+\n+ synchronized( _cache ) {\n+ if(!isBelowThreshold(value))\n+ makeSpace(value);\n+ updateSize(value, true);\n+ }\n+ }\n+ else\n+ removeEntry(item); //remove the placeholder\n+\n+ }\n+\nprivate static void putIntern(LineageItem key, MatrixBlock value, double compcost) {\nif (_cache.containsKey(key))\n//can come here if reuse_partial option is enabled\n@@ -179,7 +222,7 @@ public class LineageCache {\nreturn readFromLocalFS(key);\n}\n- public static boolean isReusable (Instruction inst) {\n+ public static boolean isReusable (Instruction inst, ExecutionContext ec) {\n// TODO: Move this to the new class LineageCacheConfig and extend\nreturn inst.getOpcode().equalsIgnoreCase(\"tsmm\")\n|| inst.getOpcode().equalsIgnoreCase(\"ba+*\")\n@@ -187,7 +230,17 @@ public class LineageCache {\ninst instanceof BinaryMatrixMatrixCPInstruction) //TODO support scalar\n|| inst.getOpcode().equalsIgnoreCase(\"rightIndex\")\n|| inst.getOpcode().equalsIgnoreCase(\"groupedagg\")\n- || inst.getOpcode().equalsIgnoreCase(\"r'\");\n+ || inst.getOpcode().equalsIgnoreCase(\"r'\")\n+ || (inst.getOpcode().equalsIgnoreCase(\"append\") && isVectorAppend(inst, ec))\n+ || inst.getOpcode().equalsIgnoreCase(\"solve\");\n+ }\n+\n+ private static boolean isVectorAppend(Instruction inst, ExecutionContext ec) {\n+ MatrixObject mo1 = ec.getMatrixObject(((ComputationCPInstruction)inst).input1);\n+ MatrixObject mo2 = ec.getMatrixObject(((ComputationCPInstruction)inst).input2);\n+ long c1 = mo1.getNumColumns();\n+ long c2 = mo2.getNumColumns();\n+ return(c1 == 1 || c2 == 1);\n}\n//---------------- CACHE SPACE MANAGEMENT METHODS -----------------\n@@ -201,6 +254,11 @@ public class LineageCache {\n// cost based eviction\nwhile ((valSize+_cachesize) > CACHE_LIMIT)\n{\n+ if (_cache.get(_end._key).isNullVal()) {\n+ setEnd2Head(_end); // Must be null function entry. Move to next.\n+ continue;\n+ }\n+\ndouble reduction = _cache.get(_end._key).getValue().getInMemorySize();\nif (_cache.get(_end._key)._compEst > getDiskSpillEstimate()\n&& LineageCacheConfig.isSetSpill())\n@@ -290,6 +348,8 @@ public class LineageCache {\nif (inst.getOpcode().equalsIgnoreCase(\"*\"))\n// considering the dimensions of inputs and the output are same\nnflops = r1 * c1;\n+ else if (inst.getOpcode().equalsIgnoreCase(\"solve\"))\n+ nflops = r1 * c1 * c1;\nbreak;\n}\n@@ -337,6 +397,24 @@ public class LineageCache {\nbreak;\n}\n+ case Append:\n+ {\n+ MatrixObject mo1 = ec.getMatrixObject(((ComputationCPInstruction)inst).input1);\n+ MatrixObject mo2 = ec.getMatrixObject(((ComputationCPInstruction)inst).input2);\n+ long r1 = mo1.getNumRows();\n+ long c1 = mo1.getNumColumns();\n+ long nnz1 = mo1.getNnz();\n+ double s1 = OptimizerUtils.getSparsity(r1, c1, nnz1);\n+ boolean lsparse = MatrixBlock.evalSparseFormatInMemory(r1, c1, nnz1);\n+ long r2 = mo2.getNumRows();\n+ long c2 = mo2.getNumColumns();\n+ long nnz2 = mo2.getNnz();\n+ double s2 = OptimizerUtils.getSparsity(r2, c2, nnz2);\n+ boolean rsparse = MatrixBlock.evalSparseFormatInMemory(r2, c2, nnz2);\n+ nflops = 1.0 * ((lsparse ? r1*c1*s1 : r1*c1) + (rsparse ? r2*c2*s2 : r2*c2));\n+ break;\n+ }\n+\ndefault:\nthrow new DMLRuntimeException(\"Lineage Cache: unsupported instruction: \"+inst.getOpcode());\n}\n@@ -415,6 +493,11 @@ public class LineageCache {\n_end = _head;\n}\n+ private static void setEnd2Head(Entry entry) {\n+ delete(entry);\n+ setHead(entry);\n+ }\n+\nprivate static void removeEntry(double space) {\nif (DMLScript.STATISTICS)\n_removelist.add(_end._key);\n@@ -423,6 +506,14 @@ public class LineageCache {\ndelete(_end);\n}\n+ public static void removeEntry(LineageItem key) {\n+ // Remove the entry for key\n+ if (!_cache.containsKey(key))\n+ return;\n+ delete(_cache.get(key));\n+ _cache.remove(key);\n+ }\n+\nprivate static class Entry {\nprivate final LineageItem _key;\nprivate MatrixBlock _val;\n@@ -450,6 +541,10 @@ public class LineageCache {\n}\n}\n+ public boolean isNullVal() {\n+ return(_val == null);\n+ }\n+\npublic synchronized void setValue(MatrixBlock val, double compEst) {\n_val = val;\n_compEst = compEst;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageRewriteReuse.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageRewriteReuse.java",
"diff": "@@ -514,7 +514,7 @@ public class LineageRewriteReuse\nprivate static boolean isTsmmCbind(Instruction curr, ExecutionContext ec, Map<String, MatrixBlock> inCache)\n{\n- if (!LineageCache.isReusable(curr)) {\n+ if (!LineageCache.isReusable(curr, ec)) {\nreturn false;\n}\n@@ -539,7 +539,7 @@ public class LineageRewriteReuse\nprivate static boolean isTsmmRbind(Instruction curr, ExecutionContext ec, Map<String, MatrixBlock> inCache)\n{\n- if (!LineageCache.isReusable(curr))\n+ if (!LineageCache.isReusable(curr, ec))\nreturn false;\n// If the input to tsmm came from rbind, look for both the inputs in cache.\n@@ -562,7 +562,7 @@ public class LineageRewriteReuse\nprivate static boolean isTsmm2Cbind (Instruction curr, ExecutionContext ec, Map<String, MatrixBlock> inCache)\n{\n- if (!LineageCache.isReusable(curr))\n+ if (!LineageCache.isReusable(curr, ec))\nreturn false;\n//TODO: support nary cbind\n@@ -590,7 +590,7 @@ public class LineageRewriteReuse\nprivate static boolean isMatMulRbindLeft(Instruction curr, ExecutionContext ec, Map<String, MatrixBlock> inCache)\n{\n- if (!LineageCache.isReusable(curr))\n+ if (!LineageCache.isReusable(curr, ec))\nreturn false;\n// If the left input to ba+* came from rbind, look for both the inputs in cache.\n@@ -615,7 +615,7 @@ public class LineageRewriteReuse\nprivate static boolean isMatMulCbindRight(Instruction curr, ExecutionContext ec, Map<String, MatrixBlock> inCache)\n{\n- if (!LineageCache.isReusable(curr))\n+ if (!LineageCache.isReusable(curr, ec))\nreturn false;\n// If the right input to ba+* came from cbind, look for both the inputs in cache.\n@@ -639,7 +639,7 @@ public class LineageRewriteReuse\nprivate static boolean isElementMulRbind(Instruction curr, ExecutionContext ec, Map<String, MatrixBlock> inCache)\n{\n- if (!LineageCache.isReusable(curr))\n+ if (!LineageCache.isReusable(curr, ec))\nreturn false;\n// If the inputs to * came from rbind, look for both the inputs in cache.\n@@ -666,7 +666,7 @@ public class LineageRewriteReuse\nprivate static boolean isElementMulCbind(Instruction curr, ExecutionContext ec, Map<String, MatrixBlock> inCache)\n{\n- if (!LineageCache.isReusable(curr))\n+ if (!LineageCache.isReusable(curr, ec))\nreturn false;\n// If the inputs to * came from cbind, look for both the inputs in cache.\n@@ -693,7 +693,7 @@ public class LineageRewriteReuse\nprivate static boolean isAggCbind (Instruction curr, ExecutionContext ec, Map<String, MatrixBlock> inCache)\n{\n- if (!LineageCache.isReusable(curr)) {\n+ if (!LineageCache.isReusable(curr, ec)) {\nreturn false;\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/FunctionFullReuseTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.lineage;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.hops.OptimizerUtils;\n+import org.tugraz.sysds.hops.recompile.Recompiler;\n+import org.tugraz.sysds.runtime.lineage.Lineage;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+public class FunctionFullReuseTest extends AutomatedTestBase {\n+\n+ protected static final String TEST_DIR = \"functions/lineage/\";\n+ protected static final String TEST_NAME1 = \"FunctionFullReuse1\";\n+ protected static final String TEST_NAME2 = \"FunctionFullReuse2\";\n+ protected static final String TEST_NAME3 = \"FunctionFullReuse3\";\n+ protected static final String TEST_NAME4 = \"FunctionFullReuse4\";\n+ protected String TEST_CLASS_DIR = TEST_DIR + FunctionFullReuseTest.class.getSimpleName() + \"/\";\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1));\n+ addTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2));\n+ addTestConfiguration(TEST_NAME3, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME3));\n+ addTestConfiguration(TEST_NAME4, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME4));\n+ }\n+\n+ @Test\n+ public void testCacheHit() {\n+ testLineageTrace(TEST_NAME1);\n+ }\n+\n+ @Test\n+ public void testCacheMiss() {\n+ testLineageTrace(TEST_NAME2);\n+ }\n+\n+ @Test\n+ public void testMultipleReturns() {\n+ testLineageTrace(TEST_NAME3);\n+ }\n+\n+ @Test\n+ public void testNestedFunc() {\n+ testLineageTrace(TEST_NAME4);\n+ }\n+\n+ public void testLineageTrace(String testname) {\n+ boolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ boolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n+\n+ try {\n+ System.out.println(\"------------ BEGIN \" + testname + \"------------\");\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = false;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = false;\n+\n+ getAndLoadTestConfiguration(testname);\n+ fullDMLScriptName = getScript();\n+\n+ // Without lineage-based reuse enabled\n+ List<String> proArgs = new ArrayList<>();\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(output(\"X\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ Lineage.resetInternalState();\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+ HashMap<MatrixValue.CellIndex, Double> X_orig = readDMLMatrixFromHDFS(\"X\");\n+\n+ // With lineage-based reuse enabled\n+ proArgs.clear();\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(ReuseCacheType.REUSE_FULL.name().toLowerCase());\n+ proArgs.add(\"-args\");\n+ proArgs.add(output(\"X\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ Lineage.resetInternalState();\n+ Lineage.setLinReuseFull();\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+ HashMap<MatrixValue.CellIndex, Double> X_reused = readDMLMatrixFromHDFS(\"X\");\n+ Lineage.setLinReuseNone();\n+\n+ TestUtils.compareMatrices(X_orig, X_reused, 1e-6, \"Origin\", \"Reused\");\n+ }\n+ finally {\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = old_simplification;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = old_sum_product;\n+ Recompiler.reinitRecompiler();\n+ }\n+ }\n+}\n+\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/FunctionFullReuse1.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+# Increase rows and cols for better performance gains\n+\n+SimLM = function(Matrix[Double] X, Matrix[Double] y, Double lamda=0.0001) return (Matrix[Double] beta)\n+{\n+ A = t(X) %*% X + diag(matrix(lamda, rows=ncol(X), cols=1));\n+ b = t(X) %*% y;\n+ beta = solve(A, b);\n+\n+ if (nrow(beta) == ncol(X))\n+ beta = t(beta) %*% beta;\n+}\n+\n+r = 100\n+c = 10\n+\n+X = rand(rows=r, cols=c, seed=42);\n+y = rand(rows=r, cols=1, seed=43);\n+R = matrix(0, 1, 2);\n+\n+beta1 = SimLM(X, y, 0.0001);\n+R[,1] = beta1;\n+\n+beta2 = SimLM(X, y, 0.0001);\n+R[,2] = beta2;\n+\n+write(R, $1, format=\"text\");\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/FunctionFullReuse2.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+# Increase rows and cols for better performance gains\n+\n+SimLM = function(Matrix[Double] X, Matrix[Double] y, Double lamda=0.0001) return (Matrix[Double] beta)\n+{\n+ A = t(X) %*% X + diag(matrix(lamda, rows=ncol(X), cols=1));\n+ b = t(X) %*% y;\n+ beta = solve(A, b);\n+\n+ if (nrow(beta) == ncol(X))\n+ beta = t(beta) %*% beta;\n+}\n+\n+r = 100\n+c = 10\n+\n+X = rand(rows=r, cols=c, seed=42);\n+y = rand(rows=r, cols=1, seed=43);\n+R = matrix(0, 1, 2);\n+\n+beta = SimLM(X, y, 0.0001);\n+R[,1] = beta;\n+\n+y = y + 1; # to generate cache miss\n+beta = SimLM(X, y, 0.0001);\n+R[,2] = beta;\n+\n+write(R, $1, format=\"text\");\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/FunctionFullReuse3.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+# Increase rows and cols for better performance gains\n+\n+func2returns = function(Matrix[Double] X, Matrix[Double] y) return (Matrix[Double] matmul, Matrix[Double] tsmmX)\n+{\n+ matmul = y %*% X;\n+ tsmmX = t(X) %*% X;\n+ while(FALSE){}\n+}\n+\n+r = 100\n+c = 1\n+\n+X = rand(rows=r, cols=c, seed=42);\n+y = rand(rows=c, cols=r, seed=43);\n+R = matrix(0, 1, 4);\n+\n+[matmul, tsmmX] = func2returns(X, y);\n+R[,1] = matmul;\n+R[,2] = tsmmX;\n+\n+[matmul, tsmmX] = func2returns(X, y);\n+R[,3] = matmul;\n+R[,4] = tsmmX;\n+\n+write(R, $1, format=\"text\");\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/FunctionFullReuse4.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+# Increase rows and cols for better performance gains\n+\n+funcadd = function(Matrix[Double] X) return (Matrix[Double] addX)\n+{\n+ addX = X + 1;\n+ while(FALSE){}\n+}\n+\n+functsmm = function(Matrix[Double] X) return (Matrix[Double] tsmmX)\n+{\n+ X = funcadd(X);\n+ tsmmX = t(X) %*% X;\n+ while(FALSE){}\n+}\n+\n+r = 100\n+c = 1\n+\n+X = rand(rows=r, cols=c, seed=42);\n+R = matrix(0, 1, 2);\n+\n+tsmmX = functsmm(X);\n+R[,1] = tsmmX;\n+\n+tsmmX = functsmm(X);\n+R[,2] = tsmmX;\n+\n+write(R, $1, format=\"text\");\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-233] Lineage cache and reuse of function results
Closes #84. |
49,693 | 25.01.2020 20:21:55 | -3,600 | 730f5df8dc2f5203dbb898a78d600d74c5405f6e | [BUGFIX] when reading a DML script from HDFS, a try block closed the Filesystem object before reading the script completed | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/api/DMLScript.java",
"new_path": "src/main/java/org/tugraz/sysds/api/DMLScript.java",
"diff": "@@ -114,6 +114,8 @@ public class DMLScript\npublic static String _uuid = IDHandler.createDistributedUniqueID();\nprivate static final Log LOG = LogFactory.getLog(DMLScript.class.getName());\n+ private static FileSystem fs = null;\n+\n///////////////////////////////\n// public external interface\n////////\n@@ -285,10 +287,9 @@ public class DMLScript\n|| IOUtilFunctions.isObjectStoreFileScheme(new Path(fileName)) )\n{\nPath scriptPath = new Path(fileName);\n- try(FileSystem fs = IOUtilFunctions.getFileSystem(scriptPath) ) {\n+ fs = IOUtilFunctions.getFileSystem(scriptPath);\nin = new BufferedReader(new InputStreamReader(fs.open(scriptPath)));\n}\n- }\n// from local file system\nelse {\nin = new BufferedReader(new FileReader(fileName));\n@@ -306,6 +307,8 @@ public class DMLScript\nthrow ex;\n}\nfinally {\n+ if(fs != null)\n+ fs.close();\nIOUtilFunctions.closeSilently(in);\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [BUGFIX] when reading a DML script from HDFS, a try block closed the Filesystem object before reading the script completed |
49,738 | 26.01.2020 00:24:54 | -3,600 | 08ff72c2d827251b0c1337008b3e12def460a8c9 | [MINOR] Fix correction handling inconsistencies (spark, invalid types) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/OperationsOnMatrixValues.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/OperationsOnMatrixValues.java",
"diff": "@@ -103,12 +103,11 @@ public class OperationsOnMatrixValues\n}\npublic static void startAggregation(MatrixValue valueOut, MatrixValue correction, AggregateOperator op,\n- int rlen, int clen, boolean sparseHint, boolean imbededCorrection) {\n+ int rlen, int clen, boolean sparseHint, boolean embeddedCorrection) {\nint outRow=0, outCol=0, corRow=0, corCol=0;\n- if(op.existsCorrection())\n- {\n- if(!imbededCorrection)\n+ if(!embeddedCorrection || op.existsCorrection())\n{\n+ if( !embeddedCorrection ) {\nswitch(op.correction)\n{\ncase NONE:\n@@ -185,8 +184,7 @@ public class OperationsOnMatrixValues\ncorrection.reset(Math.max(corRow,0), Math.max(corCol,0), op.initialValue);\n}\n}\n- else\n- {\n+ else {\nif(op.initialValue==0)\nvalueOut.reset(rlen, clen, sparseHint);\nelse\n@@ -201,11 +199,10 @@ public class OperationsOnMatrixValues\npublic static void incrementalAggregation(MatrixValue valueAgg, MatrixValue correction, MatrixValue valueAdd,\n- AggregateOperator op, boolean imbededCorrection, boolean deep)\n- {\n- if(op.existsCorrection())\n+ AggregateOperator op, boolean embeddedCorrection, boolean deep)\n{\n- if(!imbededCorrection || op.correction==CorrectionLocationType.NONE)\n+ if(!embeddedCorrection || op.existsCorrection()) {\n+ if( op.correction==CorrectionLocationType.NONE )\nvalueAgg.incrementalAggregate(op, correction, valueAdd, deep);\nelse\nvalueAgg.incrementalAggregate(op, valueAdd);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/operators/AggregateOperator.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/operators/AggregateOperator.java",
"diff": "@@ -53,6 +53,7 @@ public class AggregateOperator extends Operator implements Serializable\n}\npublic boolean existsCorrection() {\n- return correction != CorrectionLocationType.NONE;\n+ return correction != CorrectionLocationType.NONE\n+ && correction != CorrectionLocationType.INVALID;\n}\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix correction handling inconsistencies (spark, invalid types) |
49,738 | 26.01.2020 13:07:00 | -3,600 | 7c18f560fea0c88225fd613bcb340304cb02eac6 | Fix robustness of federated instruction replacement
This patch fixes issues with the federated instruction replacement which
assumes matrix types and thus fails for frames and lists. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstructionUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstructionUtils.java",
"diff": "@@ -31,6 +31,7 @@ public class FEDInstructionUtils {\npublic static Instruction checkAndReplaceCP(Instruction inst, ExecutionContext ec) {\nif (inst instanceof AggregateBinaryCPInstruction) {\nAggregateBinaryCPInstruction instruction = (AggregateBinaryCPInstruction) inst;\n+ if( instruction.input1.isMatrix() && instruction.input2.isMatrix() ) {\nMatrixObject mo1 = ec.getMatrixObject(instruction.input1);\nMatrixObject mo2 = ec.getMatrixObject(instruction.input2);\nif (mo1.isFederated() && mo2.getNumColumns() == 1 || mo1.getNumRows() == 1 && mo2.isFederated()) {\n@@ -38,12 +39,15 @@ public class FEDInstructionUtils {\nreturn AggregateBinaryFEDInstruction.parseInstruction(inst.getInstructionString());\n}\n}\n+ }\nelse if (inst instanceof AggregateUnaryCPInstruction) {\nAggregateUnaryCPInstruction instruction = (AggregateUnaryCPInstruction) inst;\n+ if( instruction.input1.isMatrix() ) {\nMatrixObject mo1 = ec.getMatrixObject(instruction.input1);\nif (mo1.isFederated() && instruction.getAUType() == AggregateUnaryCPInstruction.AUType.DEFAULT)\nreturn AggregateUnaryFEDInstruction.parseInstruction(inst.getInstructionString());\n}\n+ }\nreturn inst;\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-223] Fix robustness of federated instruction replacement
This patch fixes issues with the federated instruction replacement which
assumes matrix types and thus fails for frames and lists. |
49,738 | 26.01.2020 13:12:41 | -3,600 | afa6862b2e71bf3266173a00ab0220b171c5ad95 | Fix test conflict w/ dml-bodied pnmf builtin function
This patch just temporarily fixes the existing tests, but down the road
we should allow that user-defined functions take presedence over
dml-bodied builtin functions. | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -155,6 +155,7 @@ SYSTEMDS-200 Various Fixes\n* 202 Fix rewrite split DAG multiple removeEmpty (pending op) OK\n* 203 Fix codegen outer compilation (MV operations) OK\n* 204 Fix rewrite simplify sequences of binary comparisons OK\n+ * 205 Fix scoping of builtin dml-bodied functions (vs user-defined)\nSYSTEMDS-210 Extended lists Operations\n* 211 Cbind and Rbind over lists of matrices OK\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/misc/IPAScalarVariablePropagation.dml",
"new_path": "src/test/scripts/functions/misc/IPAScalarVariablePropagation.dml",
"diff": "#-------------------------------------------------------------\n-pnmf = function(matrix[double] V, integer max_iteration, integer rank) return (matrix[double] W, matrix[double] H) {\n+pnmf2 = function(matrix[double] V, integer max_iteration, integer rank) return (matrix[double] W, matrix[double] H) {\nn = nrow(V)\nm = ncol(V)\n@@ -47,7 +47,7 @@ max_iteration = 5\nrank = as.integer($1)\n# run PNMF and evaluate\n-[W, H] = pnmf(X, max_iteration, rank)\n+[W, H] = pnmf2(X, max_iteration, rank)\nnegloglik_temp = negloglikfunc(X, W, H)\n# write outputs\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-185] Fix test conflict w/ dml-bodied pnmf builtin function
This patch just temporarily fixes the existing tests, but down the road
we should allow that user-defined functions take presedence over
dml-bodied builtin functions. |
49,738 | 26.01.2020 13:21:38 | -3,600 | fdf44ae79e485d2c7ff523a83498f24ddd32acd1 | [SYSTEMDS-223,233] Fix invalid input handling federated/lineage | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/ExecutionContext.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/ExecutionContext.java",
"diff": "@@ -186,6 +186,10 @@ public class ExecutionContext {\n_variables.put(name, val);\n}\n+ public boolean containsVariable(CPOperand operand) {\n+ return containsVariable(operand.getName());\n+ }\n+\npublic boolean containsVariable(String name) {\nreturn _variables.keySet().contains(name);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstructionUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstructionUtils.java",
"diff": "@@ -42,7 +42,7 @@ public class FEDInstructionUtils {\n}\nelse if (inst instanceof AggregateUnaryCPInstruction) {\nAggregateUnaryCPInstruction instruction = (AggregateUnaryCPInstruction) inst;\n- if( instruction.input1.isMatrix() ) {\n+ if( instruction.input1.isMatrix() && ec.containsVariable(instruction.input1) ) {\nMatrixObject mo1 = ec.getMatrixObject(instruction.input1);\nif (mo1.isFederated() && instruction.getAUType() == AggregateUnaryCPInstruction.AUType.DEFAULT)\nreturn AggregateUnaryFEDInstruction.parseInstruction(inst.getInstructionString());\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "@@ -238,10 +238,11 @@ public class LineageCache {\n}\nprivate static boolean isVectorAppend(Instruction inst, ExecutionContext ec) {\n- MatrixObject mo1 = ec.getMatrixObject(((ComputationCPInstruction)inst).input1);\n- MatrixObject mo2 = ec.getMatrixObject(((ComputationCPInstruction)inst).input2);\n- long c1 = mo1.getNumColumns();\n- long c2 = mo2.getNumColumns();\n+ ComputationCPInstruction cpinst = (ComputationCPInstruction) inst;\n+ if( !cpinst.input1.isMatrix() || !cpinst.input2.isMatrix() )\n+ return false;\n+ long c1 = ec.getMatrixObject(cpinst.input1).getNumColumns();\n+ long c2 = ec.getMatrixObject(cpinst.input2).getNumColumns();\nreturn(c1 == 1 || c2 == 1);\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-223,233] Fix invalid input handling federated/lineage |
49,738 | 26.01.2020 19:59:58 | -3,600 | fd208ffe8e051e2992c0e944388a877e2f43a5ec | Fix corrupted rewrite binary comparison chains | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"diff": "@@ -1852,7 +1852,7 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\n{\nBinaryOp bop = (BinaryOp) hi;\nBinaryOp bop2 = (BinaryOp) hi.getInput().get(0);\n- boolean one = HopRewriteUtils.isLiteralOfValue(hi.getInput().get(1), 0);\n+ boolean one = HopRewriteUtils.isLiteralOfValue(hi.getInput().get(1), 1);\n//pattern: outer(v1,v2,\"!=\") == 1 -> outer(v1,v2,\"!=\")\nif( (one && bop.getOp() == OpOp2.EQUAL)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-204] Fix corrupted rewrite binary comparison chains |
49,738 | 26.01.2020 20:02:25 | -3,600 | f7e5053fa1ddd442402717b8b66e30040dfd9e90 | [MINOR] Fix kahan aggregation operators with separate corrections | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/functionobjects/KahanFunction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/functionobjects/KahanFunction.java",
"diff": "@@ -44,4 +44,9 @@ public abstract class KahanFunction extends ValueFunction implements Serializabl\npublic abstract void execute2(KahanObject kObj, double in);\npublic abstract void execute3(KahanObject kObj, double in, int count);\n+\n+ @Override\n+ public final boolean requiresCorrection() {\n+ return true;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/functionobjects/ValueFunction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/functionobjects/ValueFunction.java",
"diff": "@@ -25,4 +25,7 @@ public abstract class ValueFunction extends FunctionObject implements Serializab\n{\nprivate static final long serialVersionUID = -4985988545393861058L;\n+ public boolean requiresCorrection() {\n+ return false;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/OperationsOnMatrixValues.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/OperationsOnMatrixValues.java",
"diff": "@@ -193,8 +193,8 @@ public class OperationsOnMatrixValues\n}\npublic static void incrementalAggregation(MatrixValue valueAgg, MatrixValue correction, MatrixValue valueAdd,\n- AggregateOperator op, boolean imbededCorrection) {\n- incrementalAggregation(valueAgg, correction, valueAdd, op, imbededCorrection, true);\n+ AggregateOperator op, boolean embeddedCorrection) {\n+ incrementalAggregation(valueAgg, correction, valueAdd, op, embeddedCorrection, true);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/operators/AggregateOperator.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/operators/AggregateOperator.java",
"diff": "@@ -53,7 +53,8 @@ public class AggregateOperator extends Operator implements Serializable\n}\npublic boolean existsCorrection() {\n- return correction != CorrectionLocationType.NONE\n- && correction != CorrectionLocationType.INVALID;\n+ return (correction != CorrectionLocationType.NONE\n+ && correction != CorrectionLocationType.INVALID)\n+ || increOp.fn.requiresCorrection();\n}\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix kahan aggregation operators with separate corrections |
49,720 | 26.01.2020 20:25:32 | -3,600 | 6589c93dad918f4fcacdb73d28ccd9aeb8af540d | Builtin function for functional dependency discovery
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -148,7 +148,8 @@ SYSTEMDS-190 New Builtin Functions III\n* 193 New outlierBySds builtin function (delete row/cell)\n* 194 New outlierByIQR builtin function (delete row/cell)\n* 195 Builtin function mice for nominal features\n- * 196 Builtin function intersect (set intersection)\n+ * 196 Builtin function intersect (set intersection) OK\n+ * 197 Builtin function for functional dependency discovery\nSYSTEMDS-200 Various Fixes\n* 201 Fix spark append instruction zero columns OK\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/builtin/discoverFD.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#\n+#-------------------------------------------------------------\n+\n+# Implements builtin for finding functional dependencies\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# TODO\n+\n+#Output(s)\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# FD Double --- matrix of functional dependencies\n+\n+m_discoverFD = function(Matrix[Double] X)\n+ return(Matrix[Double] FD)\n+{\n+ # allocate output and working sets\n+ n = ncol(X)\n+ FD = matrix(0, n, n)\n+ FDCols = matrix(0, n, n)\n+ FDRows = matrix(0, n, n)\n+\n+ # compute summary statistics (assumes recoded columns)\n+ cm = colMaxs(X)\n+ cm = order(target=t(cm), decreasing=TRUE, index.return=TRUE)\n+\n+ sequence = (nrow(X)*(nrow(X)+1))/2\n+ for(i in 1 : n){\n+ index_i = as.scalar(cm[i,1])\n+ colDist = colDistinct(X[,index_i])\n+ columnSum = sum(X[,index_i])\n+ if(colDist == 1.0)\n+ FDCols[, index_i] = matrix(1, n, 1)\n+ else if(columnSum == sequence)\n+ FDRows[index_i, ] = matrix(1, 1, n)\n+ else {\n+ parfor(j in seq(i+1,ncol(X), 1), check =0){\n+ index_j = as.scalar(cm[j,1])\n+ [A_determines_B, del] = compute_dependency(X[, index_i], X[, index_j]);\n+ if(A_determines_B & del > 0.8)\n+ FD[index_i, index_j] = 1\n+ }\n+ }\n+ }\n+ FD = (FD + FDCols + FDRows) != 0\n+}\n+\n+compute_dependency = function(Matrix[Double] X, Matrix[Double] Y)\n+ return(Boolean A_determines_B, Double delta)\n+{\n+ ctab = table(X, Y)\n+ rowMax = rowMaxs(ctab)\n+ rowMax = removeEmpty(target = rowMax, margin = \"rows\")\n+ rowSum = rowSums(ctab)\n+ rowSumTable = rowSums(ctab != 0)\n+ A_determines_B = (sum(rowSumTable == 1) == colDistinct(X));\n+ delta = sum(rowMax) / sum(rowSum )\n+}\n+\n+colDistinct = function(Matrix[Double] X)\n+return(double distinctItems)\n+{\n+ distinctItems = sum(table(X, 1) != 0)\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"diff": "@@ -78,6 +78,7 @@ public enum Builtins {\nCUMSUMPROD(\"cumsumprod\", false),\nDETECTSCHEMA(\"detectSchema\", false),\nDIAG(\"diag\", false),\n+ DISCOVER_FD(\"discoverFD\", true),\nEIGEN(\"eigen\", false, ReturnType.MULTI_RETURN),\nEXISTS(\"exists\", false),\nEXP(\"exp\", false),\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinFDTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+\n+package org.tugraz.sysds.test.functions.builtin;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.lops.LopProperties;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+\n+public class BuiltinFDTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"functional_dependency\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinFDTest.class.getSimpleName() + \"/\";\n+\n+// private final static double eps = 0.001;\n+// private final static int rows = 1000;\n+// private final static int colsX = 500;\n+// private final static double spSparse = 0.01;\n+// private final static double spDense = 0.7;\n+// private final static int max_iter = 10;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{\"C\"}));\n+ }\n+\n+ @Test\n+ public void testFD1() {\n+ double[][] X = {{7,1,1,2,2,1},{7,2,2,3,2,1},{7,3,1,4,1,1},{7,4,2,5,3,1},{7,5,3,6,5,1}, {7,6,5,1,4,1}};\n+ runFDTests(X, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testFD2() {\n+ double[][] X = {{1,1,1,1,1},{2,1,2,2,1},{3,2,1,1,1},{4,2,2,2,1},{5,3,3,1,1}};\n+ runFDTests(X, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testFD3() {\n+ double[][] X = {{1,1},{2,1},{3,2},{2,2},{4,2}, {5,3}};\n+ runFDTests(X, LopProperties.ExecType.CP);\n+ }\n+ @Test\n+ public void testFD4() {\n+ double[][] X = {{1,1,1,1,1,1,2},{2,1,2,2,1,2,2},{3,2,1,1,1,3,2},{4,2,2,2,1,4,2},{5,3,3,1,1,5,1}};\n+ runFDTests(X, LopProperties.ExecType.CP);\n+ }\n+\n+ private void runFDTests(double [][] X , LopProperties.ExecType instType) {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+ try\n+ {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{\"-args\", input(\"X\")};\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+ runTest(true, false, null, -1);\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/builtin/functional_dependency.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = read($1)\n+C = discoverFD(X)\n+print(sum(C))\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-197] Builtin function for functional dependency discovery
Closes #88. |
49,689 | 30.01.2020 16:28:13 | -3,600 | 06e5de34b65fd5752284980f3a5873317a075a71 | Function results caching updates and bug fixes.
This patch contains -
1. Refactoring of function results caching
2. Code to skip caching if function contains Rand/Sample
3. Few bug fixes. | [
{
"change_type": "MODIFY",
"old_path": "scripts/builtin/steplm.dml",
"new_path": "scripts/builtin/steplm.dml",
"diff": "@@ -69,6 +69,13 @@ return(Matrix[Double] C, Matrix[Double] S) {\ndir = \"forward\";\nthr = 0.001;\n+ Xtmp1 = rand(rows=100, cols=100, sparsity=1.0, seed=1);\n+ betatmp1 = rand(rows=100, cols=1, sparsity=1.0, seed=1);\n+ ytmp1 = Xtmp1 %*% betatmp1;\n+ Xtmp2 = cbind(rand(rows=100, cols=100, sparsity=1.0, seed=1), Xtmp1);\n+ X = Xtmp1;\n+ y = ytmp1;\n+\nprint(\"BEGIN STEPWISE LINEAR REGRESSION SCRIPT\");\nprint(\"Reading X and Y...\");\nX_orig = X;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/DataGenCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/DataGenCPInstruction.java",
"diff": "@@ -377,8 +377,8 @@ public class DataGenCPInstruction extends UnaryCPInstruction {\nDataGenOp.UNSPECIFIED_SEED : DataGenOp.generateRandomSeed();\nint position = (method == DataGenMethod.RAND) ? SEED_POSITION_RAND :\n(method == DataGenMethod.SAMPLE) ? SEED_POSITION_SAMPLE : 0;\n- tmpInstStr = InstructionUtils.replaceOperand(\n- tmpInstStr, position, String.valueOf(runtimeSeed));\n+ tmpInstStr = position != 0 ? InstructionUtils.replaceOperand(\n+ tmpInstStr, position, String.valueOf(runtimeSeed)) : tmpInstStr;\n}\nreturn new LineageItem[]{new LineageItem(output.getName(), tmpInstStr, getOpcode())};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/FunctionCallCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/FunctionCallCPInstruction.java",
"diff": "@@ -28,12 +28,10 @@ import org.tugraz.sysds.lops.Lop;\nimport org.tugraz.sysds.parser.DMLProgram;\nimport org.tugraz.sysds.parser.DataIdentifier;\nimport org.tugraz.sysds.common.Types.DataType;\n-import org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.DMLScriptException;\nimport org.tugraz.sysds.runtime.controlprogram.FunctionProgramBlock;\nimport org.tugraz.sysds.runtime.controlprogram.LocalVariableMap;\n-import org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContextFactory;\nimport org.tugraz.sysds.runtime.instructions.Instruction;\n@@ -41,11 +39,9 @@ import org.tugraz.sysds.runtime.instructions.InstructionUtils;\nimport org.tugraz.sysds.runtime.io.IOUtilFunctions;\nimport org.tugraz.sysds.runtime.lineage.Lineage;\nimport org.tugraz.sysds.runtime.lineage.LineageCache;\n-import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\nimport org.tugraz.sysds.runtime.lineage.LineageItem;\nimport org.tugraz.sysds.runtime.lineage.LineageItemUtils;\n-import org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\n-import org.tugraz.sysds.runtime.meta.MetaData;\n+import org.tugraz.sysds.utils.Statistics;\npublic class FunctionCallCPInstruction extends CPInstruction {\nprivate final String _functionName;\n@@ -224,17 +220,10 @@ public class FunctionCallCPInstruction extends CPInstruction {\n//map lineage of function returns back to calling site\nif( lineage != null ) //unchanged ref\nec.getLineage().set(boundVarName, lineage.get(retVarName));\n-\n- if (!ReuseCacheType.isNone()) {\n- String opcode = _functionName + String.valueOf(i+1);\n- LineageItem li = new LineageItem(_boundOutputNames.get(i), opcode, liInputs);\n- if (boundValue instanceof ScalarObject) //TODO: cache scalar objects\n- LineageCache.removeEntry(li); //remove the placeholder\n- else\n- LineageCache.putValue(li, lineage.get(retVarName), (MatrixObject)boundValue);\n- //TODO: Unmark for caching in compiler if function contains rand()\n- }\n}\n+\n+ //update lineage cache with the functions outputs\n+ LineageCache.putValue(_boundOutputNames, numOutputs, liInputs, _functionName, ec);\n}\n@Override\n@@ -270,44 +259,13 @@ public class FunctionCallCPInstruction extends CPInstruction {\n}\nprivate boolean reuseFunctionOutputs(LineageItem[] liInputs, FunctionProgramBlock fpb, ExecutionContext ec) {\n- if( ReuseCacheType.isNone() )\n- return false;\n-\nint numOutputs = Math.min(_boundOutputNames.size(), fpb.getOutputParams().size());\n- boolean reuse = true;\n- for (int i=0; i< numOutputs; i++) {\n- //String opcode = _functionName + _boundOutputNames.get(i);\n- String opcode = _functionName + String.valueOf(i+1);\n- LineageItem li = new LineageItem(_boundOutputNames.get(i), opcode, liInputs);\n- MatrixBlock cachedValue = LineageCache.reuse(li);\n+ boolean reuse = LineageCache.reuse(_boundOutputNames, numOutputs, liInputs, _functionName, ec);\n- if (cachedValue != null) {\n- String boundVarName = _boundOutputNames.get(i);\n- //convert to matrix object\n- MetaData md = new MetaData(cachedValue.getDataCharacteristics());\n- MatrixObject boundValue = new MatrixObject(ValueType.FP64, boundVarName, md);\n- boundValue.acquireModify(cachedValue);\n- boundValue.release();\n+ if (reuse && DMLScript.STATISTICS)\n+ //decrement the call count for this function\n+ Statistics.maintainCPFuncCallStats(this.getExtendedOpcode());\n- //cleanup existing data bound to output variable name\n- Data exdata = ec.removeVariable(boundVarName);\n- if( exdata != boundValue)\n- ec.cleanupDataObject(exdata);\n-\n- //add/replace data in symbol table\n- ec.setVariable(boundVarName, boundValue);\n-\n- // map original lineage of function return to the calling site\n- LineageItem orig = LineageCache.getNext(li);\n- ec.getLineage().set(boundVarName, orig);\n- }\n- else {\n- // if one output cannot be reused, we need to execute the function\n- // NOTE: all outputs need to be prepared for caching and hence,\n- // we cannot directly return here\n- reuse = false;\n- }\n- }\nreturn reuse;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "package org.tugraz.sysds.runtime.lineage;\nimport org.tugraz.sysds.api.DMLScript;\n+import org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.hops.OptimizerUtils;\nimport org.tugraz.sysds.hops.cost.CostEstimatorStaticRuntime;\nimport org.tugraz.sysds.lops.MMTSJ.MMTSJType;\n@@ -30,15 +31,22 @@ import org.tugraz.sysds.runtime.instructions.Instruction;\nimport org.tugraz.sysds.runtime.instructions.cp.BinaryMatrixMatrixCPInstruction;\nimport org.tugraz.sysds.runtime.instructions.cp.CPInstruction.CPType;\nimport org.tugraz.sysds.runtime.instructions.cp.ComputationCPInstruction;\n+import org.tugraz.sysds.runtime.instructions.cp.Data;\nimport org.tugraz.sysds.runtime.instructions.cp.MMTSJCPInstruction;\nimport org.tugraz.sysds.runtime.instructions.cp.ParameterizedBuiltinCPInstruction;\n+import org.tugraz.sysds.runtime.instructions.cp.ScalarObject;\nimport org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\n+import org.tugraz.sysds.runtime.matrix.data.InputInfo;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\n+import org.tugraz.sysds.runtime.matrix.data.OutputInfo;\n+import org.tugraz.sysds.runtime.meta.MetaDataFormat;\nimport org.tugraz.sysds.runtime.util.LocalFileUtils;\nimport java.io.IOException;\n+import java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.HashSet;\n+import java.util.List;\nimport java.util.Map;\npublic class LineageCache {\n@@ -98,10 +106,54 @@ public class LineageCache {\n//create a placeholder if no reuse to avoid redundancy\n//(e.g., concurrent threads that try to start the computation)\nputIntern(item, null, 0);\n+ //FIXME: parfor - every thread gets different function names\n}\nreturn d;\n}\n+ public static boolean reuse(List<String> outputs, int numOutputs, LineageItem[] liInputs, String name, ExecutionContext ec)\n+ {\n+ if( ReuseCacheType.isNone() )\n+ return false;\n+\n+ boolean reuse = true;\n+ for (int i=0; i<numOutputs; i++) {\n+ String opcode = name + String.valueOf(i+1);\n+ LineageItem li = new LineageItem(outputs.get(i), opcode, liInputs);\n+ MatrixBlock cachedValue = LineageCache.reuse(li);\n+ //TODO: handling of recursive calls\n+\n+ if (cachedValue != null) {\n+ String boundVarName = outputs.get(i);\n+ //convert to matrix object\n+ MetaDataFormat md = new MetaDataFormat(cachedValue.getDataCharacteristics(),\n+ OutputInfo.BinaryCellOutputInfo, InputInfo.BinaryCellInputInfo);\n+ MatrixObject boundValue = new MatrixObject(ValueType.FP64, boundVarName, md);\n+ boundValue.acquireModify(cachedValue);\n+ boundValue.release();\n+\n+ //cleanup existing data bound to output variable name\n+ Data exdata = ec.removeVariable(boundVarName);\n+ if( exdata != boundValue)\n+ ec.cleanupDataObject(exdata);\n+\n+ //add/replace data in symbol table\n+ ec.setVariable(boundVarName, boundValue);\n+\n+ // map original lineage of function return to the calling site\n+ LineageItem orig = LineageCache.getNext(li);\n+ ec.getLineage().set(boundVarName, orig);\n+ }\n+ else {\n+ // if one output cannot be reused, we need to execute the function\n+ // NOTE: all outputs need to be prepared for caching and hence,\n+ // we cannot directly return here\n+ reuse = false;\n+ }\n+ }\n+ return reuse;\n+ }\n+\npublic static LineageItem getNext(LineageItem firstItem) {\nfor(Map.Entry<LineageItem, Entry> entry : _cache.entrySet()) {\nif (!(entry.getKey().equals(firstItem)) && !entry.getValue().isNullVal() &&\n@@ -158,6 +210,29 @@ public class LineageCache {\n}\n+ public static void putValue(List<String> outputs, int numOutputs, LineageItem[] liInputs, String name, ExecutionContext ec)\n+ {\n+ if( ReuseCacheType.isNone() )\n+ return;\n+\n+ for (int i=0; i<numOutputs; i++) {\n+ if (!ReuseCacheType.isNone()) {\n+ String opcode = name + String.valueOf(i+1);\n+ LineageItem li = new LineageItem(outputs.get(i), opcode, liInputs);\n+ String boundVarName = outputs.get(i);\n+ LineageItem boundLI = ec.getLineage().get(boundVarName);\n+ Data boundValue = ec.getVariable(boundVarName);\n+ //if (LineageItemUtils.containsRandDataGen(liInputs, ec.getLineage().get(boundVarName)))\n+ if (LineageItemUtils.containsRandDataGen(new HashSet<>(Arrays.asList(liInputs)), boundLI)\n+ || boundValue instanceof ScalarObject) //TODO: cache scalar objects\n+ LineageCache.removeEntry(li); //remove the placeholder\n+ else\n+ LineageCache.putValue(li, boundLI, (MatrixObject)boundValue);\n+ //TODO: Unmark for caching in compiler if function contains rand()\n+ }\n+ }\n+ }\n+\nprivate static void putIntern(LineageItem key, MatrixBlock value, double compcost) {\nif (_cache.containsKey(key))\n//can come here if reuse_partial option is enabled\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"diff": "@@ -59,6 +59,7 @@ import java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.HashMap;\n+import java.util.HashSet;\nimport java.util.Map;\nimport java.util.stream.Collectors;\n@@ -419,4 +420,40 @@ public class LineageItemUtils {\nret[i] = operands.get(item.getInputs()[i].getId());\nreturn ret;\n}\n+\n+ public static boolean containsRandDataGen(HashSet<LineageItem> entries, LineageItem root) {\n+ boolean isRand = false;\n+ if (entries.contains(root))\n+ return false;\n+ if (isNonDeterministic(root))\n+ isRand |= true;\n+ if (!root.isLeaf())\n+ for (LineageItem input : root.getInputs())\n+ isRand = isRand ? true : containsRandDataGen(entries, input);\n+ return isRand;\n+ //TODO: unmark for caching in compile time\n+ }\n+\n+ private static boolean isNonDeterministic(LineageItem li) {\n+ if (li.getType() != LineageItemType.Creation)\n+ return false;\n+\n+ boolean isND = false;\n+ DataGenCPInstruction ins = (DataGenCPInstruction)InstructionParser.parseSingleInstruction(li.getData());\n+ switch(li.getOpcode().toUpperCase())\n+ {\n+ case \"RAND\":\n+ if ((ins.getMinValue() != ins.getMaxValue()) || (ins.getSparsity() != 1))\n+ isND = true;\n+ break;\n+ case \"SAMPLE\":\n+ isND = true;\n+ break;\n+ default:\n+ isND = false;\n+ break;\n+ }\n+ //TODO: add 'read' in this list\n+ return isND;\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageMap.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageMap.java",
"diff": "@@ -218,8 +218,7 @@ public class LineageMap {\nremoveLineageItem(li.getInputs()[0].getName());\nelse {\n//remove from old and move to new key\n- _traces.put(li.getName(),\n- _traces.remove(li.getInputs()[0].getName()));\n+ _traces.put(li.getName(), li.getInputs()[0]);\n}\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/utils/Statistics.java",
"new_path": "src/main/java/org/tugraz/sysds/utils/Statistics.java",
"diff": "@@ -640,6 +640,12 @@ public class Statistics\ntmp.count.increment();\n}\n+ public static void maintainCPFuncCallStats(String instName) {\n+ InstStats tmp = _instStats.get(instName);\n+ if (tmp != null) //tmp should never be null\n+ tmp.count.decrement();\n+ }\n+\npublic static Set<String> getCPHeavyHitterOpCodes() {\nreturn _instStats.keySet();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/FunctionFullReuseTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/FunctionFullReuseTest.java",
"diff": "@@ -37,6 +37,7 @@ public class FunctionFullReuseTest extends AutomatedTestBase {\nprotected static final String TEST_NAME2 = \"FunctionFullReuse2\";\nprotected static final String TEST_NAME3 = \"FunctionFullReuse3\";\nprotected static final String TEST_NAME4 = \"FunctionFullReuse4\";\n+ protected static final String TEST_NAME5 = \"FunctionFullReuse5\";\nprotected String TEST_CLASS_DIR = TEST_DIR + FunctionFullReuseTest.class.getSimpleName() + \"/\";\n@Override\n@@ -46,6 +47,7 @@ public class FunctionFullReuseTest extends AutomatedTestBase {\naddTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2));\naddTestConfiguration(TEST_NAME3, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME3));\naddTestConfiguration(TEST_NAME4, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME4));\n+ addTestConfiguration(TEST_NAME5, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME5));\n}\n@Test\n@@ -68,6 +70,11 @@ public class FunctionFullReuseTest extends AutomatedTestBase {\ntestLineageTrace(TEST_NAME4);\n}\n+ /*@Test\n+ public void testStepLM() {\n+ testLineageTrace(TEST_NAME5);\n+ }*/\n+\npublic void testLineageTrace(String testname) {\nboolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\nboolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n@@ -97,7 +104,7 @@ public class FunctionFullReuseTest extends AutomatedTestBase {\nproArgs.clear();\nproArgs.add(\"-stats\");\nproArgs.add(\"-lineage\");\n- proArgs.add(ReuseCacheType.REUSE_FULL.name().toLowerCase());\n+ proArgs.add(ReuseCacheType.REUSE_HYBRID.name().toLowerCase());\nproArgs.add(\"-args\");\nproArgs.add(output(\"X\"));\nprogramArgs = proArgs.toArray(new String[proArgs.size()]);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/FunctionFullReuse5.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+# Increase rows and cols for better performance gains\n+\n+X = rand(rows=100, cols=100, sparsity=1.0, seed=1);\n+y = X %*% rand(rows=100, cols=1, sparsity=1.0, seed=1);\n+R = matrix(0, 1, 2);\n+\n+[C, S] = steplm(X=X, y=y, icpt=1);\n+R[1,1] = sum(C)\n+R[1,2] = sum(S)\n+\n+write(R, $1, format=\"text\");\n"
}
] | Java | Apache License 2.0 | apache/systemds | Function results caching updates and bug fixes.
This patch contains -
1. Refactoring of function results caching
2. Code to skip caching if function contains Rand/Sample
3. Few bug fixes. |
49,689 | 31.01.2020 11:34:37 | -3,600 | d97863804a115d562224fa69a9f7b4b00c0562a5 | Extends lineagecache statistics.
Added entry for multilevel caching
Fixed bugs in rewrite stats | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/FunctionCallCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/FunctionCallCPInstruction.java",
"diff": "@@ -39,6 +39,7 @@ import org.tugraz.sysds.runtime.instructions.InstructionUtils;\nimport org.tugraz.sysds.runtime.io.IOUtilFunctions;\nimport org.tugraz.sysds.runtime.lineage.Lineage;\nimport org.tugraz.sysds.runtime.lineage.LineageCache;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheStatistics;\nimport org.tugraz.sysds.runtime.lineage.LineageItem;\nimport org.tugraz.sysds.runtime.lineage.LineageItemUtils;\nimport org.tugraz.sysds.utils.Statistics;\n@@ -262,10 +263,11 @@ public class FunctionCallCPInstruction extends CPInstruction {\nint numOutputs = Math.min(_boundOutputNames.size(), fpb.getOutputParams().size());\nboolean reuse = LineageCache.reuse(_boundOutputNames, numOutputs, liInputs, _functionName, ec);\n- if (reuse && DMLScript.STATISTICS)\n+ if (reuse && DMLScript.STATISTICS) {\n//decrement the call count for this function\nStatistics.maintainCPFuncCallStats(this.getExtendedOpcode());\n-\n+ LineageCacheStatistics.incrementFuncHits();\n+ }\nreturn reuse;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "@@ -84,6 +84,9 @@ public class LineageCache {\nif (LineageCacheConfig.getCacheType().isPartialReuse())\nreuse |= LineageRewriteReuse.executeRewrites(inst, ec);\n+ if (reuse && DMLScript.STATISTICS)\n+ LineageCacheStatistics.incrementInstHits();\n+\n//create a placeholder if no reuse to avoid redundancy\n//(e.g., concurrent threads that try to start the computation)\nif( ! reuse )\n@@ -303,7 +306,8 @@ public class LineageCache {\n// TODO: Move this to the new class LineageCacheConfig and extend\nreturn inst.getOpcode().equalsIgnoreCase(\"tsmm\")\n|| inst.getOpcode().equalsIgnoreCase(\"ba+*\")\n- || (inst.getOpcode().equalsIgnoreCase(\"*\") &&\n+ || ((inst.getOpcode().equalsIgnoreCase(\"*\")\n+ || inst.getOpcode().equalsIgnoreCase(\"/\")) &&\ninst instanceof BinaryMatrixMatrixCPInstruction) //TODO support scalar\n|| inst.getOpcode().equalsIgnoreCase(\"rightIndex\")\n|| inst.getOpcode().equalsIgnoreCase(\"groupedagg\")\n@@ -418,12 +422,12 @@ public class LineageCache {\nbreak;\n}\n- case Binary:\n+ case Binary: //*, /\n{\nMatrixObject mo1 = ec.getMatrixObject(((ComputationCPInstruction)inst).input1);\nlong r1 = mo1.getNumRows();\nlong c1 = mo1.getNumColumns();\n- if (inst.getOpcode().equalsIgnoreCase(\"*\"))\n+ if (inst.getOpcode().equalsIgnoreCase(\"*\") || inst.getOpcode().equalsIgnoreCase(\"/\"))\n// considering the dimensions of inputs and the output are same\nnflops = r1 * c1;\nelse if (inst.getOpcode().equalsIgnoreCase(\"solve\"))\n@@ -431,7 +435,7 @@ public class LineageCache {\nbreak;\n}\n- case MatrixIndexing:\n+ case MatrixIndexing: //rightIndex\n{\nMatrixObject mo1 = ec.getMatrixObject(((ComputationCPInstruction)inst).input1);\nlong r1 = mo1.getNumRows();\n@@ -444,7 +448,7 @@ public class LineageCache {\nbreak;\n}\n- case ParameterizedBuiltin:\n+ case ParameterizedBuiltin: //groupedagg (sum, count)\n{\nString opcode = ((ParameterizedBuiltinCPInstruction)inst).getOpcode();\nHashMap<String, String> params = ((ParameterizedBuiltinCPInstruction)inst).getParameterMap();\n@@ -475,7 +479,7 @@ public class LineageCache {\nbreak;\n}\n- case Append:\n+ case Append: //cbind, rbind\n{\nMatrixObject mo1 = ec.getMatrixObject(((ComputationCPInstruction)inst).input1);\nMatrixObject mo2 = ec.getMatrixObject(((ComputationCPInstruction)inst).input2);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCacheStatistics.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCacheStatistics.java",
"diff": "@@ -26,6 +26,8 @@ public class LineageCacheStatistics {\nprivate static final LongAdder _numHitsMem = new LongAdder();\nprivate static final LongAdder _numHitsFS = new LongAdder();\nprivate static final LongAdder _numHitsDel = new LongAdder();\n+ private static final LongAdder _numHitsInst = new LongAdder();\n+ private static final LongAdder _numHitsFunc = new LongAdder();\nprivate static final LongAdder _numWritesMem = new LongAdder();\nprivate static final LongAdder _numWritesFS = new LongAdder();\nprivate static final LongAdder _numRewrites = new LongAdder();\n@@ -39,6 +41,8 @@ public class LineageCacheStatistics {\n_numHitsMem.reset();\n_numHitsFS.reset();\n_numHitsDel.reset();\n+ _numHitsInst.reset();\n+ _numHitsFunc.reset();\n_numWritesMem.reset();\n_numWritesFS.reset();\n_numRewrites.reset();\n@@ -64,6 +68,16 @@ public class LineageCacheStatistics {\n_numHitsDel.increment();\n}\n+ public static void incrementInstHits() {\n+ // Number of times single instruction results are reused (full and partial).\n+ _numHitsInst.increment();\n+ }\n+\n+ public static void incrementFuncHits() {\n+ // Number of times function results are reused.\n+ _numHitsFunc.increment();\n+ }\n+\npublic static void incrementMemWrites() {\n// Number of times written in cache.\n_numWritesMem.increment();\n@@ -95,7 +109,7 @@ public class LineageCacheStatistics {\n}\npublic static void incrementPRewriteTime(long delta) {\n- // Total time spent estimating computation and disk spill costs.\n+ // Total time spent executing lineage rewrites.\n_ctimeRewrite.add(delta);\n}\n@@ -114,6 +128,14 @@ public class LineageCacheStatistics {\nreturn sb.toString();\n}\n+ public static String displayMultiLvlHits() {\n+ StringBuilder sb = new StringBuilder();\n+ sb.append(_numHitsInst.longValue());\n+ sb.append(\"/\");\n+ sb.append(_numHitsFunc.longValue());\n+ return sb.toString();\n+ }\n+\npublic static String displayWtrites() {\nStringBuilder sb = new StringBuilder();\nsb.append(_numWritesMem.longValue());\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageRewriteReuse.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageRewriteReuse.java",
"diff": "@@ -71,21 +71,21 @@ public class LineageRewriteReuse\nDMLScript.EXPLAIN = ExplainType.NONE;\n//check applicability and apply rewrite\n- //tsmm(cbind(X, deltaX)) -> rbind(cbind(C, t(X) %*% deltaX), cbind(t(deltaX) %*%X, tsmm(deltaX))), where C = tsmm(X)\n+ //tsmm(cbind(X, deltaX)) -> rbind(cbind(tsmm(X), t(X) %*% deltaX), cbind(t(deltaX) %*%X, tsmm(deltaX)))\nArrayList<Instruction> newInst = rewriteTsmmCbind(curr, ec, lrwec);\n//tsmm(cbind(cbind(X, deltaX), ones)) -> TODO\nnewInst = (newInst == null) ? rewriteTsmm2Cbind(curr, ec, lrwec) : newInst;\n- //tsmm(rbind(X, deltaX)) -> C + tsmm(deltaX), where C = tsmm(X)\n+ //tsmm(rbind(X, deltaX)) -> tsmm(X) + tsmm(deltaX)\nnewInst = (newInst == null) ? rewriteTsmmRbind(curr, ec, lrwec) : newInst;\n- //rbind(X,deltaX) %*% Y -> rbind(C, deltaX %*% Y), C = X %*% Y\n+ //rbind(X,deltaX) %*% Y -> rbind(X %*% Y, deltaX %*% Y)\nnewInst = (newInst == null) ? rewriteMatMulRbindLeft(curr, ec, lrwec) : newInst;\n- //X %*% cbind(Y,deltaY)) -> cbind(C, X %*% deltaY), where C = X %*% Y\n+ //X %*% cbind(Y,deltaY)) -> cbind(X %*% Y, X %*% deltaY)\nnewInst = (newInst == null) ? rewriteMatMulCbindRight(curr, ec, lrwec) : newInst;\n- //rbind(X, deltaX) * rbind(Y, deltaY) -> rbind(C, deltaX * deltaY), where C = X * Y\n+ //rbind(X, deltaX) * rbind(Y, deltaY) -> rbind(X * Y, deltaX * deltaY)\nnewInst = (newInst == null) ? rewriteElementMulRbind(curr, ec, lrwec) : newInst;\n- //cbind(X, deltaX) * cbind(Y, deltaY) -> cbind(C, deltaX * deltaY), where C = X * Y\n+ //cbind(X, deltaX) * cbind(Y, deltaY) -> cbind(X * Y, deltaX * deltaY)\nnewInst = (newInst == null) ? rewriteElementMulCbind(curr, ec, lrwec) : newInst;\n- //aggregate(target=X+deltaX,...) = cbind(C, aggregate(target=deltaX,...)) where C = aggregate(target=X,...)\n+ //aggregate(target=cbind(X, deltaX,...) = cbind(aggregate(target=X,...), aggregate(target=deltaX,...)) for same agg function\nnewInst = (newInst == null) ? rewriteAggregateCbind(curr, ec, lrwec) : newInst;\nif (newInst == null)\n@@ -149,14 +149,15 @@ public class LineageRewriteReuse\nBinaryOp lrwHop= HopRewriteUtils.createBinary(rowOne, rowTwo, OpOp2.RBIND);\nDataOp lrwWrite = HopRewriteUtils.createTransientWrite(LR_VAR, lrwHop);\n+ // generate runtime instructions\n+ LOG.debug(\"LINEAGE REWRITE rewriteTsmmCbind APPLIED\");\n+ ArrayList<Instruction> inst = genInst(lrwWrite, lrwec);\n+\nif (DMLScript.STATISTICS) {\nLineageCacheStatistics.incrementPRewriteTime(System.nanoTime() - t0);\nLineageCacheStatistics.incrementPRewrites();\n}\n-\n- // generate runtime instructions\n- LOG.debug(\"LINEAGE REWRITE rewriteTsmmCbind APPLIED\");\n- return genInst(lrwWrite, lrwec);\n+ return inst;\n}\nprivate static ArrayList<Instruction> rewriteTsmmRbind (Instruction curr, ExecutionContext ec, ExecutionContext lrwec)\n@@ -198,7 +199,13 @@ public class LineageRewriteReuse\n// generate runtime instructions\nLOG.debug(\"LINEAGE REWRITE rewriteTsmmRbind APPLIED\");\n- return genInst(lrwWrite, lrwec);\n+ ArrayList<Instruction> inst = genInst(lrwWrite, lrwec);\n+\n+ if (DMLScript.STATISTICS) {\n+ LineageCacheStatistics.incrementPRewriteTime(System.nanoTime() - t0);\n+ LineageCacheStatistics.incrementPRewrites();\n+ }\n+ return inst;\n}\nprivate static ArrayList<Instruction> rewriteTsmm2Cbind (Instruction curr, ExecutionContext ec, ExecutionContext lrwec)\n@@ -259,7 +266,13 @@ public class LineageRewriteReuse\n// generate runtime instructions\nLOG.debug(\"LINEAGE REWRITE rewriteTsmm2Cbind APPLIED\");\n- return genInst(lrwWrite, lrwec);\n+ ArrayList<Instruction> inst = genInst(lrwWrite, lrwec);\n+\n+ if (DMLScript.STATISTICS) {\n+ LineageCacheStatistics.incrementPRewriteTime(System.nanoTime() - t0);\n+ LineageCacheStatistics.incrementPRewrites();\n+ }\n+ return inst;\n}\nprivate static ArrayList<Instruction> rewriteMatMulRbindLeft (Instruction curr, ExecutionContext ec, ExecutionContext lrwec)\n@@ -302,7 +315,13 @@ public class LineageRewriteReuse\n// generate runtime instructions\nLOG.debug(\"LINEAGE REWRITE rewriteMetMulRbindLeft APPLIED\");\n- return genInst(lrwWrite, lrwec);\n+ ArrayList<Instruction> inst = genInst(lrwWrite, lrwec);\n+\n+ if (DMLScript.STATISTICS) {\n+ LineageCacheStatistics.incrementPRewriteTime(System.nanoTime() - t0);\n+ LineageCacheStatistics.incrementPRewrites();\n+ }\n+ return inst;\n}\nprivate static ArrayList<Instruction> rewriteMatMulCbindRight (Instruction curr, ExecutionContext ec, ExecutionContext lrwec)\n@@ -345,7 +364,13 @@ public class LineageRewriteReuse\n// generate runtime instructions\nLOG.debug(\"LINEAGE REWRITE rewriteMatMulCbindRight APPLIED\");\n- return genInst(lrwWrite, lrwec);\n+ ArrayList<Instruction> inst = genInst(lrwWrite, lrwec);\n+\n+ if (DMLScript.STATISTICS) {\n+ LineageCacheStatistics.incrementPRewriteTime(System.nanoTime() - t0);\n+ LineageCacheStatistics.incrementPRewrites();\n+ }\n+ return inst;\n}\nprivate static ArrayList<Instruction> rewriteElementMulRbind (Instruction curr, ExecutionContext ec, ExecutionContext lrwec)\n@@ -399,7 +424,13 @@ public class LineageRewriteReuse\n// generate runtime instructions\nLOG.debug(\"LINEAGE REWRITE rewriteElementMulRbind APPLIED\");\n- return genInst(lrwWrite, lrwec);\n+ ArrayList<Instruction> inst = genInst(lrwWrite, lrwec);\n+\n+ if (DMLScript.STATISTICS) {\n+ LineageCacheStatistics.incrementPRewriteTime(System.nanoTime() - t0);\n+ LineageCacheStatistics.incrementPRewrites();\n+ }\n+ return inst;\n}\nprivate static ArrayList<Instruction> rewriteElementMulCbind (Instruction curr, ExecutionContext ec, ExecutionContext lrwec)\n@@ -453,7 +484,13 @@ public class LineageRewriteReuse\n// generate runtime instructions\nLOG.debug(\"LINEAGE REWRITE rewriteElementMulCbind APPLIED\");\n- return genInst(lrwWrite, lrwec);\n+ ArrayList<Instruction> inst = genInst(lrwWrite, lrwec);\n+\n+ if (DMLScript.STATISTICS) {\n+ LineageCacheStatistics.incrementPRewriteTime(System.nanoTime() - t0);\n+ LineageCacheStatistics.incrementPRewrites();\n+ }\n+ return inst;\n}\nprivate static ArrayList<Instruction> rewriteAggregateCbind (Instruction curr, ExecutionContext ec, ExecutionContext lrwec)\n@@ -507,7 +544,13 @@ public class LineageRewriteReuse\n// generate runtime instructions\nLOG.debug(\"LINEAGE REWRITE rewriteElementMulCbind APPLIED\");\n- return genInst(lrwWrite, lrwec);\n+ ArrayList<Instruction> inst = genInst(lrwWrite, lrwec);\n+\n+ if (DMLScript.STATISTICS) {\n+ LineageCacheStatistics.incrementPRewriteTime(System.nanoTime() - t0);\n+ LineageCacheStatistics.incrementPRewrites();\n+ }\n+ return inst;\n}\n/*------------------------REWRITE APPLICABILITY CHECKS-------------------------*/\n@@ -740,6 +783,7 @@ public class LineageRewriteReuse\nDMLScript.EXPLAIN = ExplainType.NONE;\ntry {\n+ long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;\n//execute instructions\nBasicProgramBlock pb = getProgramBlock();\npb.setInstructions(newInst);\n@@ -747,6 +791,8 @@ public class LineageRewriteReuse\nLineageCacheConfig.shutdownReuse();\npb.execute(lrwec);\nLineageCacheConfig.restartReuse(oldReuseOption);\n+ if (DMLScript.STATISTICS)\n+ LineageCacheStatistics.incrementPRwExecTime(System.nanoTime()-t0);\n}\ncatch (Exception e) {\nthrow new DMLRuntimeException(\"Error executing lineage rewrites\" , e);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/utils/Statistics.java",
"new_path": "src/main/java/org/tugraz/sysds/utils/Statistics.java",
"diff": "@@ -946,12 +946,13 @@ public class Statistics\nsb.append(\"Functions recompile time:\\t\" + String.format(\"%.3f\", ((double)getFunRecompileTime())/1000000000) + \" sec.\\n\");\n}\nif (DMLScript.LINEAGE && !ReuseCacheType.isNone()) {\n- sb.append(\"LineageCache hits (Mem/FS/Del): \" + LineageCacheStatistics.displayHits() + \".\\n\");\n- sb.append(\"LineageCache writes (Mem/FS): \\t\" + LineageCacheStatistics.displayWtrites() + \".\\n\");\n- sb.append(\"LineageCache FStimes (Rd/Wr): \\t\" + LineageCacheStatistics.displayTime() + \" sec.\\n\");\n- sb.append(\"LineageCache costing time: \\t\" + LineageCacheStatistics.displayCostingTime() + \" sec.\\n\");\n- sb.append(\"LineageCache Rewrites: \\t\" + LineageCacheStatistics.displayRewrites() + \".\\n\");\n- sb.append(\"LineageCache RWtime (Com/Ex): \\t\" + LineageCacheStatistics.displayRewriteTime() + \" sec.\\n\");\n+ sb.append(\"LinCache hits (Mem/FS/Del): \\t\" + LineageCacheStatistics.displayHits() + \".\\n\");\n+ sb.append(\"LinCache MultiLevel (Ins/Fn): \\t\" + LineageCacheStatistics.displayMultiLvlHits() + \".\\n\");\n+ sb.append(\"LinCache writes (Mem/FS): \\t\" + LineageCacheStatistics.displayWtrites() + \".\\n\");\n+ sb.append(\"LinCache FStimes (Rd/Wr): \\t\" + LineageCacheStatistics.displayTime() + \" sec.\\n\");\n+ sb.append(\"LinCache costing time: \\t\" + LineageCacheStatistics.displayCostingTime() + \" sec.\\n\");\n+ sb.append(\"LinCache Rewrites: \\t\\t\" + LineageCacheStatistics.displayRewrites() + \".\\n\");\n+ sb.append(\"LinCache RWtime (Com/Ex): \\t\" + LineageCacheStatistics.displayRewriteTime() + \" sec.\\n\");\n}\nif( ConfigurationManager.isCodegenEnabled() ) {\nsb.append(\"Codegen compile (DAG,CP,JC):\\t\" + getCodegenDAGCompile() + \"/\"\n"
}
] | Java | Apache License 2.0 | apache/systemds | Extends lineagecache statistics.
- Added entry for multilevel caching
- Fixed bugs in rewrite stats |
49,706 | 28.01.2020 14:56:38 | -3,600 | b3f4d28d2ce823efe2bc12717fdb15396e6c2d74 | [MINOR] Upgrading URL handling for initiating federated commands
Closes | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/conf/DMLConfig.java",
"new_path": "src/main/java/org/tugraz/sysds/conf/DMLConfig.java",
"diff": "@@ -88,6 +88,8 @@ public class DMLConfig\npublic static final String PRINT_GPU_MEMORY_INFO = \"sysds.gpu.print.memoryInfo\";\npublic static final String EVICTION_SHADOW_BUFFERSIZE = \"sysds.gpu.eviction.shadow.bufferSize\";\n+ public static final String DEFAULT_FEDERATED_PORT = \"25501\";\n+\n//internal config\npublic static final String DEFAULT_SHARED_DIR_PERMISSION = \"777\"; //for local fs and DFS\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/InitFEDInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/InitFEDInstruction.java",
"diff": "@@ -19,6 +19,7 @@ package org.tugraz.sysds.runtime.instructions.fed;\nimport org.apache.commons.lang3.tuple.ImmutablePair;\nimport org.apache.commons.lang3.tuple.Pair;\nimport org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.conf.DMLConfig;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\n@@ -34,14 +35,14 @@ import org.tugraz.sysds.runtime.instructions.cp.StringObject;\nimport java.net.InetAddress;\nimport java.net.InetSocketAddress;\n+import java.net.MalformedURLException;\n+import java.net.URL;\nimport java.net.UnknownHostException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.TreeMap;\nimport java.util.concurrent.Future;\n-import java.util.regex.Matcher;\n-import java.util.regex.Pattern;\npublic class InitFEDInstruction extends FEDInstruction {\nprivate CPOperand _addresses, _ranges, _output;\n@@ -55,7 +56,8 @@ public class InitFEDInstruction extends FEDInstruction {\npublic static InitFEDInstruction parseInstruction(String str) {\nString[] parts = InstructionUtils.getInstructionPartsWithValueType(str);\n- // We need 3 parts: Opcode, Addresses (list of Strings with url/ip:port/filepath), ranges and the output Operand\n+ // We need 4 parts: Opcode, Addresses (list of Strings with\n+ // url/ip:port/filepath), ranges and the output Operand\nif (parts.length != 4)\nthrow new DMLRuntimeException(\"Invalid number of operands in federated instruction: \" + str);\nString opcode = parts[0];\n@@ -74,31 +76,26 @@ public class InitFEDInstruction extends FEDInstruction {\nList<Pair<FederatedRange, FederatedData>> feds = new ArrayList<>();\nif (addresses.getLength() * 2 != ranges.getLength())\n- throw new DMLRuntimeException(\"Federated read needs twice the amount of addresses as ranges \" +\n- \"(begin and end): addresses=\" + addresses.getLength() + \" ranges=\" + ranges.getLength());\n+ throw new DMLRuntimeException(\"Federated read needs twice the amount of addresses as ranges \"\n+ + \"(begin and end): addresses=\" + addresses.getLength() + \" ranges=\" + ranges.getLength());\nlong[] usedDims = new long[] { 0, 0 };\nfor (int i = 0; i < addresses.getLength(); i++) {\nData addressData = addresses.getData().get(i);\nif (addressData instanceof StringObject) {\n- String address = ((StringObject) addressData).getStringValue();\n+\n// We split address into url/ip, the port and file path of file to read\n- String urlRegex = \"^([-a-zA-Z0-9@]+(?:\\\\.[a-zA-Z0-9]+)*)\";\n- String portRegex = \":([0-9]+)\";\n- String filepathRegex = \"((?:/[\\\\w-]+)*/[\\\\w-.]+)/?$\";\n- Pattern compiled = Pattern.compile(urlRegex + portRegex + filepathRegex);\n- Matcher matcher = compiled.matcher(address);\n- if( matcher.matches() ) {\n- // matches: 0 whole match, 1 host address, 2 port, 3 filepath\n- String host = matcher.group(1);\n- int port = Integer.parseInt(matcher.group(2));\n- String filepath = matcher.group(3).substring(1);\n- // get begin and end ranges\n+ String[] parsedValues = parseURL(((StringObject) addressData).getStringValue());\n+ String host = parsedValues[0];\n+ int port = Integer.parseInt(parsedValues[1]);\n+ String filePath = parsedValues[2];\n+ // get beginning and end of data ranges\nList<Data> rangesData = ranges.getData();\nData beginData = rangesData.get(i * 2);\nData endData = rangesData.get(i * 2 + 1);\nif (beginData.getDataType() != Types.DataType.LIST || endData.getDataType() != Types.DataType.LIST)\n- throw new DMLRuntimeException(\"Federated read ranges (lower, upper) have to be lists of dimensions\");\n+ throw new DMLRuntimeException(\n+ \"Federated read ranges (lower, upper) have to be lists of dimensions\");\nList<Data> beginDimsData = ((ListObject) beginData).getData();\nList<Data> endDimsData = ((ListObject) endData).getData();\n@@ -113,19 +110,13 @@ public class InitFEDInstruction extends FEDInstruction {\nusedDims[1] = Math.max(usedDims[1], endDims[1]);\ntry {\nFederatedData federatedData = new FederatedData(\n- new InetSocketAddress(InetAddress.getByName(host), port), filepath);\n+ new InetSocketAddress(InetAddress.getByName(host), port), filePath);\nfeds.add(new ImmutablePair<>(new FederatedRange(beginDims, endDims), federatedData));\n- }\n- catch (UnknownHostException e) {\n+ } catch (UnknownHostException e) {\nthrow new DMLRuntimeException(\"federated host was unknown: \" + host);\n}\n- }\n- else {\n- throw new DMLRuntimeException(\"federated address `\" + address + \"` does not fit required pattern \" +\n- \"of \\\"host:port/directory\\\"\");\n- }\n- }\n- else {\n+\n+ } else {\nthrow new DMLRuntimeException(\"federated instruction only takes strings as addresses\");\n}\n}\n@@ -134,6 +125,40 @@ public class InitFEDInstruction extends FEDInstruction {\nfederate(output, feds);\n}\n+ public static String[] parseURL(String input) {\n+ try {\n+ // Artificially making it http protocol.\n+ // This is to avoid malformed address error in the URL passing.\n+ // TODO: Construct new protocol name for Federated communication\n+ URL address = new URL(\"http://\" + input);\n+ String host = address.getHost();\n+ if (host.length() == 0)\n+ throw new IllegalArgumentException(\"Missing Host name for federated address\");\n+ // The current system does not support ipv6, only ipv4.\n+ // TODO: Support IPV6 address for Federated communication\n+ String ipRegex = \"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$\";\n+ if (host.matches(\"^\\\\d+\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+$\") && !host.matches(ipRegex))\n+ throw new IllegalArgumentException(\"Input Host address looks like an IP address but is outside range\");\n+ String port = Integer.toString(address.getPort());\n+ if (port.equals(\"-1\"))\n+ port = DMLConfig.DEFAULT_FEDERATED_PORT;\n+ String filePath = address.getPath();\n+ if (filePath.length() == 0)\n+ throw new IllegalArgumentException(\"Missing File path for federated address\");\n+\n+ if (address.getQuery() != null)\n+ throw new IllegalArgumentException(\"Query is not supported\");\n+\n+ if (address.getRef() != null)\n+ throw new IllegalArgumentException(\"Reference is not supported\");\n+\n+ return new String[] { host, port, filePath };\n+ } catch (MalformedURLException e) {\n+ throw new IllegalArgumentException(\"federated address `\" + input\n+ + \"` does not fit required URL pattern of \\\"host:port/directory\\\"\", e);\n+ }\n+ }\n+\npublic void federate(MatrixObject output, List<Pair<FederatedRange, FederatedData>> workers) {\nMap<FederatedRange, FederatedData> fedMapping = new TreeMap<>();\nfor (Pair<FederatedRange, FederatedData> t : workers) {\n@@ -162,12 +187,10 @@ public class InitFEDInstruction extends FEDInstruction {\nelse\nthrow new DMLRuntimeException(response.getErrorMessage());\n}\n- }\n- catch (Exception e) {\n+ } catch (Exception e) {\nthrow new DMLRuntimeException(\"Federation initialization failed\", e);\n}\n- output.getDataCharacteristics().setNonZeros(\n- output.getNumColumns() * output.getNumRows());\n+ output.getDataCharacteristics().setNonZeros(output.getNumColumns() * output.getNumRows());\noutput.setFedMapping(fedMapping);\n}\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Upgrading URL handling for initiating federated commands
Closes #90 |
49,693 | 27.01.2020 12:55:17 | -3,600 | ce0ae2707ad5b021be8414e37f63218721517f42 | [BUGFIX] two more try-block issues fixed | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/api/jmlc/Connection.java",
"new_path": "src/main/java/org/tugraz/sysds/api/jmlc/Connection.java",
"diff": "@@ -90,6 +90,7 @@ public class Connection implements Closeable\n{\nprivate final DMLConfig _dmlconf;\nprivate final CompilerConfig _cconf;\n+ private static FileSystem fs = null;\n/**\n* Connection constructor, the starting point for any other JMLC API calls.\n@@ -310,9 +311,9 @@ public class Connection implements Closeable\n|| IOUtilFunctions.isObjectStoreFileScheme(new Path(fname)) )\n{\nPath scriptPath = new Path(fname);\n- try(FileSystem fs = IOUtilFunctions.getFileSystem(scriptPath) ) {\n+ fs = IOUtilFunctions.getFileSystem(scriptPath);\nin = new BufferedReader(new InputStreamReader(fs.open(scriptPath)));\n- }\n+\n}\n// from local file system\nelse {\n@@ -327,6 +328,8 @@ public class Connection implements Closeable\n}\n}\nfinally {\n+ if(fs != null)\n+ fs.close();\nIOUtilFunctions.closeSilently(in);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/ParserWrapper.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/ParserWrapper.java",
"diff": "@@ -35,6 +35,7 @@ import org.apache.commons.io.IOUtils;\nimport org.apache.commons.logging.Log;\nimport org.apache.hadoop.fs.FileSystem;\nimport org.apache.hadoop.fs.Path;\n+import org.tugraz.sysds.api.jmlc.Connection;\nimport org.tugraz.sysds.parser.dml.CustomErrorListener.ParseIssue;\nimport org.tugraz.sysds.runtime.io.IOUtilFunctions;\n@@ -46,6 +47,7 @@ public abstract class ParserWrapper {\nprotected boolean atLeastOneError = false;\nprotected boolean atLeastOneWarning = false;\nprotected List<ParseIssue> parseIssues;\n+ private static FileSystem fs = null;\npublic abstract DMLProgram parse(String fileName, String dmlScript, Map<String, String> argVals);\n@@ -102,10 +104,9 @@ public abstract class ParserWrapper {\nPath scriptPath = new Path(script);\nString scheme = (scriptPath.toUri()!=null) ? scriptPath.toUri().getScheme() : null;\nLOG.debug(\"Looking for the following file in \"+scheme+\": \" + script);\n- try( FileSystem fs = IOUtilFunctions.getFileSystem(scriptPath) ) {\n+ fs = IOUtilFunctions.getFileSystem(scriptPath);\nin = new BufferedReader(new InputStreamReader(fs.open(scriptPath)));\n}\n- }\n// from local file system\nelse\n{\n@@ -152,6 +153,9 @@ public abstract class ParserWrapper {\n}\n}\nfinally {\n+ if(fs != null)\n+ fs.close();\n+\nIOUtilFunctions.closeSilently(in);\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [BUGFIX] two more try-block issues fixed |
49,689 | 08.02.2020 20:38:24 | -3,600 | 48faea45cc74289d6b2c4aa5d20d1a22d577a9ca | Initial code style eclipse template
Closes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/CodeStyle_eclipse.xml",
"diff": "+<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n+<profiles version=\"16\">\n+<profile kind=\"CodeFormatterProfile\" name=\"SystemDS\" version=\"16\">\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_ellipsis\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_for_statment\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_logical_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_method_invocation\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_after_imports\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_switch_statement\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.format_javadoc_comments\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indentation.size\" value=\"4\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_enum_constant_declaration\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.align_with_spaces\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.disabling_tag\" value=\"@formatter:off\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.continuation_indentation\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_enum_constants\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_imports\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_after_package\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_if_while_statement\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.indent_root_tags\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.enabling_tag\" value=\"@formatter:on\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.count_line_length_from_starting_position\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_multiplicative_operator\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_parameterized_type_references\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_logical_operator\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_annotation_declaration_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_enum_constant\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_multiplicative_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_statements_compare_to_block\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.align_tags_descriptions_grouped\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.line_length\" value=\"120\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.use_on_off_tags\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_method_body_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_loop_body_block_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_method_declaration\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_enum_constant_declaration_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.align_variable_declarations_on_columns\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_type_declaration_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_catch_clause\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_additive_operator\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_relational_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_multiplicative_operator\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_anonymous_type_declaration_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_shift_operator\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_block\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_lambda_body\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.compact_else_if\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_bitwise_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_type_parameters\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation\" value=\"80\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_compact_loops\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_simple_for_body_on_same_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_relational_operator\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_unary_operator\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_annotation\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_ellipsis\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_additive_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_string_concatenation\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.format_line_comments\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.align_type_members_on_columns\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_assignment\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_module_statements\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.align_tags_names_descriptions\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_if_then_body_block_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_conditional_expression\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.align_assignment_statements_on_columns\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_block_in_case\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_conditional_expression_chain\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.format_header\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_additive_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_method_declaration\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.join_wrapped_lines\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_conditional_operator\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_shift_operator\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.align_fields_grouping_blank_lines\" value=\"2147483647\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_bitwise_operator\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_resources_in_try\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_try_clause\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_code_block_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.tabulation.size\" value=\"4\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_bitwise_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.format_source_code\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_field\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_method\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_assignment_operator\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_switch\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_type_annotation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.format_html\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_method_delcaration\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_compact_if\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_lambda_body_block_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_empty_lines\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_type_arguments\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_unary_operator\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_label\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_member_type\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_logical_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_bitwise_operator\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_semicolon\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_relational_operator\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.format_block_comments\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_lambda_arrow\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.indent_tag_description\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_string_concatenation\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_statements_compare_to_body\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_multiple_fields\" value=\"16\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_simple_while_body_on_same_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_array_initializer\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_logical_operator\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_shift_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.parentheses_positions_in_lambda_declaration\" value=\"common_lines\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_shift_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_simple_do_while_body_on_same_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_enum_declaration_on_one_line\" value=\"one_line_never\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_enum_constant\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.brace_position_for_type_declaration\" value=\"end_of_line\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_multiplicative_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_before_package\" value=\"0\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.alignment_for_expressions_in_for_loop_header\" value=\"80\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_additive_operator\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.keep_simple_getter_setter_on_one_line\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_string_concatenation\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_lambda_arrow\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.join_lines_in_comments\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.comment.indent_parameter_description\" value=\"false\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.tabulation.char\" value=\"tab\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_relational_operator\" value=\"insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.wrap_before_string_concatenation\" value=\"true\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.blank_lines_between_import_groups\" value=\"1\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.lineSplit\" value=\"120\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation\" value=\"do not insert\"/>\n+<setting id=\"org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch\" value=\"do not insert\"/>\n+</profile>\n+</profiles>\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-156] Initial code style eclipse template
Closes #79. |
49,720 | 08.02.2020 21:31:14 | -3,600 | e2b903c67ed2c485bc5ad42618917730975c9e1f | New builtin function for outlier detection via std dev
Outliers detection using standard deviation and repair using row
deletion, mean and median imputation
Closes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/builtin/outlierBySd.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+\n+# Builtin function for detecting and repairing outliers using standard deviation\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Double --- Matrix X\n+# k Double 3 threshold values 1, 2, 3 for 68%, 95%, 99.7% respectively (3-sigma rule)\n+# repairMethod Integer 1 values: 0 = delete rows having outliers, 1 = replace outliers as missing values\n+# (this script replaces outliers with zeros)\n+# max_iterations Integer 0 values: 0 = arbitrary number of iteration until all outliers are removed,\n+# n = any constant defined by user\n+# ---------------------------------------------------------------------------------------------\n+\n+\n+#Output(s)\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# Y Double --- Matrix X with no outliers\n+\n+m_outlierBySd = function(Matrix[Double] X, Double k = 3, Integer repairMethod = 1,\n+ Integer max_iterations, Boolean verbose = TRUE) return(Matrix[Double] Y)\n+{\n+ sumPrevious = 0\n+ sumNext = 1\n+ counter = 0\n+\n+ if( k < 1 | k > 7)\n+ stop(\"outlierBySd: invalid argument - k should be in range 1-7 found \"+k)\n+\n+ while( max_iterations == 0 | counter < max_iterations )\n+ {\n+ colSD = colSds(X)\n+ colMean = (colMeans(X))\n+\n+ upperBound = colMean + k * colSD\n+ lowerBound = colMean - k * colSD\n+\n+ outlierFilter = (X < lowerBound) | (X > upperBound)\n+\n+ if(sum(outlierFilter) > 1 & sum(X) != 0 & sumPrevious != sumNext) {\n+ #TODO why is the check with sumPrevious and sumNext necessary\n+ sumPrevious = sum(X)\n+ X = fix_outliers(X, outlierFilter, repairMethod)\n+ sumNext = sum(X)\n+ }\n+ else\n+ max_iterations = - 1;\n+\n+ counter = counter + 1;\n+ }\n+ Y = X\n+ if(verbose) {\n+ print(\"last outlier filter:\\n\"+ toString(outlierFilter))\n+ print(\"Total executed iterations = \"+counter)\n+ print(\"Upper-bound of data was calculated using Mean + k * Standard Deviation\")\n+ print(\"lower-bound of data was calculated using Mean - k * Standard Deviation\")\n+ print(\"Anything less than the lower-bound and greater than the upper-bound was treated as outlier\")\n+ if(sum(Y) == 0)\n+ print(\"output is a zero matrix due to iterative evaluation of outliers \")\n+ print(\"output:\\n\"+ toString(Y))\n+ }\n+}\n+\n+fix_outliers = function(Matrix[Double] X, Matrix[Double] outlierFilter, Integer repairMethod = 2)\n+ return(Matrix[Double] fixed_X)\n+{\n+ rows = nrow(X)\n+ cols = ncol(X)\n+ if(repairMethod == 0) {\n+ sel = (rowMaxs(outlierFilter) == 0)\n+ X = removeEmpty(target = X, margin = \"rows\", select = sel)\n+ }\n+ else if(repairMethod == 1)\n+ X = (outlierFilter == 0) * X\n+ else\n+ stop(\"outlierBySd: invalid argument - repair required 0-1 found: \"+repairMethod)\n+\n+ fixed_X = X\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"diff": "@@ -122,6 +122,7 @@ public enum Builtins {\nNAIVEBAYES(\"naivebayes\", true, false),\nOUTER(\"outer\", false),\nOUTLIER(\"outlier\", true, false), //TODO parameterize opposite\n+ OUTLIERBYSD(\"outlierBySd\", true),\nPNMF(\"pnmf\", true),\nPPRED(\"ppred\", false),\nPROD(\"prod\", false),\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinOutlierBySDTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.tugraz.sysds.test.functions.builtin;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.lops.LopProperties;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+\n+import java.util.concurrent.ThreadLocalRandom;\n+\n+public class BuiltinOutlierBySDTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"outlier_by_sd\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinOutlierBySDTest.class.getSimpleName() + \"/\";\n+\n+ private final static int rows = 50;\n+ private final static int cols = 10;\n+ private final static double spDense = 0.6;\n+ private final static double spSparse = 0.4;\n+\n+ @Override\n+ public void setUp() {\n+ addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{\"B\"}));\n+ }\n+\n+ @Test\n+ public void testOutlierRepair0CP() {\n+ runOutlierTest(false, 2,0, 0, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testOutlierRepair1CP() {\n+ runOutlierTest(false, 2,1, 0, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testOutlierRepair2CP() {\n+ runOutlierTest(false, 2,2, 10, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testOutlierRepair0SP() {\n+ runOutlierTest(false, 2,0, 10, LopProperties.ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testOutlierRepair1SP() {\n+ runOutlierTest(false, 2,1, 0, LopProperties.ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testOutlierK3CP() {\n+ runOutlierTest(true, 3,1, 10,LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testOutlierIterativeCP() {\n+ runOutlierTest(false, 2,1, 0, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testOutlierIterativeSP() {\n+ runOutlierTest(false, 2,1, 0, LopProperties.ExecType.SPARK);\n+ }\n+\n+ private void runOutlierTest(boolean sparse, double k, int repair, int max_iterations, LopProperties.ExecType instType)\n+ {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+\n+ try\n+ {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{ \"-args\", input(\"A\"), String.valueOf(k),\n+ String.valueOf(repair), String.valueOf(max_iterations),output(\"B\")};\n+\n+ //generate actual dataset\n+ double[][] A = getRandomMatrix(rows, cols, 1, 10000, sparse?spSparse:spDense, 7);\n+ for(int i=0; i<A.length/4; i++) {\n+ int r = ThreadLocalRandom.current().nextInt(0, A.length);\n+ int c = ThreadLocalRandom.current().nextInt(0, A[0].length);\n+ double badValue = ThreadLocalRandom.current().nextDouble(0, A.length*100);\n+ A[r][c] = badValue;\n+ }\n+\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+\n+ runTest(true, false, null, -1);\n+\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/builtin/outlier_by_sd.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = read($1);\n+Y = outlierBySd(X, $2, $3, $4, TRUE);\n+write(Y, $5)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-193] New builtin function for outlier detection via std dev
Outliers detection using standard deviation and repair using row
deletion, mean and median imputation
Closes #89. |
49,720 | 08.02.2020 21:55:46 | -3,600 | da30e27c549c758e30dc94fc8e9004bc60da38d2 | New builtin function for outlier detection via IQR
Outlier detection using IQR - Initial commit
Closes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/builtin/outlierByIQR.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+\n+# Builtin function for detecting and repairing outliers using standard deviation\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Double --- Matrix X\n+# k Double 1.5 a constant used to discern outliers k*IQR\n+# isIterative Boolean TRUE iterative repair or single repair\n+# repairMethod Integer 1 values: 0 = delete rows having outliers,\n+# 1 = replace outliers as missing values\n+# max_iterations Integer 0 values: 0 = arbitrary number of iteraition until all outliers are removed,\n+# n = any constant defined by user\n+# ---------------------------------------------------------------------------------------------\n+\n+\n+#Output(s)\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# Y Double --- Matrix X with no outliers\n+\n+m_outlierByIQR = function(Matrix[Double] X, Double k =1.5, Integer repairMethod = 1,\n+ Integer max_iterations, Boolean verbose = TRUE) return(Matrix[Double] Y)\n+{\n+ sumPrevious =0\n+ sumNext = 1\n+ counter = 0\n+\n+ while( max_iterations == 0 | counter < max_iterations )\n+ {\n+ [Q1, Q3, IQR] = compute_quartiles(X)\n+ upperBound = (Q3 + (k * IQR));\n+ lowerBound = (Q1 - (k * IQR));\n+ outlierFilter = X < lowerBound | X > upperBound\n+\n+ if(sum(outlierFilter) > 1 & sum(X) != 0 & sumPrevious != sumNext ) {\n+ #TODO: see outlierBySd why are sumPrevious and sumNext necessary\n+ sumPrevious = sum(X)\n+ X = fix_outliers(X, outlierFilter, repairMethod)\n+ sumNext = sum(X)\n+ }\n+ else\n+ max_iterations = -1\n+\n+ counter = counter + 1;\n+ }\n+ Y = X\n+ if(verbose) {\n+ print(\"Total executed iterations = \"+counter)\n+ print(\"Upper-bound of data was calculated using Q3 + k * IQR\")\n+ print(\"lower-bound of data was calculated using Q3 - k * IQR\")\n+ print(\"Anything less than the lower-bound and greater than the upper-bound was treated as outlier\")\n+ if(sum(Y) == 0)\n+ print(\"output is a zero matrix due to iterative evaluation of outliers \")\n+ print(\"output:\\n\"+ toString(Y))\n+ }\n+}\n+\n+fix_outliers = function(Matrix[Double] X, Matrix[Double] outlierFilter, Integer repairMethod = 1)\n+ return(Matrix[Double] fixed_X)\n+{\n+ rows = nrow(X)\n+ cols = ncol(X)\n+ if(repairMethod == 0) {\n+ sel = rowMaxs(outlierFilter) == 0\n+ X = removeEmpty(target = X, margin = \"rows\", select = sel)\n+ }\n+ else if(repairMethod == 1)\n+ X = (outlierFilter == 0) * X\n+ else\n+ stop(\"outlierByIQR: invalid argument - repair required 0-1 found: \"+repairMethod)\n+\n+ fixed_X = X\n+}\n+\n+compute_quartiles = function(Matrix[Double] X)\n+ return(Matrix[Double] colQ1, Matrix[Double] colQ3, Matrix[Double] IQR)\n+{\n+ cols = ncol(X)\n+ colQ1 = matrix(0, 1, cols)\n+ colQ3 = matrix(0, 1, cols)\n+ if(nrow(X) > 1) {\n+ parfor(i in 1:cols) {\n+ colQ1[,i] = quantile(X[,i], 0.25)\n+ colQ3[,i] = quantile(X[,i], 0.75)\n+ }\n+ }\n+ IQR = colQ3 - colQ1\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"diff": "@@ -122,7 +122,8 @@ public enum Builtins {\nNAIVEBAYES(\"naivebayes\", true, false),\nOUTER(\"outer\", false),\nOUTLIER(\"outlier\", true, false), //TODO parameterize opposite\n- OUTLIERBYSD(\"outlierBySd\", true),\n+ OUTLIER_SD(\"outlierBySd\", true),\n+ OUTLIER_IQR(\"outlierByIQR\", true),\nPNMF(\"pnmf\", true),\nPPRED(\"ppred\", false),\nPROD(\"prod\", false),\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinOutlierByIQRTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+package org.tugraz.sysds.test.functions.builtin;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.lops.LopProperties;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+\n+import java.util.concurrent.ThreadLocalRandom;\n+\n+public class BuiltinOutlierByIQRTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"outlier_by_IQR\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinOutlierByIQRTest.class.getSimpleName() + \"/\";\n+\n+ private final static int rows = 100;\n+ private final static int cols = 15;\n+ private final static double spDense = 0.7;\n+ private final static double spSparse = 0.8;\n+\n+ @Override\n+ public void setUp() {\n+ addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{\"B\"}));\n+ }\n+\n+ @Test\n+ public void testOutlierRepair0CP() {\n+ runOutlierTest(false, 1.5, 0, 10,LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testOutlierRepair1CP() {\n+ runOutlierTest(false, 2, 1, 10,LopProperties.ExecType.CP);\n+ }\n+\n+\n+ @Test\n+ public void testOutlierRepair0SP() {\n+ runOutlierTest(false, 2, 0, 10,LopProperties.ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testOutlierRepair1SP() {\n+ runOutlierTest(false, 1.5, 1, 10,LopProperties.ExecType.SPARK);\n+ }\n+ @Test\n+ public void testOutlierRepair0IterativeCP() {\n+ runOutlierTest(false, 1.5, 0, 0,LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testOutlierRepair1IterativeCP() {\n+ runOutlierTest(false, 1.5, 1, 0,LopProperties.ExecType.CP);\n+ }\n+\n+\n+ @Test\n+ public void testOutlierRepair0IterativeSP() {\n+ runOutlierTest(false, 1.5, 0, 0,LopProperties.ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testOutlierRepair1IterativeSP() {\n+ runOutlierTest(false, 1.5, 1, 0,LopProperties.ExecType.SPARK);\n+ }\n+\n+\n+ private void runOutlierTest(boolean sparse, double k, int repair, int max_iterations, LopProperties.ExecType instType)\n+ {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+\n+ try\n+ {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{ \"-args\", input(\"A\"), String.valueOf(k),\n+ String.valueOf(repair), String.valueOf(max_iterations),output(\"B\")};\n+\n+ //generate actual dataset\n+ double[][] A = getRandomMatrix(rows, cols, 1, 100, sparse?spSparse:spDense, 10);\n+ for(int i=0; i<A.length/4; i++) {\n+ int r = ThreadLocalRandom.current().nextInt(0, A.length);\n+ int c = ThreadLocalRandom.current().nextInt(0, A[0].length);\n+ double badValue = ThreadLocalRandom.current().nextDouble(0, A.length*100);\n+ A[r][c] = badValue;\n+ }\n+\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+\n+ runTest(true, false, null, -1);\n+\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/builtin/outlier_by_IQR.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = read($1);\n+Y = outlierByIQR(X, $2, $3, $4, TRUE);\n+write(Y, $5)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-194] New builtin function for outlier detection via IQR
Outlier detection using IQR - Initial commit
Closes #91. |
49,746 | 09.02.2020 21:34:26 | -3,600 | 645d0ba563bac01172ae5b04f56d0fd43357fb91 | New federated rbind and cbind operations
Optimizes rbind and cbind to only append federated metadata for the
result.
Closes | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/FederatedRange.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/FederatedRange.java",
"diff": "@@ -34,6 +34,23 @@ public class FederatedRange implements Comparable<FederatedRange> {\n_endDims = endDims;\n}\n+ /**\n+ * Does a deep copy of another <code>FederatedRange</code> object.\n+ * @param other the <code>FederatedRange</code> to copy\n+ */\n+ public FederatedRange(FederatedRange other) {\n+ _beginDims = other._beginDims.clone();\n+ _endDims = other._endDims.clone();\n+ }\n+\n+ public void setBeginDim(int dim, long value) {\n+ _beginDims[dim] = value;\n+ }\n+\n+ public void setEndDim(int dim, long value) {\n+ _endDims[dim] = value;\n+ }\n+\npublic long[] getBeginDims() {\nreturn _beginDims;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/FederatedWorkerHandler.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/FederatedWorkerHandler.java",
"diff": "@@ -149,8 +149,8 @@ public class FederatedWorkerHandler extends ChannelInboundHandlerAdapter {\nData dataObject = _vars.get(varID);\nif (dataObject.getDataType() != Types.DataType.MATRIX) {\nreturn new FederatedResponse(FederatedResponse.Type.ERROR,\n- \"FederatedWorkerHandler: Aggregation only supported for matrices, not for \" +\n- dataObject.getDataType().name());\n+ \"FederatedWorkerHandler: Aggregation only supported for matrices, not for \"\n+ + dataObject.getDataType().name());\n}\nMatrixObject matrixObject = (MatrixObject) dataObject;\nMatrixBlock matrixBlock = matrixObject.acquireRead();\n@@ -287,9 +287,8 @@ public class FederatedWorkerHandler extends ChannelInboundHandlerAdapter {\nprivate static void checkNumParams(int actual, int... expected) {\nif( Arrays.stream(expected).anyMatch(x -> x==actual ))\nreturn;\n- throw new DMLRuntimeException(\n- \"FederatedWorkerHandler: Received wrong amount of params:\" + \" expected=\"\n- + Arrays.toString(expected) + \", actual=\" + actual);\n+ throw new DMLRuntimeException(\"FederatedWorkerHandler: Received wrong amount of params:\"\n+ + \" expected=\" + Arrays.toString(expected) +\", actual=\" + actual);\n}\n@Override\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/LibFederatedAppend.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ *\n+ */\n+\n+package org.tugraz.sysds.runtime.controlprogram.federated;\n+\n+import org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\n+import org.tugraz.sysds.runtime.meta.DataCharacteristics;\n+\n+import java.util.Map;\n+import java.util.TreeMap;\n+\n+public class LibFederatedAppend {\n+ public static MatrixObject federateAppend(MatrixObject matObject1, MatrixObject matObject2,\n+ MatrixObject matObjectRet, boolean cbind)\n+ {\n+ Map<FederatedRange, FederatedData> fedMapping = new TreeMap<>();\n+ DataCharacteristics dc = matObjectRet.getDataCharacteristics();\n+ if (cbind) {\n+ // check for same amount of rows for matObject1 and matObject2 should have been checked before call\n+ dc.setRows(matObject1.getNumRows());\n+ // added because cbind\n+ long columnsLeftMat = matObject1.getNumColumns();\n+ dc.setCols(columnsLeftMat + matObject2.getNumColumns());\n+\n+ Map<FederatedRange, FederatedData> fedMappingLeft = matObject1.getFedMapping();\n+ for (Map.Entry<FederatedRange, FederatedData> entry : fedMappingLeft.entrySet()) {\n+ // note that FederatedData should not change its varId once set\n+ fedMapping.put(new FederatedRange(entry.getKey()), entry.getValue());\n+ }\n+ Map<FederatedRange, FederatedData> fedMappingRight = matObject2.getFedMapping();\n+ for (Map.Entry<FederatedRange, FederatedData> entry : fedMappingRight.entrySet()) {\n+ // add offset due to cbind\n+ FederatedRange range = new FederatedRange(entry.getKey());\n+ range.setBeginDim(1, columnsLeftMat + range.getBeginDims()[1]);\n+ range.setEndDim(1, columnsLeftMat + range.getEndDims()[1]);\n+ fedMapping.put(range, entry.getValue());\n+ }\n+ }\n+ else {\n+ // check for same amount of cols for matObject1 and matObject2 should have been checked before call\n+ dc.setCols(matObject1.getNumColumns());\n+ // added because rbind\n+ long rowsUpperMat = matObject1.getNumRows();\n+ dc.setRows(rowsUpperMat + matObject2.getNumRows());\n+\n+ Map<FederatedRange, FederatedData> fedMappingUpper = matObject1.getFedMapping();\n+ for (Map.Entry<FederatedRange, FederatedData> entry : fedMappingUpper.entrySet()) {\n+ // note that FederatedData should not change its varId once set\n+ fedMapping.put(new FederatedRange(entry.getKey()), entry.getValue());\n+ }\n+ Map<FederatedRange, FederatedData> fedMappingLower = matObject2.getFedMapping();\n+ for (Map.Entry<FederatedRange, FederatedData> entry : fedMappingLower.entrySet()) {\n+ // add offset due to rbind\n+ FederatedRange range = new FederatedRange(entry.getKey());\n+ range.setBeginDim(0, rowsUpperMat + range.getBeginDims()[0]);\n+ range.setEndDim(0, rowsUpperMat + range.getEndDims()[0]);\n+ fedMapping.put(range, entry.getValue());\n+ }\n+ }\n+ matObjectRet.setFedMapping(fedMapping);\n+ dc.setNonZeros(matObject1.getNnz() + matObject2.getNnz());\n+ return matObjectRet;\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/AppendFEDInstruction.java",
"diff": "+/*\n+ * Licensed to the Apache Software Foundation (ASF) under one\n+ * or more contributor license agreements. See the NOTICE file\n+ * distributed with this work for additional information\n+ * regarding copyright ownership. The ASF licenses this file\n+ * to you under the Apache License, Version 2.0 (the\n+ * \"License\"); you may not use this file except in compliance\n+ * with the License. You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing,\n+ * software distributed under the License is distributed on an\n+ * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+ * KIND, either express or implied. See the License for the\n+ * specific language governing permissions and limitations\n+ * under the License.\n+ */\n+\n+package org.tugraz.sysds.runtime.instructions.fed;\n+\n+import org.tugraz.sysds.runtime.DMLRuntimeException;\n+import org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\n+import org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\n+import org.tugraz.sysds.runtime.controlprogram.federated.LibFederatedAppend;\n+import org.tugraz.sysds.runtime.functionobjects.OffsetColumnIndex;\n+import org.tugraz.sysds.runtime.instructions.InstructionUtils;\n+import org.tugraz.sysds.runtime.instructions.cp.CPOperand;\n+import org.tugraz.sysds.runtime.matrix.operators.Operator;\n+import org.tugraz.sysds.runtime.matrix.operators.ReorgOperator;\n+\n+public class AppendFEDInstruction extends BinaryFEDInstruction {\n+ public enum FEDAppendType {\n+ CBIND, RBIND;\n+ public boolean isCBind() {\n+ return this == CBIND;\n+ }\n+ }\n+\n+ protected final FEDAppendType _type;\n+\n+ protected AppendFEDInstruction(Operator op, CPOperand in1, CPOperand in2, CPOperand out, FEDAppendType type,\n+ String opcode, String istr) {\n+ super(FEDType.Append, op, in1, in2, out, opcode, istr);\n+ _type = type;\n+ }\n+\n+ public static AppendFEDInstruction parseInstruction(String str) {\n+ String[] parts = InstructionUtils.getInstructionPartsWithValueType(str);\n+ InstructionUtils.checkNumFields(parts, 5, 4);\n+\n+ String opcode = parts[0];\n+ CPOperand in1 = new CPOperand(parts[1]);\n+ CPOperand in2 = new CPOperand(parts[2]);\n+ CPOperand out = new CPOperand(parts[parts.length - 2]);\n+ boolean cbind = Boolean.parseBoolean(parts[parts.length - 1]);\n+\n+ FEDAppendType type = cbind ? FEDAppendType.CBIND : FEDAppendType.RBIND;\n+\n+ if (!opcode.equalsIgnoreCase(\"append\") && !opcode.equalsIgnoreCase(\"remove\")\n+ && !opcode.equalsIgnoreCase(\"galignedappend\"))\n+ throw new DMLRuntimeException(\"Unknown opcode while parsing a AppendCPInstruction: \" + str);\n+\n+ Operator op = new ReorgOperator(OffsetColumnIndex.getOffsetColumnIndexFnObject(-1));\n+ return new AppendFEDInstruction(op, in1, in2, out, type, opcode, str);\n+ }\n+\n+ @Override\n+ public void processInstruction(ExecutionContext ec) {\n+ //get inputs\n+ MatrixObject matObject1 = ec.getMatrixObject(input1.getName());\n+ MatrixObject matObject2 = ec.getMatrixObject(input2.getName());\n+ //check input dimensions\n+ if (_type == FEDAppendType.CBIND && matObject1.getNumRows() != matObject2.getNumRows()) {\n+ throw new DMLRuntimeException(\n+ \"Append-cbind is not possible for federated input matrices \" + input1.getName() + \" and \"\n+ + input2.getName() + \" with different number of rows: \" + matObject1.getNumRows() + \" vs \"\n+ + matObject2.getNumRows());\n+ }\n+ else if (_type == FEDAppendType.RBIND && matObject1.getNumColumns() != matObject2.getNumColumns()) {\n+ throw new DMLRuntimeException(\n+ \"Append-rbind is not possible for federated input matrices \" + input1.getName() + \" and \"\n+ + input2.getName() + \" with different number of columns: \" + matObject1.getNumColumns()\n+ + \" vs \" + matObject2.getNumColumns());\n+ }\n+ // append MatrixObjects\n+ LibFederatedAppend.federateAppend(matObject1, matObject2,\n+ ec.getMatrixObject(output.getName()), _type.isCBind());\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstruction.java",
"diff": "@@ -23,7 +23,7 @@ import org.tugraz.sysds.runtime.matrix.operators.Operator;\npublic abstract class FEDInstruction extends Instruction {\npublic enum FEDType {\n- Init, AggregateBinary, AggregateUnary\n+ Init, AggregateBinary, AggregateUnary, Append\n}\nprotected final FEDType _fedType;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstructionUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstructionUtils.java",
"diff": "@@ -24,6 +24,7 @@ import org.tugraz.sysds.runtime.instructions.cp.AggregateUnaryCPInstruction;\nimport org.tugraz.sysds.runtime.instructions.cp.Data;\nimport org.tugraz.sysds.runtime.instructions.cp.VariableCPInstruction;\nimport org.tugraz.sysds.runtime.instructions.spark.AggregateUnarySPInstruction;\n+import org.tugraz.sysds.runtime.instructions.spark.AppendGAlignedSPInstruction;\nimport org.tugraz.sysds.runtime.instructions.spark.MapmmSPInstruction;\nimport org.tugraz.sysds.runtime.instructions.spark.WriteSPInstruction;\n@@ -76,6 +77,14 @@ public class FEDInstructionUtils {\nreturn VariableCPInstruction.parseInstruction(instruction.getInstructionString());\n}\n}\n+ else if (inst instanceof AppendGAlignedSPInstruction) {\n+ // TODO other Append Spark instructions\n+ AppendGAlignedSPInstruction instruction = (AppendGAlignedSPInstruction) inst;\n+ Data data = ec.getVariable(instruction.input1);\n+ if (data instanceof MatrixObject && ((MatrixObject) data).isFederated()) {\n+ return AppendFEDInstruction.parseInstruction(instruction.getInstructionString());\n+ }\n+ }\nreturn inst;\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/InitFEDInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/InitFEDInstruction.java",
"diff": "@@ -112,11 +112,13 @@ public class InitFEDInstruction extends FEDInstruction {\nFederatedData federatedData = new FederatedData(\nnew InetSocketAddress(InetAddress.getByName(host), port), filePath);\nfeds.add(new ImmutablePair<>(new FederatedRange(beginDims, endDims), federatedData));\n- } catch (UnknownHostException e) {\n+ }\n+ catch (UnknownHostException e) {\nthrow new DMLRuntimeException(\"federated host was unknown: \" + host);\n}\n- } else {\n+ }\n+ else {\nthrow new DMLRuntimeException(\"federated instruction only takes strings as addresses\");\n}\n}\n@@ -153,7 +155,8 @@ public class InitFEDInstruction extends FEDInstruction {\nthrow new IllegalArgumentException(\"Reference is not supported\");\nreturn new String[] { host, port, filePath };\n- } catch (MalformedURLException e) {\n+ }\n+ catch (MalformedURLException e) {\nthrow new IllegalArgumentException(\"federated address `\" + input\n+ \"` does not fit required URL pattern of \\\"host:port/directory\\\"\", e);\n}\n@@ -187,7 +190,8 @@ public class InitFEDInstruction extends FEDInstruction {\nelse\nthrow new DMLRuntimeException(response.getErrorMessage());\n}\n- } catch (Exception e) {\n+ }\n+ catch (Exception e) {\nthrow new DMLRuntimeException(\"Federation initialization failed\", e);\n}\noutput.getDataCharacteristics().setNonZeros(output.getNumColumns() * output.getNumRows());\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/UnaryFEDInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/UnaryFEDInstruction.java",
"diff": "@@ -73,6 +73,7 @@ public abstract class UnaryFEDInstruction extends ComputationFEDInstruction {\ncase 5:\nin1.split(parts[1]);\nin2.split(parts[2]);\n+ in3.split(parts[3]);\nbreak;\ndefault:\nthrow new DMLRuntimeException(\"Unexpected number of operands in the instruction: \" + instr);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/federated/FederatedRCBindTest.java",
"diff": "+/*\n+ * Copyright 2019 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ *\n+ */\n+\n+package org.tugraz.sysds.test.functions.federated;\n+\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+import org.tugraz.sysds.api.DMLScript;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.runtime.meta.MatrixCharacteristics;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+import java.util.Arrays;\n+import java.util.Collection;\n+\n+import static java.lang.Thread.sleep;\n+\n+@RunWith(value = Parameterized.class)\n+public class FederatedRCBindTest extends AutomatedTestBase {\n+\n+ private final static String TEST_DIR = \"functions/federated/\";\n+ private final static String TEST_NAME = \"FederatedRCBindTest\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + FederatedRCBindTest.class.getSimpleName() + \"/\";\n+\n+ private final static int port = 1222;\n+ private final static int blocksize = 1024;\n+ private int rows, cols;\n+\n+ public FederatedRCBindTest(int rows, int cols) {\n+ this.rows = rows;\n+ this.cols = cols;\n+ }\n+\n+ @Parameterized.Parameters\n+ public static Collection<Object[]> data() {\n+ Object[][] data = new Object[][] {{1, 1000}, {10, 100}, {100, 10}, {1000, 1}, {10, 2000}, {2000, 10}};\n+ return Arrays.asList(data);\n+ }\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {\"R\", \"C\"}));\n+ }\n+\n+ @Test\n+ public void federatedRCBindCP() {\n+ federatedRCBind(Types.ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ public void federatedRCBindSP() {\n+ federatedRCBind(Types.ExecMode.SPARK);\n+ }\n+\n+ public void federatedRCBind(Types.ExecMode execMode) {\n+ boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\n+ Types.ExecMode platformOld = rtplatform;\n+\n+ Thread t = null;\n+ try {\n+ getAndLoadTestConfiguration(TEST_NAME);\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+\n+ // empty script name because we don't execute any script, just start the worker\n+ fullDMLScriptName = \"\";\n+ programArgs = new String[] {\"-w\", Integer.toString(port)};\n+\n+ double[][] A = getRandomMatrix(rows, cols, -10, 10, 1, 1);\n+ writeInputMatrixWithMTD(\"A\", A, false, new MatrixCharacteristics(rows, cols, blocksize, rows * cols));\n+ t = new Thread(() -> runTest(true, false, null, -1));\n+ t.start();\n+ sleep(FED_WORKER_WAIT);\n+\n+ // we need the reference file to not be written to hdfs, so we get the correct format\n+ rtplatform = Types.ExecMode.SINGLE_NODE;\n+ // Run reference dml script with normal matrix for Row/Col sum\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-args\", input(\"A\"), expected(\"R\"), expected(\"C\")};\n+ runTest(true, false, null, -1);\n+\n+ // reference file should not be written to hdfs, so we set platform here\n+ rtplatform = execMode;\n+ if (rtplatform == Types.ExecMode.SPARK) {\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+ }\n+ TestConfiguration config = availableTestConfigurations.get(TEST_NAME);\n+ loadTestConfiguration(config);\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-explain\", \"-args\", \"\\\"localhost:\" + port + \"/\" + input(\"A\") + \"\\\"\",\n+ Integer.toString(rows), Integer.toString(cols), output(\"R\"), output(\"C\")};\n+\n+ runTest(true, false, null, -1);\n+\n+ // compare all sums via files\n+ compareResults(1e-11);\n+ }\n+ catch (InterruptedException e) {\n+ e.printStackTrace();\n+ assert (false);\n+ }\n+ finally {\n+ TestUtils.shutdownThread(t);\n+ rtplatform = platformOld;\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/federated/FederatedRCBindTest.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+A = federated(addresses=list($1), ranges=list(list(0, 0), list($2, $3)))\n+B = federated(addresses=list($1), ranges=list(list(0, 0), list($2, $3)))\n+R = rbind(A, B)\n+C = cbind(A, B)\n+write(R, $4)\n+write(C, $5)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/federated/FederatedRCBindTestReference.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+A = read($1)\n+R = rbind(A, A)\n+C = cbind(A, A)\n+write(R, $2)\n+write(C, $3)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-226] New federated rbind and cbind operations
Optimizes rbind and cbind to only append federated metadata for the
result.
Closes #92. |
49,745 | 14.02.2020 16:06:08 | -3,600 | c42c90be1c530ad9bdcc07162801e56d0faa59d3 | [261] Stable Marriage Algorithm
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -185,5 +185,8 @@ SYSTEMDS-240 GPU Backend Improvements\nSYSTEMDS-250 Large-Scale Slice Finding\n* 251 Initial data slicing implementation Python\n+SYSTEMDS-260 Algorithms\n+ * 261 Stable marriage algorithm ok\n+\nOthers:\n* Break append instruction to cbind and rbind\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/stable_marriage/StableMarriage.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#\n+#-------------------------------------------------------------\n+#\n+# THIS SCRIPT COMPUTES A SOLUTION FOR THE STABLE MARRIAGE PROBLEM (WITHOUT TIES, COMPLETE LISTS)\n+#\n+# INPUT PARAMETERS:\n+# --------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# --------------------------------------------------------------------------------------------\n+# P String --- Location (on HDFS) to read the proposer's preference matrix P.\n+# P is assumed to store preferences row-wise (i.e. row j stores proposer j's preferences).\n+# It must be a square matrix with no zeros.\n+#\n+# A String --- Location (on HDFS) to read the acceptor's preference matrix A.\n+# A is assumed to store preferences row-wise (i.e. row j stores acceptor j's preferences).\n+# It must be a square matrix with no zeros.\n+#\n+# O String --- Location to store the stable marriage solution matrix. If omitted, no output file is written.\n+# If cell [i,j] is non-zero, it means that acceptor i has matched with proposer j.\n+# Further, if cell [i,j] is non-zero, it holds the preference value that led to the match.\n+#\n+# ordered Boolean TRUE If true, P and A are assumed to be ordered,\n+# i.e. the leftmost value in a row is the most preferred partner's index.\n+# If false, P and A are assumed to be unordered,\n+# i.e. the leftmost value in a row in P is the preference value for the acceptor with index 1 and vice-versa (higher is better).\n+#\n+#\n+# Example:\n+# spark-submit SystemDS.jar -f StableMarriage.dml -nvargs P=Proposers.mtx A=Acceptors.mtx O=Output.mtx ordered=TRUE\n+#\n+# Proposers.mtx:\n+# 2.0,1.0,3.0\n+# 1.0,2.0,3.0\n+# 1.0,3.0,2.0\n+#\n+# Since ordered=TRUE, this means that proposer 1 (row 1) likes acceptor 2 the most, followed by acceptor 1 and acceptor 3.\n+# If ordered=FALSE, this would mean that proposer 1 (row 1) likes acceptor 3 the most (since the value at [1,3] is the row max),\n+# followed by acceptor 1 (2.0 preference value) and acceptor 2 (1.0 preference value).\n+#\n+# Acceptors.mtx:\n+# 3.0,1.0,2.0\n+# 2.0,1.0,3.0\n+# 3.0,2.0,1.0\n+#\n+# Since ordered=TRUE, this means that acceptor 1 (row 1) likes proposer 3 the most, followed by proposer 1 and proposer 2.\n+# If ordered=FALSE, this would mean that acceptor 1 (row 1) likes proposer 1 the most (since the value at [1,1] is the row max),\n+# followed by proposer 3 (2.0 preference value) and proposer 2 (1.0 preference value).\n+#\n+# Output.mtx (assuming ordered=TRUE):\n+# 0.0,0.0,3.0\n+# 0.0,3.0,0.0\n+# 1.0,0.0,0.0\n+#\n+# Acceptor 1 has matched with proposer 3 (since [1,3] is non-zero) at a preference level of 3.0.\n+# Acceptor 2 has matched with proposer 2 (since [2,2] is non-zero) at a preference level of 3.0.\n+# Acceptor 3 has matched with proposer 1 (since [3,1] is non-zero) at a preference level of 1.0.\n+#\n+\n+#TODO set a finite number of maximum iterations so that the execution termiates after maximum iterations.\n+fileP = ifdef ($P, \"\");\n+fileA = ifdef ($A, \"\");\n+fileOutput = ifdef ($O, \"\");\n+ordered = ifdef ($ordered, TRUE);\n+\n+print(\"\\n\")\n+print(\"STARTING STABLE MARRIAGE\");\n+print(\"READING P AND A...\");\n+\n+# P : Proposers Preference Matrix\n+# A : Acceptors Preference Matrix\n+\n+if(fileP == \"\" | fileA == \"\") {\n+ print(\"ERROR: Both P and A must be supplied.\")\n+}\n+else\n+{\n+ P = read (fileP);\n+ A = read (fileA);\n+ if(nrow(P) != ncol(P) | nrow(A) != ncol(A)) {\n+ print(\"ERROR: Wrong Input! Both P and A must be square.\")\n+ }\n+ else if(nrow(P) != nrow(P)) {\n+ print(\"ERROR: Wrong Input! Both P and A must have the same number of rows and columns.\")\n+ }\n+ else\n+ {\n+ n = nrow(P)\n+\n+ # Let S be the identity matrix\n+ S = diag(matrix(1.0, rows=n, cols=1))\n+ Result_matrix = matrix(0.0, rows=n, cols=n)\n+\n+ # Pre-processing\n+ if(!ordered){\n+ # If unordered, we need to order P\n+ Ordered_P = matrix(0.0, rows=n, cols=n)\n+ Transposed_P = t(P)\n+\n+ parfor(i in 1:n)\n+ Ordered_P[,i] = order(target=Transposed_P, by=i, decreasing=TRUE, index.return=TRUE)\n+\n+ P = t(Ordered_P)\n+ }\n+ else {\n+ # If ordered, we need to unorder A\n+ Unordered_A = matrix(0.0, rows=n, cols=n)\n+\n+ # Since cells can be converted to unordered indices independently, we can nest parfor loops.\n+ parfor(i in 1:n) {\n+ parfor(j in 1:n, check=0) {\n+ Unordered_A[i, as.scalar(A[i, j])] = n - j + 1\n+ }\n+ }\n+\n+ A = Unordered_A\n+ }\n+\n+ proposer_pointers = matrix(1.0, rows=n, cols=1)\n+\n+ while(sum(S) > 0) {\n+ Stripped_preferences = S %*% P\n+ Mask_matrix = matrix(0.0, rows=n, cols=n)\n+\n+ parfor(i in 1:n) {\n+ max_proposal = as.scalar(Stripped_preferences[i, as.scalar(proposer_pointers[i])])\n+ if(max_proposal != 0) {\n+ proposer_pointers[i] = as.scalar(proposer_pointers[i]) + 1\n+ Mask_matrix[max_proposal, i] = 1\n+ }\n+ }\n+\n+ # Hadamard Product\n+ Propose_round_results = Mask_matrix * A\n+ best_proposers_vector = rowIndexMax(Propose_round_results)\n+ prev_best_proposers = rowIndexMax(Result_matrix)\n+\n+ parfor(i in 1:n, check=0) {\n+ new_best_proposer_index = as.scalar(best_proposers_vector[i])\n+ new_best = as.scalar(Propose_round_results[i, new_best_proposer_index])\n+\n+ if(new_best > 0) {\n+ prev_best_proposer_index = as.scalar(prev_best_proposers[i])\n+ prev_best = as.scalar(Result_matrix[i, prev_best_proposer_index])\n+\n+ if (new_best > prev_best)\n+ {\n+ # Proposal is better than current fiance\n+ Result_matrix[i, prev_best_proposer_index] = 0\n+ Result_matrix[i, new_best_proposer_index] = new_best\n+\n+ #Disable freshly married man to search for a new woman in the next round\n+ S[new_best_proposer_index, new_best_proposer_index] = 0\n+\n+ # If a fiance existed, dump him/her\n+ if(prev_best > 0)\n+ S[prev_best_proposer_index, prev_best_proposer_index] = 1\n+ }\n+ }\n+ }\n+ }\n+\n+ print(\"Result: \")\n+ print(toString(Result_matrix))\n+\n+ if(fileOutput != \"\")\n+ write(Result_matrix, fileOutput)\n+\n+ }\n+}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [261] Stable Marriage Algorithm
Closes #99 |
49,738 | 14.02.2020 19:08:06 | -3,600 | c46c7389c9407d30131c9838828048afced798c9 | [MINOR] Fix strict compilation errors (types, statements) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/LibMatrixCUDA.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/LibMatrixCUDA.java",
"diff": "@@ -2278,7 +2278,7 @@ public class LibMatrixCUDA {\n}\nelse\nreturn 0.0;\n- };\n+ }\n/**\n* Cumulative scan\n@@ -2386,7 +2386,7 @@ public class LibMatrixCUDA {\nif(rows > 128) {\nfinal int MAX_BLOCKS = getMaxBlocks(gCtx);\nArrayList<Pointer> intermediate_buffers = new ArrayList<>();\n- ArrayList<Integer> cb_list = new ArrayList<Integer>();\n+ ArrayList<Integer> cb_list = new ArrayList<>();\nint block_height = 64;\nint blocks = (rows + block_height - 1) / block_height;\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix strict compilation errors (types, statements) |
49,738 | 14.02.2020 22:04:34 | -3,600 | 149da7b6a49c2879e0f1b6a197a1af543879ac94 | Cleanup unnecessary reorg hop/lop type indirections | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Types.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Types.java",
"diff": "@@ -183,10 +183,58 @@ public class Types\n}\n}\n+ // Operations that require 3 operands\n+ public enum OpOp3 {\n+ QUANTILE, INTERQUANTILE, CTABLE, MOMENT, COV, PLUS_MULT, MINUS_MULT, IFELSE\n+ }\n+\n+ // Operations that require 4 operands\n+ public enum OpOp4 {\n+ WSLOSS, //weighted sloss mm\n+ WSIGMOID, //weighted sigmoid mm\n+ WDIVMM, //weighted divide mm\n+ WCEMM, //weighted cross entropy mm\n+ WUMM //weighted unary mm\n+ }\n+\n+ // Operations that require a variable number of operands\n+ public enum OpOpN {\n+ PRINTF, CBIND, RBIND, MIN, MAX, EVAL, LIST\n+ }\n+\n+ public enum ReOrgOp {\n+ TRANS(\"t\"),\n+ RESHAPE(\"rshape\"),\n+ DIAG, //DIAG_V2M and DIAG_M2V could not be distinguished if sizes unknown\n+ SORT,\n+ REV;\n+\n+ private ReOrgOp() {\n+ _opString = name().toLowerCase();\n+ }\n+\n+ private ReOrgOp(String opString) {\n+ _opString = opString; //custom hop label\n+ }\n+\n+ private final String _opString;\n+\n+ public String getOpString() {\n+ return _opString;\n+ }\n+ }\n+\npublic enum ParamBuiltinOp {\nINVALID, CDF, INVCDF, GROUPEDAGG, RMEMPTY, REPLACE, REXPAND,\nLOWER_TRI, UPPER_TRI,\nTRANSFORMAPPLY, TRANSFORMDECODE, TRANSFORMCOLMAP, TRANSFORMMETA,\nTOSTRING, LIST, PARAMSERV\n}\n+\n+ public enum OpOpDnn {\n+ MAX_POOL, MAX_POOL_BACKWARD, AVG_POOL, AVG_POOL_BACKWARD,\n+ CONV2D, CONV2D_BACKWARD_FILTER, CONV2D_BACKWARD_DATA,\n+ BIASADD, BIASMULT, BATCH_NORM2D_TEST, CHANNEL_SUMS,\n+ UPDATE_NESTEROV_X\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/AggBinaryOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/AggBinaryOp.java",
"diff": "@@ -26,6 +26,7 @@ import org.tugraz.sysds.common.Types.AggOp;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.Direction;\nimport org.tugraz.sysds.common.Types.ExecMode;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.hops.rewrite.HopRewriteUtils;\nimport org.tugraz.sysds.lops.Binary;\n@@ -42,7 +43,6 @@ import org.tugraz.sysds.lops.MapMultChain.ChainType;\nimport org.tugraz.sysds.lops.PMMJ;\nimport org.tugraz.sysds.lops.PMapMult;\nimport org.tugraz.sysds.lops.Transform;\n-import org.tugraz.sysds.lops.Transform.OperationTypes;\nimport org.tugraz.sysds.runtime.controlprogram.context.SparkExecutionContext;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\nimport org.tugraz.sysds.runtime.meta.DataCharacteristics;\n@@ -644,9 +644,9 @@ public class AggBinaryOp extends MultiThreadedHop\n//right vector transpose\nLop lY = Y.constructLops();\n- Lop tY = (lY instanceof Transform && ((Transform)lY).getOperationType()==OperationTypes.Transpose ) ?\n+ Lop tY = (lY instanceof Transform && ((Transform)lY).getOp()==ReOrgOp.TRANS ) ?\nlY.getInputs().get(0) : //if input is already a transpose, avoid redundant transpose ops\n- new Transform(lY, OperationTypes.Transpose, getDataType(), getValueType(), ExecType.CP, k);\n+ new Transform(lY, ReOrgOp.TRANS, getDataType(), getValueType(), ExecType.CP, k);\ntY.getOutputParameters().setDimensions(Y.getDim2(), Y.getDim1(), getBlocksize(), Y.getNnz());\nsetLineNumbers(tY);\n@@ -656,7 +656,7 @@ public class AggBinaryOp extends MultiThreadedHop\nsetLineNumbers(mult);\n//result transpose (dimensions set outside)\n- Lop out = new Transform(mult, OperationTypes.Transpose, getDataType(), getValueType(), ExecType.CP, k);\n+ Lop out = new Transform(mult, ReOrgOp.TRANS, getDataType(), getValueType(), ExecType.CP, k);\nreturn out;\n}\n@@ -705,7 +705,7 @@ public class AggBinaryOp extends MultiThreadedHop\nHop Y = getInput().get(1);\n//right vector transpose\n- Lop tY = new Transform(Y.constructLops(), OperationTypes.Transpose, getDataType(), getValueType(), ExecType.CP);\n+ Lop tY = new Transform(Y.constructLops(), ReOrgOp.TRANS, getDataType(), getValueType(), ExecType.CP);\ntY.getOutputParameters().setDimensions(Y.getDim2(), Y.getDim1(), getBlocksize(), Y.getNnz());\nsetLineNumbers(tY);\n@@ -720,7 +720,7 @@ public class AggBinaryOp extends MultiThreadedHop\nsetLineNumbers(mult);\n//result transpose (dimensions set outside)\n- Lop out = new Transform(mult, OperationTypes.Transpose, getDataType(), getValueType(), ExecType.CP);\n+ Lop out = new Transform(mult, ReOrgOp.TRANS, getDataType(), getValueType(), ExecType.CP);\nreturn out;\n}\n@@ -777,7 +777,7 @@ public class AggBinaryOp extends MultiThreadedHop\nHop Y = getInput().get(1);\n//right vector transpose CP\n- Lop tY = new Transform(Y.constructLops(), OperationTypes.Transpose, getDataType(), getValueType(), ExecType.CP);\n+ Lop tY = new Transform(Y.constructLops(), ReOrgOp.TRANS, getDataType(), getValueType(), ExecType.CP);\ntY.getOutputParameters().setDimensions(Y.getDim2(), Y.getDim1(), Y.getBlocksize(), Y.getNnz());\nsetLineNumbers(tY);\n@@ -788,7 +788,7 @@ public class AggBinaryOp extends MultiThreadedHop\nsetLineNumbers(mmcj);\n//result transpose CP\n- Lop out = new Transform(mmcj, OperationTypes.Transpose, getDataType(), getValueType(), ExecType.CP);\n+ Lop out = new Transform(mmcj, ReOrgOp.TRANS, getDataType(), getValueType(), ExecType.CP);\nout.getOutputParameters().setDimensions(X.getDim2(), Y.getDim2(), getBlocksize(), getNnz());\nreturn out;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/Hop.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/Hop.java",
"diff": "@@ -1015,14 +1015,6 @@ public abstract class Hop implements ParseInfo\nPRINTF, CBIND, RBIND, MIN, MAX, EVAL, LIST\n}\n- public enum ReOrgOp {\n- TRANS, DIAG, RESHAPE, SORT, REV\n- //Note: Diag types are invalid because for unknown sizes this would\n- //create incorrect plans (now we try to infer it for memory estimates\n- //and rewrites but the final choice is made during runtime)\n- //DIAG_V2M, DIAG_M2V,\n- }\n-\npublic enum OpOpDnn {\nMAX_POOL, MAX_POOL_BACKWARD, AVG_POOL, AVG_POOL_BACKWARD,\nCONV2D, CONV2D_BACKWARD_FILTER, CONV2D_BACKWARD_DATA,\n@@ -1051,17 +1043,6 @@ public abstract class Hop implements ParseInfo\nHopsData2Lops.put(DataOpTypes.TRANSIENTREAD, org.tugraz.sysds.lops.Data.OperationTypes.READ);\n}\n- protected static final HashMap<ReOrgOp, org.tugraz.sysds.lops.Transform.OperationTypes> HopsTransf2Lops;\n- static {\n- HopsTransf2Lops = new HashMap<>();\n- HopsTransf2Lops.put(ReOrgOp.TRANS, org.tugraz.sysds.lops.Transform.OperationTypes.Transpose);\n- HopsTransf2Lops.put(ReOrgOp.REV, org.tugraz.sysds.lops.Transform.OperationTypes.Rev);\n- HopsTransf2Lops.put(ReOrgOp.DIAG, org.tugraz.sysds.lops.Transform.OperationTypes.Diag);\n- HopsTransf2Lops.put(ReOrgOp.RESHAPE, org.tugraz.sysds.lops.Transform.OperationTypes.Reshape);\n- HopsTransf2Lops.put(ReOrgOp.SORT, org.tugraz.sysds.lops.Transform.OperationTypes.Sort);\n-\n- }\n-\nprotected static final HashMap<OpOpDnn, org.tugraz.sysds.lops.DnnTransform.OperationTypes> HopsConv2Lops;\nstatic {\nHopsConv2Lops = new HashMap<>();\n@@ -1416,15 +1397,6 @@ public abstract class Hop implements ParseInfo\nHopsOpOp4String.put(OpOp4.WUMM, \"wumm\");\n}\n- protected static final HashMap<Hop.ReOrgOp, String> HopsTransf2String;\n- static {\n- HopsTransf2String = new HashMap<>();\n- HopsTransf2String.put(ReOrgOp.TRANS, \"t\");\n- HopsTransf2String.put(ReOrgOp.DIAG, \"diag\");\n- HopsTransf2String.put(ReOrgOp.RESHAPE, \"rshape\");\n- HopsTransf2String.put(ReOrgOp.SORT, \"sort\");\n- }\n-\nprotected static final HashMap<DataOpTypes, String> HopsData2String;\nstatic {\nHopsData2String = new HashMap<>();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/OptimizerUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/OptimizerUtils.java",
"diff": "@@ -25,6 +25,7 @@ import org.apache.log4j.Level;\nimport org.apache.log4j.Logger;\nimport org.tugraz.sysds.api.DMLScript;\nimport org.tugraz.sysds.common.Types.ExecMode;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.conf.CompilerConfig;\nimport org.tugraz.sysds.conf.CompilerConfig.ConfigType;\n@@ -33,7 +34,6 @@ import org.tugraz.sysds.conf.DMLConfig;\nimport org.tugraz.sysds.hops.Hop.DataOpTypes;\nimport org.tugraz.sysds.hops.Hop.FileFormatTypes;\nimport org.tugraz.sysds.hops.Hop.OpOp2;\n-import org.tugraz.sysds.hops.Hop.ReOrgOp;\nimport org.tugraz.sysds.hops.rewrite.HopRewriteUtils;\nimport org.tugraz.sysds.lops.Checkpoint;\nimport org.tugraz.sysds.lops.Lop;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/ParameterizedBuiltinOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/ParameterizedBuiltinOp.java",
"diff": "@@ -25,6 +25,7 @@ import org.tugraz.sysds.common.Types.AggOp;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.Direction;\nimport org.tugraz.sysds.common.Types.ParamBuiltinOp;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.hops.rewrite.HopRewriteUtils;\nimport org.tugraz.sysds.lops.Data;\n@@ -955,10 +956,8 @@ public class ParameterizedBuiltinOp extends MultiThreadedHop\nreturn ret;\n}\n- public boolean isTargetDiagInput()\n- {\n+ public boolean isTargetDiagInput() {\nHop targetHop = getTargetHop();\n-\n//input vector (guarantees diagV2M), implies remove rows\nreturn ( targetHop instanceof ReorgOp\n&& ((ReorgOp)targetHop).getOp()==ReOrgOp.DIAG\n@@ -971,7 +970,6 @@ public class ParameterizedBuiltinOp extends MultiThreadedHop\n*/\nprivate boolean isRemoveEmptyBcSP() // TODO find if 2 x size needed.\n{\n- boolean ret = false;\nHop input = getInput().get(0);\n//note: both cases (partitioned matrix, and sorted double array), require to\n@@ -983,11 +981,6 @@ public class ParameterizedBuiltinOp extends MultiThreadedHop\nOptimizerUtils.estimateSize(input.getDim1(), 1) : //dims known and estimate fits\ninput.getOutputMemEstimate(); //dims unknown but worst-case estimate fits\n- if( OptimizerUtils.checkSparkBroadcastMemoryBudget(size) ) {\n- ret = true;\n- }\n-\n- return ret;\n+ return OptimizerUtils.checkSparkBroadcastMemoryBudget(size);\n}\n-\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/ReorgOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/ReorgOp.java",
"diff": "@@ -23,12 +23,12 @@ package org.tugraz.sysds.hops;\nimport org.tugraz.sysds.api.DMLScript;\nimport org.tugraz.sysds.common.Types.DataType;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.hops.rewrite.HopRewriteUtils;\nimport org.tugraz.sysds.lops.Lop;\nimport org.tugraz.sysds.lops.LopProperties.ExecType;\nimport org.tugraz.sysds.lops.Transform;\n-import org.tugraz.sysds.lops.Transform.OperationTypes;\nimport org.tugraz.sysds.runtime.meta.DataCharacteristics;\nimport org.tugraz.sysds.runtime.meta.MatrixCharacteristics;\n@@ -107,7 +107,7 @@ public class ReorgOp extends MultiThreadedHop\n@Override\npublic String getOpString() {\n- return \"r(\" + HopsTransf2String.get(_op) + \")\";\n+ return \"r(\" + _op.getOpString() + \")\";\n}\n@Override\n@@ -154,14 +154,13 @@ public class ReorgOp extends MultiThreadedHop\ncase TRANS:\n{\nLop lin = getInput().get(0).constructLops();\n- if( lin instanceof Transform && ((Transform)lin).getOperationType()==OperationTypes.Transpose )\n+ if( lin instanceof Transform && ((Transform)lin).getOp()==ReOrgOp.TRANS )\nsetLops(lin.getInputs().get(0)); //if input is already a transpose, avoid redundant transpose ops\nelse if( getDim1()==1 && getDim2()==1 )\nsetLops(lin); //if input of size 1x1, avoid unnecessary transpose\nelse { //general case\nint k = OptimizerUtils.getConstrainedNumThreads(_maxNumThreads);\n- Transform transform1 = new Transform( lin,\n- HopsTransf2Lops.get(_op), getDataType(), getValueType(), et, k);\n+ Transform transform1 = new Transform(lin, _op, getDataType(), getValueType(), et, k);\nsetOutputDimensions(transform1);\nsetLineNumbers(transform1);\nsetLops(transform1);\n@@ -170,12 +169,12 @@ public class ReorgOp extends MultiThreadedHop\n}\ncase DIAG:\ncase REV: {\n- Transform transform1 = new Transform( getInput().get(0).constructLops(),\n- HopsTransf2Lops.get(_op), getDataType(), getValueType(), et);\n+ Transform transform1 = new Transform(\n+ getInput().get(0).constructLops(),\n+ _op, getDataType(), getValueType(), et);\nsetOutputDimensions(transform1);\nsetLineNumbers(transform1);\nsetLops(transform1);\n-\nbreak;\n}\ncase RESHAPE: {\n@@ -185,7 +184,7 @@ public class ReorgOp extends MultiThreadedHop\n_outputEmptyBlocks = (et == ExecType.SPARK &&\n!OptimizerUtils.allowsToFilterEmptyBlockOutputs(this));\nTransform transform1 = new Transform(linputs,\n- HopsTransf2Lops.get(_op), getDataType(), getValueType(), _outputEmptyBlocks, et);\n+ _op, getDataType(), getValueType(), _outputEmptyBlocks, et);\nsetOutputDimensions(transform1);\nsetLineNumbers(transform1);\n@@ -202,12 +201,12 @@ public class ReorgOp extends MultiThreadedHop\nif( et==ExecType.SPARK ) {\nboolean sortRewrite = !FORCE_DIST_SORT_INDEXES\n&& isSortSPRewriteApplicable() && by.getDataType().isScalar();\n- transform1 = new Transform( linputs, HopsTransf2Lops.get(ReOrgOp.SORT),\n+ transform1 = new Transform(linputs, ReOrgOp.SORT,\ngetDataType(), getValueType(), et, sortRewrite, 1); //#threads = 1\n}\nelse { //CP\nint k = OptimizerUtils.getConstrainedNumThreads(_maxNumThreads);\n- transform1 = new Transform( linputs, HopsTransf2Lops.get(ReOrgOp.SORT),\n+ transform1 = new Transform( linputs, ReOrgOp.SORT,\ngetDataType(), getValueType(), et, false, k);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/TernaryOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/TernaryOp.java",
"diff": "@@ -24,6 +24,7 @@ package org.tugraz.sysds.hops;\nimport org.tugraz.sysds.api.DMLScript;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.ParamBuiltinOp;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.conf.ConfigurationManager;\nimport org.tugraz.sysds.hops.rewrite.HopRewriteUtils;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/recompile/Recompiler.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/recompile/Recompiler.java",
"diff": "@@ -27,6 +27,7 @@ import org.apache.wink.json4j.JSONObject;\nimport org.tugraz.sysds.api.DMLScript;\nimport org.tugraz.sysds.api.jmlc.JMLCUtils;\nimport org.tugraz.sysds.common.Types.DataType;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.conf.CompilerConfig.ConfigType;\nimport org.tugraz.sysds.conf.ConfigurationManager;\n@@ -39,7 +40,6 @@ import org.tugraz.sysds.hops.Hop.DataGenMethod;\nimport org.tugraz.sysds.hops.Hop.DataOpTypes;\nimport org.tugraz.sysds.hops.Hop.FileFormatTypes;\nimport org.tugraz.sysds.hops.Hop.OpOp1;\n-import org.tugraz.sysds.hops.Hop.ReOrgOp;\nimport org.tugraz.sysds.hops.HopsException;\nimport org.tugraz.sysds.hops.IndexingOp;\nimport org.tugraz.sysds.hops.LiteralOp;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/HopRewriteUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/HopRewriteUtils.java",
"diff": "@@ -26,6 +26,7 @@ import org.tugraz.sysds.api.DMLScript;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.ExecMode;\nimport org.tugraz.sysds.common.Types.ParamBuiltinOp;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.conf.ConfigurationManager;\nimport org.tugraz.sysds.hops.AggBinaryOp;\n@@ -45,7 +46,6 @@ import org.tugraz.sysds.hops.Hop.OpOp2;\nimport org.tugraz.sysds.hops.Hop.OpOp3;\nimport org.tugraz.sysds.hops.Hop.OpOpDnn;\nimport org.tugraz.sysds.hops.Hop.OpOpN;\n-import org.tugraz.sysds.hops.Hop.ReOrgOp;\nimport org.tugraz.sysds.hops.HopsException;\nimport org.tugraz.sysds.hops.IndexingOp;\nimport org.tugraz.sysds.hops.LeftIndexingOp;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationDynamic.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationDynamic.java",
"diff": "@@ -46,13 +46,13 @@ import org.tugraz.sysds.hops.UnaryOp;\nimport org.tugraz.sysds.common.Types.AggOp;\nimport org.tugraz.sysds.common.Types.Direction;\nimport org.tugraz.sysds.common.Types.ParamBuiltinOp;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.hops.Hop.DataGenMethod;\nimport org.tugraz.sysds.hops.Hop.OpOp1;\nimport org.tugraz.sysds.hops.Hop.OpOp2;\nimport org.tugraz.sysds.hops.Hop.OpOp3;\nimport org.tugraz.sysds.hops.Hop.OpOp4;\nimport org.tugraz.sysds.hops.Hop.OpOpN;\n-import org.tugraz.sysds.hops.Hop.ReOrgOp;\nimport org.tugraz.sysds.lops.MapMultChain.ChainType;\nimport org.tugraz.sysds.parser.DataExpression;\nimport org.tugraz.sysds.common.Types.DataType;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"diff": "@@ -43,11 +43,11 @@ import org.tugraz.sysds.common.Types.AggOp;\nimport org.tugraz.sysds.hops.Hop.DataGenMethod;\nimport org.tugraz.sysds.common.Types.Direction;\nimport org.tugraz.sysds.common.Types.ParamBuiltinOp;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.hops.Hop.OpOp1;\nimport org.tugraz.sysds.hops.Hop.OpOp2;\nimport org.tugraz.sysds.hops.Hop.OpOp3;\nimport org.tugraz.sysds.hops.Hop.OpOpN;\n-import org.tugraz.sysds.hops.Hop.ReOrgOp;\nimport org.tugraz.sysds.parser.DataExpression;\nimport org.tugraz.sysds.parser.Statement;\nimport org.tugraz.sysds.common.Types.DataType;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteGPUSpecificOps.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteGPUSpecificOps.java",
"diff": "@@ -38,10 +38,10 @@ import org.tugraz.sysds.hops.FunctionOp.FunctionType;\nimport org.tugraz.sysds.common.Types.AggOp;\nimport org.tugraz.sysds.hops.Hop.DataOpTypes;\nimport org.tugraz.sysds.common.Types.Direction;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.hops.Hop.OpOp1;\nimport org.tugraz.sysds.hops.Hop.OpOp2;\nimport org.tugraz.sysds.hops.Hop.OpOpDnn;\n-import org.tugraz.sysds.hops.Hop.ReOrgOp;\nimport org.tugraz.sysds.parser.DMLProgram;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.runtime.instructions.gpu.context.GPUContextPool;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteSplitDagDataDependentOperators.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteSplitDagDataDependentOperators.java",
"diff": "@@ -28,6 +28,7 @@ import java.util.List;\nimport org.tugraz.sysds.api.DMLScript;\nimport org.tugraz.sysds.common.Types.ExecMode;\nimport org.tugraz.sysds.common.Types.ParamBuiltinOp;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.conf.ConfigurationManager;\nimport org.tugraz.sysds.hops.AggBinaryOp;\nimport org.tugraz.sysds.hops.DataOp;\n@@ -40,7 +41,6 @@ import org.tugraz.sysds.hops.Hop.DataOpTypes;\nimport org.tugraz.sysds.hops.Hop.OpOp1;\nimport org.tugraz.sysds.hops.Hop.OpOp3;\nimport org.tugraz.sysds.hops.Hop.OpOpN;\n-import org.tugraz.sysds.hops.Hop.ReOrgOp;\nimport org.tugraz.sysds.hops.recompile.Recompiler;\nimport org.tugraz.sysds.parser.DataIdentifier;\nimport org.tugraz.sysds.parser.StatementBlock;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/lops/Transform.java",
"new_path": "src/main/java/org/tugraz/sysds/lops/Transform.java",
"diff": "@@ -25,6 +25,7 @@ package org.tugraz.sysds.lops;\nimport org.tugraz.sysds.lops.LopProperties.ExecType;\nimport org.tugraz.sysds.common.Types.DataType;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\n@@ -34,75 +35,63 @@ import org.tugraz.sysds.common.Types.ValueType;\n*/\npublic class Transform extends Lop\n{\n- public enum OperationTypes {\n- Transpose,\n- Diag,\n- Reshape,\n- Sort,\n- Rev\n- }\n-\n- private OperationTypes operation = null;\n+ private ReOrgOp _operation = null;\nprivate boolean _bSortIndInMem = false;\nprivate boolean _outputEmptyBlock = true;\nprivate int _numThreads = 1;\n- public Transform(Lop input, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et) {\n+ public Transform(Lop input, ReOrgOp op, DataType dt, ValueType vt, ExecType et) {\nthis(input, op, dt, vt, et, 1);\n}\n- public Transform(Lop[] inputs, Transform.OperationTypes op, DataType dt, ValueType vt, boolean outputEmptyBlock, ExecType et) {\n+ public Transform(Lop[] inputs, ReOrgOp op, DataType dt, ValueType vt, boolean outputEmptyBlock, ExecType et) {\nthis(inputs, op, dt, vt, et, 1);\n_outputEmptyBlock = outputEmptyBlock;\n}\n- public Transform(Lop input, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et, int k) {\n+ public Transform(Lop input, ReOrgOp op, DataType dt, ValueType vt, ExecType et, int k) {\nsuper(Lop.Type.Transform, dt, vt);\ninit(new Lop[]{input}, op, dt, vt, et);\n_numThreads = k;\n}\n- public Transform(Lop[] inputs, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et, int k) {\n+ public Transform(Lop[] inputs, ReOrgOp op, DataType dt, ValueType vt, ExecType et, int k) {\nsuper(Lop.Type.Transform, dt, vt);\ninit(inputs, op, dt, vt, et);\n_numThreads = k;\n}\n- public Transform(Lop input, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et, boolean bSortIndInMem) {\n+ public Transform(Lop input, ReOrgOp op, DataType dt, ValueType vt, ExecType et, boolean bSortIndInMem) {\nsuper(Lop.Type.Transform, dt, vt);\n_bSortIndInMem = bSortIndInMem;\ninit(new Lop[]{input}, op, dt, vt, et);\n}\n- public Transform(Lop[] inputs, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et, boolean bSortIndInMem) {\n+ public Transform(Lop[] inputs, ReOrgOp op, DataType dt, ValueType vt, ExecType et, boolean bSortIndInMem) {\nsuper(Lop.Type.Transform, dt, vt);\n_bSortIndInMem = bSortIndInMem;\ninit(inputs, op, dt, vt, et);\n}\n- public Transform(Lop[] inputs, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et, boolean bSortIndInMem, int k) {\n+ public Transform(Lop[] inputs, ReOrgOp op, DataType dt, ValueType vt, ExecType et, boolean bSortIndInMem, int k) {\nsuper(Lop.Type.Transform, dt, vt);\n_bSortIndInMem = bSortIndInMem;\n_numThreads = k;\ninit(inputs, op, dt, vt, et);\n}\n- private void init (Lop[] input, Transform.OperationTypes op, DataType dt, ValueType vt, ExecType et)\n- {\n- operation = op;\n-\n+ private void init (Lop[] input, ReOrgOp op, DataType dt, ValueType vt, ExecType et) {\n+ _operation = op;\nfor(Lop in : input) {\nthis.addInput(in);\nin.addOutput(this);\n}\n-\nlps.setProperties(inputs, et);\n}\n@Override\npublic String toString() {\n-\n- return \" Operation: \" + operation;\n+ return \" Operation: \" + _operation;\n}\n/**\n@@ -110,35 +99,35 @@ public class Transform extends Lop\n* @return operaton type\n*/\n- public OperationTypes getOperationType()\n- {\n- return operation;\n+ public ReOrgOp getOp() {\n+ return _operation;\n}\nprivate String getOpcode() {\n- switch(operation) {\n- case Transpose:\n+ switch(_operation) {\n+ case TRANS:\n// Transpose a matrix\nreturn \"r'\";\n- case Rev:\n+ case REV:\n// Transpose a matrix\nreturn \"rev\";\n- case Diag:\n+ case DIAG:\n// Transform a vector into a diagonal matrix\nreturn \"rdiag\";\n- case Reshape:\n+ case RESHAPE:\n// Transform a vector into a diagonal matrix\nreturn \"rshape\";\n- case Sort:\n+ case SORT:\n// Transform a matrix into a sorted matrix\nreturn \"rsort\";\ndefault:\n- throw new UnsupportedOperationException(this.printErrorLocation() + \"Instruction is not defined for Transform operation \" + operation);\n+ throw new UnsupportedOperationException(printErrorLocation()\n+ + \"Instruction is not defined for Transform operation \" + _operation);\n}\n}\n@@ -181,19 +170,16 @@ public class Transform extends Lop\nsb.append( OPERAND_DELIMITOR );\nsb.append( this.prepOutputOperand(output));\n- if( getExecType()==ExecType.CP && operation == OperationTypes.Transpose ) {\n- sb.append( OPERAND_DELIMITOR );\n- sb.append( _numThreads );\n- }\n- if( getExecType()==ExecType.CP && operation == OperationTypes.Sort ) {\n+ if( getExecType()==ExecType.CP\n+ && (_operation == ReOrgOp.TRANS || _operation == ReOrgOp.SORT) ) {\nsb.append( OPERAND_DELIMITOR );\nsb.append( _numThreads );\n}\n- if( getExecType()==ExecType.SPARK && operation == OperationTypes.Reshape ) {\n+ if( getExecType()==ExecType.SPARK && _operation == ReOrgOp.RESHAPE ) {\nsb.append( OPERAND_DELIMITOR );\nsb.append( _outputEmptyBlock );\n}\n- if( getExecType()==ExecType.SPARK && operation == OperationTypes.Sort ){\n+ if( getExecType()==ExecType.SPARK && _operation == ReOrgOp.SORT ){\nsb.append( OPERAND_DELIMITOR );\nsb.append( _bSortIndInMem );\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/DMLTranslator.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/DMLTranslator.java",
"diff": "@@ -49,7 +49,6 @@ import org.tugraz.sysds.hops.Hop.OpOp2;\nimport org.tugraz.sysds.hops.Hop.OpOp3;\nimport org.tugraz.sysds.hops.Hop.OpOpDnn;\nimport org.tugraz.sysds.hops.Hop.OpOpN;\n-import org.tugraz.sysds.hops.Hop.ReOrgOp;\nimport org.tugraz.sysds.hops.HopsException;\nimport org.tugraz.sysds.hops.IndexingOp;\nimport org.tugraz.sysds.hops.LeftIndexingOp;\n@@ -77,6 +76,7 @@ import org.tugraz.sysds.common.Types.AggOp;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.Direction;\nimport org.tugraz.sysds.common.Types.ParamBuiltinOp;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.parser.Expression.FormatType;\nimport org.tugraz.sysds.parser.PrintStatement.PRINTTYPE;\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-12] Cleanup unnecessary reorg hop/lop type indirections |
49,720 | 15.02.2020 22:00:10 | -3,600 | 8df07bfe9eaa7320606c02579b44471f8ede57f8 | Improved functional dependency discovery (discoverFD)
1. Included Mask and threshold as input parameters
2. Output Matrix FD contains the scores for FDs
Closes | [
{
"change_type": "MODIFY",
"old_path": "scripts/builtin/discoverFD.dml",
"new_path": "scripts/builtin/discoverFD.dml",
"diff": "# ---------------------------------------------------------------------------------------------\n# NAME TYPE DEFAULT MEANING\n# ---------------------------------------------------------------------------------------------\n-# TODO\n+# X Double -- Input Matrix X, encoded Matrix if data is categorical\n+# Mask Double -- A row vector for interested features i.e. Mask =[1, 0, 1]\n+ # will exclude the second column from processing\n+# threshold Double -- threshold value in interval [0, 1] for robust FDs\n+# ---------------------------------------------------------------------------------------------\n+\n#Output(s)\n# ---------------------------------------------------------------------------------------------\n# ---------------------------------------------------------------------------------------------\n# FD Double --- matrix of functional dependencies\n-m_discoverFD = function(Matrix[Double] X)\n+m_discoverFD = function(Matrix[Double] X, Matrix[Double] Mask, Double threshold)\nreturn(Matrix[Double] FD)\n{\n- #TODO pass mask of relevant columns (only integer/boolean)\n- # remove known dependencies and only iterate over pairs for relevant cols\n+ if( threshold < 0 | threshold > 1 )\n+ stop(\"Stopping due to invalid input, threshold required in interval [0, 1] found \"+threshold)\n+\n+ if(ncol(X) != ncol(Mask))\n+ stop(\"Stopping due to dimension mismatch in Matrix and it's Mask\")\n+\n+ if( nrow(Mask) > 1 )\n+ stop(\"Stopping due to invalid input, Mask required n * 1 found n * \"+nrow(Mask))\n+\n+ # feature pruning using mask (keep interested features only for FD discovery)\n+ X = removeEmpty(target = X, margin = \"cols\", select=Mask)\n# allocate output and working sets\n- n = ncol(X)\n- FD = matrix(0, n, n)\n+ n = nrow(X)\n+ d = ncol(X)\n+ FD = matrix(0, d, d)\n+ cm = matrix(0, 1, d)\n- # compute summary statistics (assumes integer codes)\n- #TODO parfor over colDistinct instead (to work not just with recoded)\n- cm = colMaxs(X) # num distinct per column\n+ # num distinct per column\n+ parfor(i in 1:d)\n+ cm[1,i] = colDistinct(X[,i])\n# add know functional dependencies\nFD = FD + (cm == 1) # constant columns determined by all columns\nFD = FD + (t(cm) == n) # unique columns determine all columns\n+ FD = FD != 0 # to keep the count consistent\n# sort num distinct and enumerate only upper triangle\ncm2 = order(target=t(cm), decreasing=TRUE, index.return=TRUE)\n- parfor(i in 1 : n, check=0) {\n+ parfor(i in 1 : d, check=0) {\nindex_i = as.scalar(cm2[i,1])\nndX = as.scalar(cm[1,index_i])\nif( ndX!=1 & ndX!=n) {\nXi = X[,index_i];\n- parfor(j in i+1:n, check=0) {\n+ k = ifelse(threshold < 1, 1, (i+1)); # enumerate only upper triangle if threshold = 1\n+ parfor(j in k:d , check=0) {\n+ if(j != i) {\nindex_j = as.scalar(cm2[j,1])\n- ndY = as.scalar(cm[1,index_j])\n- [A_determines_B, del] = isFD(Xi, X[,index_j], ndX, ndY);\n- if(A_determines_B & del > 0.8)\n- FD[index_i, index_j] = 1\n+ [A_determines_B, ratio] = isFD(Xi, X[,index_j], ndX);\n+ if(A_determines_B | ratio >= threshold)\n+ FD[index_i, index_j] = ratio; # matrix of robust FD with their ratios\n+ }\n}\n}\n}\n}\n-isFD = function(Matrix[Double] X, Matrix[Double] Y, Integer ndX, Integer ndY)\n- return(Boolean A_determines_B, Double delta)\n+isFD = function(Matrix[Double] X, Matrix[Double] Y, Integer ndX)\n+ return(Boolean A_determines_B, Double ratio)\n{\n- ctab = table(X, Y, ndX, ndY)\n+ ctab = table(X, Y)\nrowSumTable = rowSums(ctab != 0) # X values -> num Y values\nA_determines_B = (sum(rowSumTable==1) == ndX);\n# robust functional dependency ratio (1.0 if A -> B)\n- delta = sum(rowMaxs(ctab)) / nrow(X)\n+ ratio = sum(rowMaxs(ctab)) / nrow(X)\n}\ncolDistinct = function(Matrix[Double] X)\n- return(double distinctItems)\n+ return(Double distinctItems)\n{\ndistinctItems = sum(table(X, 1) != 0)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinFDTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinFDTest.java",
"diff": "@@ -30,13 +30,6 @@ public class BuiltinFDTest extends AutomatedTestBase {\nprivate final static String TEST_DIR = \"functions/builtin/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + BuiltinFDTest.class.getSimpleName() + \"/\";\n-// private final static double eps = 0.001;\n-// private final static int rows = 1000;\n-// private final static int colsX = 500;\n-// private final static double spSparse = 0.01;\n-// private final static double spDense = 0.7;\n-// private final static int max_iter = 10;\n-\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n@@ -46,35 +39,48 @@ public class BuiltinFDTest extends AutomatedTestBase {\n@Test\npublic void testFD1() {\ndouble[][] X = {{7,1,1,2,2,1},{7,2,2,3,2,1},{7,3,1,4,1,1},{7,4,2,5,3,1},{7,5,3,6,5,1}, {7,6,5,1,4,1}};\n- runFDTests(X, LopProperties.ExecType.CP);\n+ double[][] M = {{0, 1, 1, 0, 1, 1}};\n+ runFDTests(X, M, 1, LopProperties.ExecType.CP );\n}\n@Test\npublic void testFD2() {\ndouble[][] X = {{1,1,1,1,1},{2,1,2,2,1},{3,2,1,1,1},{4,2,2,2,1},{5,3,3,1,1}};\n- runFDTests(X, LopProperties.ExecType.CP);\n+ double[][] M = {{1, 1, 1, 1, 1}};\n+ runFDTests(X, M, 0.8, LopProperties.ExecType.CP );\n}\n@Test\npublic void testFD3() {\ndouble[][] X = {{1,1},{2,1},{3,2},{2,2},{4,2}, {5,3}};\n- runFDTests(X, LopProperties.ExecType.CP);\n+ double[][] M = {{0, 1}};\n+ runFDTests(X, M, 0.8, LopProperties.ExecType.CP );\n}\n+\n@Test\npublic void testFD4() {\ndouble[][] X = {{1,1,1,1,1,1,2},{2,1,2,2,1,2,2},{3,2,1,1,1,3,2},{4,2,2,2,1,4,2},{5,3,3,1,1,5,1}};\n- runFDTests(X, LopProperties.ExecType.CP);\n+ double[][] M = {{0, 1, 1, 1, 0, 1, 1}};\n+ runFDTests(X, M, 0.8, LopProperties.ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testFD5() {\n+ double[][] X = {{7,1,1,2,2,1},{7,2,2,3,2,1},{7,3,1,4,1,1},{7,4,2,5,3,1},{7,5,3,6,5,1}, {7,6,5,1,4,1}};\n+ double[][] M = {{0, 1, 1, 0, 1, 1}};\n+ runFDTests(X, M, 0.8, LopProperties.ExecType.CP );\n}\n- private void runFDTests(double [][] X , LopProperties.ExecType instType) {\n+ private void runFDTests(double [][] X , double[][] M, double threshold, LopProperties.ExecType instType) {\nTypes.ExecMode platformOld = setExecMode(instType);\ntry\n{\nloadTestConfiguration(getTestConfiguration(TEST_NAME));\nString HOME = SCRIPT_DIR + TEST_DIR;\nfullDMLScriptName = HOME + TEST_NAME + \".dml\";\n- programArgs = new String[]{\"-stats\",\"-args\", input(\"X\")};\n+ programArgs = new String[]{\"-stats\",\"-args\", input(\"X\"), input(\"M\"), String.valueOf(threshold), output(\"B\")};\nwriteInputMatrixWithMTD(\"X\", X, true);\n+ writeInputMatrixWithMTD(\"M\", M, true);\nrunTest(true, false, null, -1);\n}\nfinally {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/builtin/functional_dependency.dml",
"new_path": "src/test/scripts/functions/builtin/functional_dependency.dml",
"diff": "#-------------------------------------------------------------\nX = read($1)\n-C = discoverFD(X)\n-print(sum(C))\n\\ No newline at end of file\n+M = read($2)\n+C = discoverFD(X, M, $3)\n+write(C, $4)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-197] Improved functional dependency discovery (discoverFD)
1. Included Mask and threshold as input parameters
2. Output Matrix FD contains the scores for FDs
Closes #95. |
49,750 | 15.02.2020 22:30:05 | -3,600 | f5394e9684a0757a7ae47992200efbc697f38a37 | Data augmentation tool for data cleaning primitives
DIA project data augmentation for data cleaning (outliers, missing
values, typos, swapped columns)
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -189,8 +189,9 @@ SYSTEMDS-240 GPU Backend Improvements\nSYSTEMDS-250 Large-Scale Slice Finding\n* 251 Initial data slicing implementation Python\n-SYSTEMDS-260 Algorithms\n+SYSTEMDS-260 Misc Tools\n* 261 Stable marriage algorithm OK\n+ * 262 Data augmentation tool for data cleaning OK\nOthers:\n* Break append instruction to cbind and rbind\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/MatrixBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/MatrixBlock.java",
"diff": "@@ -2605,7 +2605,7 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab\n// Core block operations (called from instructions)\n@Override\n- public MatrixValue scalarOperations(ScalarOperator op, MatrixValue result) {\n+ public MatrixBlock scalarOperations(ScalarOperator op, MatrixValue result) {\nMatrixBlock ret = checkType(result);\n// estimate the sparsity structure of result matrix\n@@ -2626,7 +2626,7 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab\n}\n@Override\n- public MatrixValue unaryOperations(UnaryOperator op, MatrixValue result) {\n+ public MatrixBlock unaryOperations(UnaryOperator op, MatrixValue result) {\nMatrixBlock ret = checkType(result);\n// estimate the sparsity structure of result matrix\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/org/tugraz/sysds/utils/DataAugmentation.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ *\n+ */\n+\n+package org.tugraz.sysds.utils;\n+\n+import java.util.ArrayList;\n+import java.util.Arrays;\n+import java.util.HashMap;\n+import java.util.List;\n+import java.util.Map;\n+import java.util.Random;\n+\n+import org.tugraz.sysds.common.Types.ValueType;\n+import org.tugraz.sysds.runtime.instructions.InstructionUtils;\n+import org.tugraz.sysds.runtime.matrix.data.FrameBlock;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\n+import org.tugraz.sysds.runtime.util.DataConverter;\n+\n+public class DataAugmentation\n+{\n+ /**\n+ * This function returns a new frame block with error introduced in the data:\n+ * Typos in string values, null values, outliers in numeric data and swapped elements.\n+ *\n+ * @param input Original frame block\n+ * @param pTypo Probability of introducing a typo in a row\n+ * @param pMiss Probability of introducing missing values in a row\n+ * @param pDrop Probability of dropping a value inside a row\n+ * @param pOut Probability of introducing outliers in a row\n+ * @param pSwap Probability swapping two elements in a row\n+ * @return A new frameblock with corrupted elements\n+ *\n+ */\n+ public static FrameBlock dataCorruption(FrameBlock input, double pTypo, double pMiss, double pDrop, double pOut, double pSwap) {\n+ List<Integer> numerics = new ArrayList<>();\n+ List<Integer> strings = new ArrayList<>();\n+ List<Integer> swappable = new ArrayList<>();\n+\n+ FrameBlock res = preprocessing(input, numerics, strings, swappable);\n+ res = typos(res, strings, pTypo);\n+ res = miss(res, pMiss, pDrop);\n+ res = outlier(res, numerics, pOut, 0.5, 3);\n+\n+ return res;\n+ }\n+\n+ /**\n+ * This function returns a new frame block with a labels column added, and build the lists\n+ * with column index of the different types of data.\n+ *\n+ * @param frame Original frame block\n+ * @param numerics Empty list to return the numeric positions\n+ * @param strings Empty list to return the string positions\n+ * @param swappable Empty list to return the swappable positions\n+ * @return A new frameblock with a labels column\n+ *\n+ */\n+ public static FrameBlock preprocessing(FrameBlock frame, List<Integer> numerics, List<Integer> strings, List<Integer> swappable) {\n+ FrameBlock res = new FrameBlock(frame);\n+ for(int i=0;i<res.getNumColumns();i++) {\n+ if(res.getSchema()[i].isNumeric())\n+ numerics.add(i);\n+ else if(res.getSchema()[i].equals(ValueType.STRING))\n+ strings.add(i);\n+ if(i!=res.getNumColumns()-1 && res.getSchema()[i].equals(res.getSchema()[i+1]))\n+ swappable.add(i);\n+ }\n+\n+ String[] labels = new String[res.getNumRows()];\n+ Arrays.fill(labels, \"\");\n+ res.appendColumn(labels);\n+ res.getColumnNames()[res.getNumColumns()-1] = \"errorLabels\";\n+\n+ return res;\n+ }\n+\n+ /**\n+ * This function modifies the given, preprocessed frame block to add typos to the string values,\n+ * marking them with the label typos.\n+ *\n+ * @param frame Original frame block\n+ * @param strings List with the columns of string type that can be changed, generated during preprocessing or manually selected\n+ * @param pTypo Probability of adding a typo to a row\n+ * @return A new frameblock with typos\n+ *\n+ */\n+ public static FrameBlock typos(FrameBlock frame, List<Integer> strings, double pTypo)\n+ {\n+ if(!frame.getColumnName(frame.getNumColumns()-1).equals(\"errorLabels\")) {\n+ throw new IllegalArgumentException(\"The FrameBlock passed has not been preprocessed.\");\n+ }\n+ if(strings.isEmpty())\n+ return frame;\n+\n+ Random rand = new Random();\n+ for(int r=0;r<frame.getNumRows();r++) {\n+ int c = strings.get(rand.nextInt(strings.size()));\n+ String s = (String) frame.get(r, c);\n+ if(s.length()!=1 && rand.nextDouble()<=pTypo) {\n+ int i = rand.nextInt(s.length());\n+ if(i==s.length()-1) s = swapchr(s, i-1, i);\n+ else if(i==0) s = swapchr(s, i, i+1);\n+ else if(rand.nextDouble()<=0.5) s = swapchr(s, i, i+1);\n+ else s = swapchr(s, i-1, i);\n+ frame.set(r, c, s);\n+ String label = (String) frame.get(r, frame.getNumColumns()-1);\n+ frame.set(r, frame.getNumColumns()-1,\n+ label.equals(\"\") ? \"typo\" : (label + \",typo\"));\n+ }\n+ }\n+ return frame;\n+ }\n+\n+ /**\n+ * This function modifies the given, preprocessed frame block to add missing values to some of the rows,\n+ * marking them with the label missing.\n+ *\n+ * @param frame Original frame block\n+ * @param pMiss Probability of adding missing values to a row\n+ * @param pTypo Probability of dropping a value from a row previously selected by pTypo\n+ * @return A new frameblock with missing values\n+ *\n+ */\n+ public static FrameBlock miss(FrameBlock frame, double pMiss, double pDrop) {\n+ if(!frame.getColumnName(frame.getNumColumns()-1).equals(\"errorLabels\")) {\n+ throw new IllegalArgumentException(\"The FrameBlock passed has not been preprocessed.\");\n+ }\n+ Random rand = new Random();\n+ for(int r=0;r<frame.getNumRows();r++) {\n+ if(rand.nextDouble()<=pMiss) {\n+ int dropped = 0;\n+ for(int c=0;c<frame.getNumColumns()-1;c++) {\n+ Object xi = frame.get(r, c);\n+ if(xi!=null && !xi.equals(0) && rand.nextDouble()<=pDrop) {\n+ frame.set(r, c, null);\n+ dropped++;\n+ }\n+ }\n+ if(dropped>0) {\n+ String label = (String) frame.get(r, frame.getNumColumns()-1);\n+ frame.set(r, frame.getNumColumns()-1,\n+ label.equals(\"\") ? \"missing\" : (label + \",missing\"));\n+ }\n+ }\n+ }\n+ return frame;\n+ }\n+\n+ /**\n+ * This function modifies the given, preprocessed frame block to add outliers to some\n+ * of the numeric data of the frame, adding or several times the standard deviation,\n+ * and marking them with the label outlier.\n+ *\n+ * @param frame Original frame block\n+ * @param numerics List with the columns of numeric type that can be changed, generated during preprocessing or manually selected\n+ * @param pOut Probability of introducing an outlier in a row\n+ * @param pPos Probability of using positive deviation\n+ * @param times Times the standard deviation is added\n+ * @return A new frameblock with outliers\n+ *\n+ */\n+ public static FrameBlock outlier(FrameBlock frame, List<Integer> numerics, double pOut, double pPos, int times) {\n+\n+ if(!frame.getColumnName(frame.getNumColumns()-1).equals(\"errorLabels\")) {\n+ throw new IllegalArgumentException(\"The FrameBlock passed has not been preprocessed.\");\n+ }\n+ if(numerics.isEmpty())\n+ return frame;\n+\n+ Map<Integer, Double> stds = new HashMap<>();\n+ Random rand = new Random();\n+ for(int r=0;r<frame.getNumRows();r++) {\n+ if(rand.nextDouble()>pOut) continue;\n+ int c = numerics.get(rand.nextInt(numerics.size()));\n+ if(!stds.containsKey(c)) {\n+ FrameBlock ftmp = frame.slice(0,\n+ frame.getNumColumns()-1, c, c, new FrameBlock());\n+ MatrixBlock mtmp = DataConverter.convertToMatrixBlock(ftmp);\n+ double sum = mtmp.sum();\n+ double mean = sum/mtmp.getNumRows();\n+ MatrixBlock diff = mtmp.scalarOperations(InstructionUtils\n+ .parseScalarBinaryOperator(\"-\", false, mean), new MatrixBlock());\n+ double sumsq = diff.sumSq();\n+ stds.put(c, Math.sqrt(sumsq/mtmp.getNumRows()));\n+ }\n+ Double std = stds.get(c);\n+ boolean pos = rand.nextDouble()<=pPos;\n+ switch(frame.getSchema()[c]) {\n+ case INT32: {\n+ Integer val = (Integer) frame.get(r, c);\n+ frame.set(r, c, val + (pos?1:-1)*(int)Math.round(times*std));\n+ break;\n+ }\n+ case INT64: {\n+ Long val = (Long) frame.get(r, c);\n+ frame.set(r, c, val + (pos?1:-1)*Math.round(times*std));\n+ break;\n+ }\n+ case FP32: {\n+ Float val = (Float) frame.get(r, c);\n+ frame.set(r, c, val + (pos?1:-1)*(float)(times*std));\n+ break;\n+ }\n+ case FP64: {\n+ Double val = (Double) frame.get(r, c);\n+ frame.set(r, c, val + (pos?1:-1)*times*std);\n+ break;\n+ }\n+ default: //do nothing\n+ }\n+ String label = (String) frame.get(r, frame.getNumColumns()-1);\n+ frame.set(r, frame.getNumColumns()-1,\n+ label.equals(\"\") ? \"outlier\": (label + \",outlier\"));\n+ }\n+\n+ return frame;\n+ }\n+\n+ /**\n+ * This function modifies the given, preprocessed frame block to add swapped fields of the same ValueType\n+ * that are consecutive, marking them with the label swap.\n+ *\n+ * @param frame Original frame block\n+ * @param swappable List with the columns that are swappable, generated during preprocessing\n+ * @param pSwap Probability of swapping two fields in a row\n+ * @return A new frameblock with swapped elements\n+ *\n+ */\n+ public static FrameBlock swap(FrameBlock frame, List<Integer> swappable, double pSwap) {\n+ if(!frame.getColumnName(frame.getNumColumns()-1).equals(\"errorLabels\")) {\n+ throw new IllegalArgumentException(\"The FrameBlock passed has not been preprocessed.\");\n+ }\n+ Random rand = new Random();\n+ for(int r=0;r<frame.getNumRows();r++) {\n+ if(rand.nextDouble()<=pSwap) {\n+ int i = swappable.get(rand.nextInt(swappable.size()));\n+ Object tmp = frame.get(r, i);\n+ frame.set(r, i, frame.get(r, i+1));\n+ frame.set(r, i+1, tmp);\n+ String label = (String) frame.get(r, frame.getNumColumns()-1);\n+ frame.set(r, frame.getNumColumns()-1,\n+ label.equals(\"\") ? \"swap\" : (label + \",swap\"));\n+ }\n+ }\n+ return frame;\n+ }\n+\n+ private static String swapchr(String str, int i, int j) {\n+ if (j == str.length() - 1)\n+ return str.substring(0, i) + str.charAt(j)\n+ + str.substring(i + 1, j) + str.charAt(i);\n+ return str.substring(0, i) + str.charAt(j)\n+ + str.substring(i + 1, j) + str.charAt(i)\n+ + str.substring(j + 1, str.length());\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/component/frame/DataCorruptionTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ *\n+ */\n+\n+package org.tugraz.sysds.test.component.frame;\n+\n+import static org.junit.Assert.assertEquals;\n+import static org.junit.Assert.assertTrue;\n+\n+import java.util.ArrayList;\n+import java.util.List;\n+import java.util.Random;\n+\n+import org.junit.Before;\n+import org.junit.BeforeClass;\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types.ValueType;\n+import org.tugraz.sysds.runtime.matrix.data.FrameBlock;\n+import org.tugraz.sysds.utils.DataAugmentation;\n+\n+public class DataCorruptionTest\n+{\n+ private static FrameBlock X; // original\n+ private FrameBlock Xp; // changed\n+ private List<Integer> numerics;\n+ private List<Integer> stringpos;\n+ private List<Integer> swappable;\n+\n+ // Set input frame\n+ @BeforeClass\n+ public static void init() {\n+ ValueType[] schema = new ValueType[] {ValueType.STRING, ValueType.STRING, ValueType.INT32, ValueType.FP64};\n+ X = new FrameBlock(schema);\n+ String[] strings = new String[] {\n+ \"Toyota\", \"Mercedes\", \"BMW\", \"Volkswagen\", \"Skoda\" };\n+ String[] strings2 = new String[] {\n+ \"Austria\", \"Spain\", \"France\", \"United Kingdom\"};\n+ Random rand = new Random();\n+\n+ for(int i = 0; i<1000; i++) {\n+ Object[] row = new Object[4];\n+ row[0] = strings[rand.nextInt(strings.length)];\n+ row[1] = strings2[rand.nextInt(strings2.length)];\n+ row[2] = rand.nextInt(1000);\n+ row[3] = rand.nextGaussian();\n+ X.appendRow(row);\n+ }\n+ }\n+\n+ // Reset lists and output frame\n+ @Before\n+ public void testInit() {\n+ numerics = new ArrayList<Integer>();\n+ stringpos = new ArrayList<Integer>();\n+ swappable = new ArrayList<Integer>();\n+ Xp = DataAugmentation.preprocessing(X, numerics, stringpos, swappable);\n+ }\n+\n+ @Test\n+ public void testTypos() {\n+ Xp = DataAugmentation.typos(Xp, stringpos, 0.2);\n+\n+ double numch = 0.;\n+ for(int i=0;i<Xp.getNumRows();i++) {\n+ String label = (String) Xp.get(i, Xp.getNumColumns()-1);\n+ if(label.equals(\"typo\")) {\n+ numch++;\n+ boolean checkTypo = false;\n+ for(int c:stringpos) {\n+ String val = (String) X.get(i, c);\n+ String valch = (String) Xp.get(i, c);\n+ checkTypo = checkTypo || !val.equals(valch);\n+ if(checkTypo) break;\n+ }\n+ assertTrue(\"Row \"+i+\" was marked with typos, but it has not been changed.\", checkTypo);\n+ }\n+ }\n+ System.out.println(\"Test typos: number of changed rows: \" + numch);\n+ assertEquals(\"The number of changed rows is not approx. 20%\", 0.2, numch/Xp.getNumRows(), 0.05);\n+ }\n+\n+ @Test\n+ public void testMiss() {\n+ Xp = DataAugmentation.miss(Xp, 0.2, 0.7);\n+\n+ double numch = 0.;\n+ for(int i=0;i<Xp.getNumRows();i++) {\n+ String label = (String) Xp.get(i, Xp.getNumColumns()-1);\n+ if(label.equals(\"missing\")) {\n+ int dropped = 0;\n+ for(int c=0;c<X.getNumColumns();c++) {\n+ Object xi = X.get(i, c);\n+ Object xpi = Xp.get(i, c);\n+ if((xi!=null && !xi.equals(0) && !xi.equals(0d) && !xi.equals(0L) && !xi.equals(0f))\n+ && (xpi==null || xpi.equals(0) || xpi.equals(0d) || xpi.equals(0L) || xpi.equals(0f)))\n+ dropped++;\n+ }\n+ numch++;\n+ assertTrue(\"Row \"+i+\" was marked with missing values, but it has not been changed.\", dropped>0);\n+ }\n+ }\n+ System.out.println(\"Test missing: number of changed rows: \" + numch);\n+ assertEquals(\"The number of changed rows is not approx. 20%\", 0.2, numch/Xp.getNumRows(), 0.05);\n+ }\n+\n+ @Test\n+ public void testOutliers() {\n+ Xp = DataAugmentation.outlier(Xp, numerics, 0.2, 0.5, 3);\n+\n+ double numch = 0.;\n+ for(int i=0;i<Xp.getNumRows();i++) {\n+ String label = (String) Xp.get(i, Xp.getNumColumns()-1);\n+ if(label.equals(\"outlier\")) {\n+ numch++;\n+ boolean checkOut = false;\n+ for(int c:numerics) {\n+ switch(Xp.getSchema()[c]) {\n+ case INT32:\n+ case INT64:\n+ case FP32:\n+ case FP64:\n+ Object val = X.get(i, c);\n+ Object valch = Xp.get(i, c);\n+ checkOut = checkOut || !val.equals(valch);\n+ break;\n+ default:\n+ //do nothing\n+ }\n+ if(checkOut)\n+ break;\n+ }\n+ assertTrue(\"Row \"+i+\" was marked with outliers, but it has not been changed.\", checkOut);\n+ }\n+ }\n+ System.out.println(\"Test outliers: number of changed rows: \" + numch);\n+ assertEquals(\"The number of changed rows is not approx. 20%\", 0.2, numch/Xp.getNumRows(), 0.05);\n+ }\n+\n+ @Test\n+ public void testSwap() {\n+ ValueType[] schema = new ValueType[] {ValueType.INT32, ValueType.INT32, ValueType.INT32};\n+ FrameBlock ori = new FrameBlock(schema);\n+\n+ Random rand = new Random();\n+\n+ for(int i = 0; i<1000; i++) {\n+ Object[] row = new Object[3];\n+ row[0] = rand.nextInt(1000);\n+ row[1] = rand.nextInt(1000);\n+ row[2] = rand.nextInt(1000);\n+\n+ ori.appendRow(row);\n+ }\n+\n+ List<Integer> numerics = new ArrayList<Integer>();\n+ List<Integer> strings = new ArrayList<Integer>();\n+ List<Integer> swappable = new ArrayList<Integer>();\n+\n+ FrameBlock changed = DataAugmentation.preprocessing(ori, numerics, strings, swappable);\n+\n+ changed = DataAugmentation.swap(changed, swappable, 0.2);\n+\n+ double numch = 0.;\n+ for(int i=0;i<changed.getNumRows();i++) {\n+ String label = (String) changed.get(i, changed.getNumColumns()-1);\n+ if(label.equals(\"swap\")) {\n+ numch++;\n+ boolean checkSwap = false;\n+ for(int c:swappable) {\n+ Integer val0 = (Integer) ori.get(i, c);\n+ Integer valch0 = (Integer) changed.get(i, c);\n+ Integer val1 = (Integer) ori.get(i, c+1);\n+ Integer valch1 = (Integer) changed.get(i, c+1);\n+ checkSwap = checkSwap || (val0.equals(valch1) && val1.equals(valch0));\n+ if(checkSwap) break;\n+ }\n+ assertTrue(\"Row \"+i+\" was marked with outliers, but it has not been changed.\",checkSwap);\n+ }\n+ }\n+ System.out.println(\"Test swap: number of changed rows: \" + numch);\n+ assertEquals(\"The number of changed rows is not approx. 20%\", 0.2, numch/changed.getNumRows(), 0.05);\n+\n+ }\n+}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-262] Data augmentation tool for data cleaning primitives
DIA project data augmentation for data cleaning (outliers, missing
values, typos, swapped columns)
Closes #101. |
49,689 | 07.02.2020 10:28:53 | -3,600 | e44e4129c61acc70be5b0c6981806316e6fccbc3 | Extended multi-level lineage-based reuse (block-level)
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -183,6 +183,7 @@ SYSTEMDS-230 Lineage Integration\n* 233 Lineage cache and reuse of function results OK\n* 234 Lineage tracing for spark instructions OK\n* 235 Lineage tracing for remote-spark parfor OK\n+ * 236 Extended multi-level lineage cache for statement blocks OK\nSYSTEMDS-240 GPU Backend Improvements\n* 241 Dense GPU cumulative aggregates\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/StatementBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/StatementBlock.java",
"diff": "@@ -46,6 +46,8 @@ public class StatementBlock extends LiveVariableAnalysis implements ParseInfo\nprotected static final Log LOG = LogFactory.getLog(StatementBlock.class.getName());\nprotected static IDSequence _seq = new IDSequence();\n+ private static IDSequence _seqSBID = new IDSequence();\n+ protected final long _ID;\nprotected DMLProgram _dmlProg;\nprotected ArrayList<Statement> _statements;\n@@ -59,6 +61,7 @@ public class StatementBlock extends LiveVariableAnalysis implements ParseInfo\nprivate boolean _splitDag = false;\npublic StatementBlock() {\n+ _ID = getNextSBID();\n_dmlProg = null;\n_statements = new ArrayList<>();\n_read = new VariableSet();\n@@ -82,10 +85,18 @@ public class StatementBlock extends LiveVariableAnalysis implements ParseInfo\n_dmlProg = dmlProg;\n}\n+ private static long getNextSBID() {\n+ return _seqSBID.getNextID();\n+ }\n+\npublic DMLProgram getDMLProg(){\nreturn _dmlProg;\n}\n+ public long getSBID() {\n+ return _ID;\n+ }\n+\npublic void addStatement(Statement s) {\n_statements.add(s);\nif (_statements.size() == 1){\n@@ -377,6 +388,28 @@ public class StatementBlock extends LiveVariableAnalysis implements ParseInfo\nreturn sb.toString();\n}\n+ public ArrayList<String> getInputstoSB() {\n+ ArrayList<String> inputs = _liveIn != null && _read != null ? new ArrayList<>() : null;\n+ if (_liveIn != null && _read != null) {\n+ for (String varName : _read.getVariables().keySet()) {\n+ if (_liveIn.containsVariable(varName))\n+ inputs.add(varName);\n+ }\n+ }\n+ return inputs;\n+ }\n+\n+ public ArrayList<String> getOutputsofSB() {\n+ ArrayList<String> outputs = _liveOut != null && _updated != null ? new ArrayList<>() : null;\n+ if (_liveOut != null && _updated != null) {\n+ for (String varName : _updated.getVariables().keySet()) {\n+ if (_liveOut.containsVariable(varName))\n+ outputs.add(varName);\n+ }\n+ }\n+ return outputs;\n+ }\n+\npublic static ArrayList<StatementBlock> mergeStatementBlocks(ArrayList<StatementBlock> sb){\nif (sb == null || sb.isEmpty())\nreturn new ArrayList<>();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/BasicProgramBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/BasicProgramBlock.java",
"diff": "@@ -24,6 +24,11 @@ import org.tugraz.sysds.hops.recompile.Recompiler;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\nimport org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.tugraz.sysds.runtime.instructions.Instruction;\n+import org.tugraz.sysds.runtime.lineage.LineageCache;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheStatistics;\n+import org.tugraz.sysds.runtime.lineage.LineageItem;\n+import org.tugraz.sysds.runtime.lineage.LineageItemUtils;\nimport org.tugraz.sysds.utils.Statistics;\npublic class BasicProgramBlock extends ProgramBlock\n@@ -97,7 +102,25 @@ public class BasicProgramBlock extends ProgramBlock\nthrow new DMLRuntimeException(\"Unable to recompile program block.\", ex);\n}\n+ //statement-block-level, lineage-based reuse\n+ LineageItem[] liInputs = null;\n+ if (_sb != null && !ReuseCacheType.isNone()) {\n+ String name = \"SB\" + _sb.getSBID();\n+ liInputs = LineageItemUtils.getLineageItemInputstoSB(_sb.getInputstoSB(), ec);\n+ if( LineageCache.reuse(_sb.getOutputsofSB(), _sb.getOutputsofSB().size(), liInputs, name, ec) ) {\n+ if( DMLScript.STATISTICS )\n+ LineageCacheStatistics.incrementSBHits();\n+ return;\n+ }\n+ }\n+\n//actual instruction execution\nexecuteInstructions(tmp, ec);\n+\n+ //statement-block-level, lineage-based caching\n+ if (_sb != null && liInputs != null) {\n+ String name = \"SB\" + _sb.getSBID();\n+ LineageCache.putValue(_sb.getOutputsofSB(), _sb.getOutputsofSB().size(), liInputs, name, ec);\n+ }\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "@@ -119,7 +119,7 @@ public class LineageCache {\nif( ReuseCacheType.isNone() )\nreturn false;\n- boolean reuse = true;\n+ boolean reuse = (numOutputs != 0);\nfor (int i=0; i<numOutputs; i++) {\nString opcode = name + String.valueOf(i+1);\nLineageItem li = new LineageItem(outputs.get(i), opcode, liInputs);\n@@ -144,7 +144,7 @@ public class LineageCache {\nec.setVariable(boundVarName, boundValue);\n// map original lineage of function return to the calling site\n- LineageItem orig = LineageCache.getNext(li);\n+ LineageItem orig = _cache.get(li)._origItem; //FIXME: synchronize\nec.getLineage().set(boundVarName, orig);\n}\nelse {\n@@ -157,17 +157,7 @@ public class LineageCache {\nreturn reuse;\n}\n- public static LineageItem getNext(LineageItem firstItem) {\n- for(Map.Entry<LineageItem, Entry> entry : _cache.entrySet()) {\n- if (!(entry.getKey().equals(firstItem)) && !entry.getValue().isNullVal() &&\n- (entry.getValue().getValue() == _cache.get(firstItem).getValue()))\n- return entry.getKey();\n- }\n- return null;\n- }\n-\n//NOTE: safe to pin the object in memory as coming from CPInstruction\n-\npublic static void put(Instruction inst, ExecutionContext ec) {\nif (inst instanceof ComputationCPInstruction && isReusable(inst, ec) ) {\nLineageItem item = ((LineageTraceable) inst).getLineageItems(ec)[0];\n@@ -195,12 +185,14 @@ public class LineageCache {\n}\n}\n- public static void putValue(LineageItem item, LineageItem probeItem, MatrixObject mo) {\n+ public static void putValue(LineageItem item, LineageItem probeItem) {\nif (ReuseCacheType.isNone())\nreturn;\nif (LineageCache.probe(probeItem)) {\nMatrixBlock value = LineageCache.get(probeItem);\n- _cache.get(item).setValue(value, 0); //TODO: compute estimate for function\n+ Entry e = _cache.get(item);\n+ e.setValue(value, 0); //TODO: compute estimate for function\n+ e._origItem = probeItem;\nsynchronized( _cache ) {\nif(!isBelowThreshold(value))\n@@ -218,22 +210,31 @@ public class LineageCache {\nif( ReuseCacheType.isNone() )\nreturn;\n+ HashMap<LineageItem, LineageItem> FuncLIMap = new HashMap<>();\n+ boolean AllOutputsCacheable = true;\nfor (int i=0; i<numOutputs; i++) {\n- if (!ReuseCacheType.isNone()) {\nString opcode = name + String.valueOf(i+1);\nLineageItem li = new LineageItem(outputs.get(i), opcode, liInputs);\nString boundVarName = outputs.get(i);\nLineageItem boundLI = ec.getLineage().get(boundVarName);\nData boundValue = ec.getVariable(boundVarName);\n- //if (LineageItemUtils.containsRandDataGen(liInputs, ec.getLineage().get(boundVarName)))\n- if (LineageItemUtils.containsRandDataGen(new HashSet<>(Arrays.asList(liInputs)), boundLI)\n- || boundValue instanceof ScalarObject) //TODO: cache scalar objects\n- LineageCache.removeEntry(li); //remove the placeholder\n- else\n- LineageCache.putValue(li, boundLI, (MatrixObject)boundValue);\n- //TODO: Unmark for caching in compiler if function contains rand()\n+ if (boundLI == null\n+ || !LineageCache.probe(li)\n+ || LineageItemUtils.containsRandDataGen(new HashSet<>(Arrays.asList(liInputs)), boundLI)\n+ || boundValue instanceof ScalarObject) { //TODO: cache scalar objects\n+ AllOutputsCacheable = false;\n}\n+ FuncLIMap.put(li, boundLI);\n}\n+\n+ //cache either all the outputs, or none.\n+ if(AllOutputsCacheable)\n+ FuncLIMap.forEach((Li, boundLI) -> LineageCache.putValue(Li, boundLI));\n+ else\n+ //remove all the placeholders\n+ FuncLIMap.forEach((Li, boundLI) -> LineageCache.removeEntry(Li));\n+\n+ return;\n}\nprivate static void putIntern(LineageItem key, MatrixBlock value, double compcost) {\n@@ -273,6 +274,8 @@ public class LineageCache {\npublic static void resetCache() {\n_cache.clear();\n_spillList.clear();\n+ _head = null;\n+ _end = null;\nif (DMLScript.STATISTICS)\n_removelist.clear();\n}\n@@ -602,11 +605,13 @@ public class LineageCache {\ndouble _compEst;\nprivate Entry _prev;\nprivate Entry _next;\n+ private LineageItem _origItem;\npublic Entry(LineageItem key, MatrixBlock value, double computecost) {\n_key = key;\n_val = value;\n_compEst = computecost;\n+ _origItem = null;\n}\npublic synchronized MatrixBlock getValue() {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCacheStatistics.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCacheStatistics.java",
"diff": "@@ -27,6 +27,7 @@ public class LineageCacheStatistics {\nprivate static final LongAdder _numHitsFS = new LongAdder();\nprivate static final LongAdder _numHitsDel = new LongAdder();\nprivate static final LongAdder _numHitsInst = new LongAdder();\n+ private static final LongAdder _numHitsSB = new LongAdder();\nprivate static final LongAdder _numHitsFunc = new LongAdder();\nprivate static final LongAdder _numWritesMem = new LongAdder();\nprivate static final LongAdder _numWritesFS = new LongAdder();\n@@ -42,6 +43,7 @@ public class LineageCacheStatistics {\n_numHitsFS.reset();\n_numHitsDel.reset();\n_numHitsInst.reset();\n+ _numHitsSB.reset();\n_numHitsFunc.reset();\n_numWritesMem.reset();\n_numWritesFS.reset();\n@@ -73,6 +75,11 @@ public class LineageCacheStatistics {\n_numHitsInst.increment();\n}\n+ public static void incrementSBHits() {\n+ // Number of times statementblock results are reused.\n+ _numHitsSB.increment();\n+ }\n+\npublic static void incrementFuncHits() {\n// Number of times function results are reused.\n_numHitsFunc.increment();\n@@ -114,7 +121,7 @@ public class LineageCacheStatistics {\n}\npublic static void incrementPRwExecTime(long delta) {\n- // Total time spent estimating computation and disk spill costs.\n+ // Total time spent executing lineage rewrites.\n_ctimeRewriteEx.add(delta);\n}\n@@ -132,6 +139,8 @@ public class LineageCacheStatistics {\nStringBuilder sb = new StringBuilder();\nsb.append(_numHitsInst.longValue());\nsb.append(\"/\");\n+ sb.append(_numHitsSB.longValue());\n+ sb.append(\"/\");\nsb.append(_numHitsFunc.longValue());\nreturn sb.toString();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"diff": "@@ -23,6 +23,7 @@ import org.apache.hadoop.fs.LocalFileSystem;\nimport org.apache.hadoop.fs.Path;\nimport org.tugraz.sysds.runtime.instructions.spark.RandSPInstruction;\nimport org.tugraz.sysds.runtime.io.IOUtilFunctions;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\nimport org.tugraz.sysds.runtime.lineage.LineageItem.LineageItemType;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.OpOpN;\n@@ -50,9 +51,11 @@ import org.tugraz.sysds.runtime.instructions.InstructionUtils;\nimport org.tugraz.sysds.runtime.instructions.cp.CPOperand;\nimport org.tugraz.sysds.runtime.instructions.cp.Data;\nimport org.tugraz.sysds.runtime.instructions.cp.DataGenCPInstruction;\n+import org.tugraz.sysds.runtime.instructions.cp.ScalarObject;\nimport org.tugraz.sysds.runtime.instructions.cp.ScalarObjectFactory;\nimport org.tugraz.sysds.runtime.instructions.cp.VariableCPInstruction;\nimport org.tugraz.sysds.runtime.instructions.spark.SPInstruction.SPType;\n+import org.tugraz.sysds.runtime.instructions.cp.CPInstruction;\nimport org.tugraz.sysds.runtime.instructions.cp.CPInstruction.CPType;\nimport org.tugraz.sysds.runtime.util.HDFSTool;\n@@ -459,12 +462,19 @@ public class LineageItemUtils {\nreturn false;\nboolean isND = false;\n- DataGenCPInstruction ins = (DataGenCPInstruction)InstructionParser.parseSingleInstruction(li.getData());\n+ CPInstruction CPins = (CPInstruction) InstructionParser.parseSingleInstruction(li.getData());\n+ if (!(CPins instanceof DataGenCPInstruction))\n+ return false;\n+\n+ DataGenCPInstruction ins = (DataGenCPInstruction)CPins;\nswitch(li.getOpcode().toUpperCase())\n{\ncase \"RAND\":\nif ((ins.getMinValue() != ins.getMaxValue()) || (ins.getSparsity() != 1))\nisND = true;\n+ //NOTE:It is hard to detect in runtime if rand was called with unspecified seed\n+ //as -1 is already replaced by computed seed. Solution is to unmark for caching in\n+ //compile time. That way we can differentiate between given and unspecified seed.\nbreak;\ncase \"SAMPLE\":\nisND = true;\n@@ -476,4 +486,20 @@ public class LineageItemUtils {\n//TODO: add 'read' in this list\nreturn isND;\n}\n+\n+ public static LineageItem[] getLineageItemInputstoSB(ArrayList<String> inputs, ExecutionContext ec) {\n+ if (ReuseCacheType.isNone())\n+ return null;\n+\n+ ArrayList<CPOperand> CPOpInputs = inputs.size() > 0 ? new ArrayList<>() : null;\n+ for (int i=0; i<inputs.size(); i++) {\n+ Data value = ec.getVariable(inputs.get(i));\n+ if (value != null) {\n+ CPOpInputs.add(new CPOperand(value instanceof ScalarObject ? value.toString() : inputs.get(i),\n+ value.getValueType(), value.getDataType()));\n+ }\n+ }\n+ return(CPOpInputs != null ? LineageItemUtils.getLineage(ec,\n+ CPOpInputs.toArray(new CPOperand[CPOpInputs.size()])) : null);\n+ }\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/utils/Statistics.java",
"new_path": "src/main/java/org/tugraz/sysds/utils/Statistics.java",
"diff": "@@ -947,7 +947,7 @@ public class Statistics\n}\nif (DMLScript.LINEAGE && !ReuseCacheType.isNone()) {\nsb.append(\"LinCache hits (Mem/FS/Del): \\t\" + LineageCacheStatistics.displayHits() + \".\\n\");\n- sb.append(\"LinCache MultiLevel (Ins/Fn): \\t\" + LineageCacheStatistics.displayMultiLvlHits() + \".\\n\");\n+ sb.append(\"LinCache MultiLevel (Ins/SB/Fn):\" + LineageCacheStatistics.displayMultiLvlHits() + \".\\n\");\nsb.append(\"LinCache writes (Mem/FS): \\t\" + LineageCacheStatistics.displayWtrites() + \".\\n\");\nsb.append(\"LinCache FStimes (Rd/Wr): \\t\" + LineageCacheStatistics.displayTime() + \" sec.\\n\");\nsb.append(\"LinCache costing time: \\t\" + LineageCacheStatistics.displayCostingTime() + \" sec.\\n\");\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/FunctionFullReuseTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/FunctionFullReuseTest.java",
"diff": "package org.tugraz.sysds.test.functions.lineage;\nimport org.junit.Test;\n+import org.tugraz.sysds.common.Types.ExecMode;\nimport org.tugraz.sysds.hops.OptimizerUtils;\nimport org.tugraz.sysds.hops.recompile.Recompiler;\n+import org.tugraz.sysds.lops.LopProperties.ExecType;\nimport org.tugraz.sysds.runtime.lineage.Lineage;\nimport org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixValue;\n@@ -70,14 +72,15 @@ public class FunctionFullReuseTest extends AutomatedTestBase {\ntestLineageTrace(TEST_NAME4);\n}\n- /*@Test\n+ @Test\npublic void testStepLM() {\ntestLineageTrace(TEST_NAME5);\n- }*/\n+ }\npublic void testLineageTrace(String testname) {\nboolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\nboolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n+ ExecMode platformOld = setExecMode(ExecType.CP);\ntry {\nSystem.out.println(\"------------ BEGIN \" + testname + \"------------\");\n@@ -92,6 +95,7 @@ public class FunctionFullReuseTest extends AutomatedTestBase {\nList<String> proArgs = new ArrayList<>();\nproArgs.add(\"-stats\");\nproArgs.add(\"-lineage\");\n+ proArgs.add(\"-explain\");\nproArgs.add(\"-args\");\nproArgs.add(output(\"X\"));\nprogramArgs = proArgs.toArray(new String[proArgs.size()]);\n@@ -104,7 +108,7 @@ public class FunctionFullReuseTest extends AutomatedTestBase {\nproArgs.clear();\nproArgs.add(\"-stats\");\nproArgs.add(\"-lineage\");\n- proArgs.add(ReuseCacheType.REUSE_HYBRID.name().toLowerCase());\n+ proArgs.add(ReuseCacheType.REUSE_FULL.name().toLowerCase());\nproArgs.add(\"-args\");\nproArgs.add(output(\"X\"));\nprogramArgs = proArgs.toArray(new String[proArgs.size()]);\n@@ -120,6 +124,7 @@ public class FunctionFullReuseTest extends AutomatedTestBase {\nfinally {\nOptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = old_simplification;\nOptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = old_sum_product;\n+ rtplatform = platformOld;\nRecompiler.reinitRecompiler();\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/SBFullReuseTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.lineage;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types.ExecMode;\n+import org.tugraz.sysds.hops.OptimizerUtils;\n+import org.tugraz.sysds.hops.recompile.Recompiler;\n+import org.tugraz.sysds.lops.LopProperties.ExecType;\n+import org.tugraz.sysds.runtime.lineage.Lineage;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+public class SBFullReuseTest extends AutomatedTestBase {\n+\n+ protected static final String TEST_DIR = \"functions/lineage/\";\n+ protected static final String TEST_NAME1 = \"SBFullReuse1\";\n+ protected static final String TEST_NAME2 = \"SBFullReuse2\";\n+ protected static final String TEST_NAME3 = \"SBFullReuse3\";\n+ protected String TEST_CLASS_DIR = TEST_DIR + SBFullReuseTest.class.getSimpleName() + \"/\";\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1));\n+ addTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2));\n+ addTestConfiguration(TEST_NAME3, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME3));\n+ }\n+\n+ @Test\n+ public void testCacheHit() {\n+ testLineageTrace(TEST_NAME1);\n+ }\n+\n+ @Test\n+ public void testCacheMiss() {\n+ testLineageTrace(TEST_NAME2);\n+ }\n+\n+ @Test\n+ public void testCacheFallThrough() {\n+ testLineageTrace(TEST_NAME3);\n+ }\n+\n+ public void testLineageTrace(String testname) {\n+ boolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ boolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n+ ExecMode platformOld = setExecMode(ExecType.CP);\n+\n+ try {\n+ System.out.println(\"------------ BEGIN \" + testname + \"------------\");\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = false;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = false;\n+\n+ getAndLoadTestConfiguration(testname);\n+ fullDMLScriptName = getScript();\n+\n+ // Without lineage-based reuse enabled\n+ List<String> proArgs = new ArrayList<>();\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(output(\"X\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ Lineage.resetInternalState();\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+ HashMap<MatrixValue.CellIndex, Double> X_orig = readDMLMatrixFromHDFS(\"X\");\n+\n+ // With lineage-based reuse enabled\n+ proArgs.clear();\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-explain\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(ReuseCacheType.REUSE_FULL.name().toLowerCase());\n+ proArgs.add(\"-args\");\n+ proArgs.add(output(\"X\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ Lineage.resetInternalState();\n+ Lineage.setLinReuseFull();\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+ HashMap<MatrixValue.CellIndex, Double> X_reused = readDMLMatrixFromHDFS(\"X\");\n+ Lineage.setLinReuseNone();\n+\n+ TestUtils.compareMatrices(X_orig, X_reused, 1e-6, \"Origin\", \"Reused\");\n+ }\n+ finally {\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = old_simplification;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = old_sum_product;\n+ rtplatform = platformOld;\n+ Recompiler.reinitRecompiler();\n+ }\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/lineage/FunctionFullReuse5.dml",
"new_path": "src/test/scripts/functions/lineage/FunctionFullReuse5.dml",
"diff": "#-------------------------------------------------------------\n# Increase rows and cols for better performance gains\n-X = rand(rows=100, cols=100, sparsity=1.0, seed=1);\n-y = X %*% rand(rows=100, cols=1, sparsity=1.0, seed=1);\n-R = matrix(0, 1, 2);\n+X = rand(rows=100, cols=10, sparsity=1.0, seed=1);\n+y = X %*% rand(rows=10, cols=1, sparsity=1.0, seed=1);\n+R = matrix(0, 101, 2);\n-[C, S] = steplm(X=X, y=y, icpt=1);\n-R[1,1] = sum(C)\n-R[1,2] = sum(S)\n+[C, S] = steplm(X=X, y=y, icpt=2);\n+S = cbind(S, matrix(1, 1, 1));\n+R[1:nrow(C) ,1] = C;\n+R[1:ncol(S) ,2] = t(S);\nwrite(R, $1, format=\"text\");\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/SBFullReuse1.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+# Increase k for better performance gains\n+\n+X = rand(rows=1024, cols=1024, seed=42);\n+R = matrix(0, 1024, 1024);\n+k = 10\n+\n+for(i in 1:k) {\n+ tmp = t(X) %*% X;\n+ tmp = tmp + 1;\n+ tmp1 = X %*% tmp;\n+}\n+\n+write(tmp1, $1, format=\"text\");\n+\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/SBFullReuse2.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+# Increase k for better performance gains\n+\n+X = rand(rows=1024, cols=1024, seed=42);\n+k = 10\n+\n+for(i in 1:k) {\n+ tmp = t(X) %*% X;\n+ tmp = tmp + i; # generate cache miss for statement block\n+ tmp1 = X %*% tmp;\n+}\n+\n+write(tmp1, $1, format=\"text\");\n+\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/SBFullReuse3.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+# Increase k for better performance gains\n+\n+X = rand(rows=1024, cols=1024, seed=42);\n+R = matrix(0, 1024, 1024);\n+k = 10\n+\n+for(i in 1:k) {\n+ tmp = t(X) %*% X;\n+ tmp = tmp + 1;\n+ tmp1 = X %*% tmp;\n+}\n+\n+if (sum(t(X) %*% X) > 1) {\n+ tmp = t(X) %*% X;\n+ tmp = tmp + 1;\n+ tmp1 = X %*% tmp;\n+}\n+\n+R = t(tmp1) %*% tmp1;\n+\n+write(R, $1, format=\"text\");\n+\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-236] Extended multi-level lineage-based reuse (block-level)
Closes #102. |
49,706 | 16.02.2020 17:24:49 | -3,600 | 8cba08d41662177defec12342244a513ffb5b733 | Improved Federated Environment Startup
Upgrade the startup of the Federated Environment
Support for Default Port
Relative and static file path URL for Federated Worker
Minor Startup cleanup in Federated Worker
No need for extra file argument to start a federated worker
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -176,6 +176,7 @@ SYSTEMDS-220 Federated Tensors and Instructions\n* 224 Federated transform functionality\n* 225 Federated elementwise operations\n* 226 Federated rbind and cbind OK\n+ * 227 Federated worker setup and infrastructure OK\nSYSTEMDS-230 Lineage Integration\n* 231 Use lineage in buffer pool\n"
},
{
"change_type": "MODIFY",
"old_path": "pom.xml",
"new_path": "pom.xml",
"diff": "</build>\n</profile>\n+ <!-- Profile to make standalone jar file for execution-->\n+ <profile>\n+ <id>standalone</id>\n+ <build>\n+ <plugins>\n+ <plugin>\n+ <artifactId>maven-assembly-plugin</artifactId>\n+ <version>3.2.0</version>\n+ <configuration>\n+ <descriptorRefs>\n+ <descriptorRef>jar-with-dependencies</descriptorRef>\n+ </descriptorRefs>\n+ <finalName>SystemDS-StandAlone</finalName>\n+ <archive>\n+ <manifest>\n+ <mainClass>org.tugraz.sysds.api.DMLScript</mainClass>\n+ </manifest>\n+ </archive>\n+ <appendAssemblyId>false</appendAssemblyId>\n+ </configuration>\n+ <executions>\n+ <execution>\n+ <id>make-assembly</id>\n+ <phase>package</phase>\n+ <goals>\n+ <goal>single</goal>\n+ </goals>\n+ </execution>\n+ </executions>\n+ </plugin>\n+ </plugins>\n+ </build>\n+ <dependencies>\n+ <dependency>\n+ <groupId>io.netty</groupId>\n+ <artifactId>netty-all</artifactId>\n+ <version>4.0.42.Final</version>\n+ </dependency>\n+ </dependencies>\n+ </profile>\n</profiles>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/api/DMLOptions.java",
"new_path": "src/main/java/org/tugraz/sysds/api/DMLOptions.java",
"diff": "@@ -47,7 +47,7 @@ import org.tugraz.sysds.utils.Explain.ExplainType;\npublic class DMLOptions {\npublic final Options options;\npublic Map<String, String> argVals = new HashMap<>(); // Arguments map containing either named arguments or arguments by position for a DML program\n- public String configFile = null; // Path to config file if default config and default config is to be overriden\n+ public String configFile = null; // Path to config file if default config and default config is to be overridden\npublic boolean clean = false; // Whether to clean up all SystemDS working directories (FS, DFS)\npublic boolean stats = false; // Whether to record and print the statistics\npublic int statsCount = 10; // Default statistics count\n@@ -271,8 +271,8 @@ public class DMLOptions {\n.create(\"help\");\nOption lineageOpt = OptionBuilder.withDescription(\"computes lineage traces\")\n.hasOptionalArgs().create(\"lineage\");\n- Option fedOpt = OptionBuilder.withDescription(\"starts a federated worker.\")\n- .hasArg().create(\"w\");\n+ Option fedOpt = OptionBuilder.withDescription(\"starts a federated worker with the given argument as the port.\")\n+ .hasOptionalArg().create(\"w\");\noptions.addOption(configOpt);\noptions.addOption(cleanOpt);\n@@ -288,7 +288,11 @@ public class DMLOptions {\n// Either a clean(-clean), a file(-f), a script(-s) or help(-help) needs to be specified\nOptionGroup fileOrScriptOpt = new OptionGroup()\n- .addOption(scriptOpt).addOption(fileOpt).addOption(cleanOpt).addOption(helpOpt);\n+ .addOption(scriptOpt)\n+ .addOption(fileOpt)\n+ .addOption(cleanOpt)\n+ .addOption(helpOpt)\n+ .addOption(fedOpt);\nfileOrScriptOpt.setRequired(true);\noptions.addOptionGroup(fileOrScriptOpt);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/api/DMLScript.java",
"new_path": "src/main/java/org/tugraz/sysds/api/DMLScript.java",
"diff": "@@ -150,21 +150,19 @@ public class DMLScript\n/**\n*\n* @param args command-line arguments\n- * @throws IOException if an IOException occurs\n+ * @throws IOException if an IOException occurs in the hadoop GenericOptionsParser\n*/\npublic static void main(String[] args)\nthrows IOException\n{\nConfiguration conf = new Configuration(ConfigurationManager.getCachedJobConf());\nString[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();\n-\ntry {\nDMLScript.executeScript(conf, otherArgs);\n- } catch (ParseException pe) {\n- System.err.println(pe.getMessage());\n- } catch (DMLScriptException e){\n+ }\n+ catch (ParseException | DMLScriptException e) {\n// In case of DMLScriptException, simply print the error message.\n- System.err.println(e.getMessage());\n+\n}\n}\n@@ -217,7 +215,7 @@ public class DMLScript\n}\nif (dmlOptions.fedWorker) {\n- startFederatedWorker(dmlOptions.fedWorkerPort);\n+ new FederatedWorker(dmlOptions.fedWorkerPort).run();\nreturn true;\n}\n@@ -540,17 +538,6 @@ public class DMLScript\n}\n}\n- private static void startFederatedWorker(int port) {\n- try {\n- new FederatedWorker(port).run();\n- } catch (ParseException e) {\n- System.err.println(\"-w flag should be followed by valid port number\");\n- }\n- catch (Exception e) {\n- System.err.println(e.getMessage());\n- }\n- }\n-\npublic static ExecMode getGlobalExecMode() {\nreturn EXEC_MODE;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/conf/DMLConfig.java",
"new_path": "src/main/java/org/tugraz/sysds/conf/DMLConfig.java",
"diff": "@@ -88,7 +88,8 @@ public class DMLConfig\npublic static final String PRINT_GPU_MEMORY_INFO = \"sysds.gpu.print.memoryInfo\";\npublic static final String EVICTION_SHADOW_BUFFERSIZE = \"sysds.gpu.eviction.shadow.bufferSize\";\n- public static final String DEFAULT_FEDERATED_PORT = \"25501\";\n+ public static final String DEFAULT_FEDERATED_PORT = \"4040\"; // borrowed default Spark Port\n+ public static final String DEFAULT_NUMBER_OF_FEDERATED_WORKER_THREADS = \"10\";\n//internal config\npublic static final String DEFAULT_SHARED_DIR_PERMISSION = \"777\"; //for local fs and DFS\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/FederatedWorker.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/FederatedWorker.java",
"diff": "package org.tugraz.sysds.runtime.controlprogram.federated;\n-\nimport io.netty.bootstrap.ServerBootstrap;\nimport io.netty.channel.ChannelFuture;\nimport io.netty.channel.ChannelInitializer;\n@@ -32,6 +31,7 @@ import io.netty.handler.codec.serialization.ObjectEncoder;\nimport org.apache.log4j.Logger;\nimport org.tugraz.sysds.runtime.controlprogram.caching.CacheableData;\nimport org.tugraz.sysds.runtime.controlprogram.parfor.util.IDSequence;\n+import org.tugraz.sysds.conf.DMLConfig;\nimport java.util.HashMap;\nimport java.util.Map;\n@@ -39,39 +39,44 @@ import java.util.Map;\npublic class FederatedWorker {\nprotected static Logger log = Logger.getLogger(FederatedWorker.class);\n- public int _port;\n+ private int _port;\n+ private int _nrThreads = Integer.parseInt(DMLConfig.DEFAULT_NUMBER_OF_FEDERATED_WORKER_THREADS);\nprivate IDSequence _seq = new IDSequence();\nprivate Map<Long, CacheableData<?>> _vars = new HashMap<>();\npublic FederatedWorker(int port) {\n- _port = port;\n+ _port = (port == -1) ?\n+ Integer.parseInt(DMLConfig.DEFAULT_FEDERATED_PORT) : port;\n}\n- public void run() throws Exception {\n- log.debug(\"[Federated Worker] Setting up...\");\n- EventLoopGroup bossGroup = new NioEventLoopGroup(10);\n- EventLoopGroup workerGroup = new NioEventLoopGroup(10);\n- try {\n+ public void run() {\n+ log.info(\"Setting up Federated Worker\");\n+ EventLoopGroup bossGroup = new NioEventLoopGroup(_nrThreads);\n+ EventLoopGroup workerGroup = new NioEventLoopGroup(_nrThreads);\nServerBootstrap b = new ServerBootstrap();\n- b.group(bossGroup, workerGroup)\n- .channel(NioServerSocketChannel.class)\n+ b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)\n.childHandler(new ChannelInitializer<SocketChannel>() {\n@Override\npublic void initChannel(SocketChannel ch) {\n- ch.pipeline().addLast(\"ObjectDecoder\",\n- new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.weakCachingResolver(ClassLoader.getSystemClassLoader())))\n+ ch.pipeline()\n+ .addLast(\"ObjectDecoder\",\n+ new ObjectDecoder(Integer.MAX_VALUE,\n+ ClassResolvers.weakCachingResolver(ClassLoader.getSystemClassLoader())))\n.addLast(\"ObjectEncoder\", new ObjectEncoder())\n.addLast(\"FederatedWorkerHandler\", new FederatedWorkerHandler(_seq, _vars));\n}\n- })\n- .option(ChannelOption.SO_BACKLOG, 128)\n- .childOption(ChannelOption.SO_KEEPALIVE, true);\n- log.debug(\"[Federated Worker] Starting server at port \" + _port);\n+ }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);\n+ try {\n+ log.info(\"Starting Federated Worker server at port: \" + _port);\nChannelFuture f = b.bind(_port).sync();\n+ log.info(\"Started Federated Worker at port: \" + _port);\nf.channel().closeFuture().sync();\n}\n+ catch (InterruptedException e) {\n+ log.error(\"Federated worker interrupted\", e);\n+ }\nfinally {\n- log.debug(\"[Federated Worker] Shutting down.\");\n+ log.info(\"Federated Worker Shutting down.\");\nworkerGroup.shutdownGracefully();\nbossGroup.shutdownGracefully();\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/FederatedWorkerHandler.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/federated/FederatedWorkerHandler.java",
"diff": "/*\n- * Copyright 2019 Graz University of Technology\n+ * Copyright 2020 Graz University of Technology\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n@@ -56,12 +56,6 @@ import java.io.InputStreamReader;\nimport java.util.Arrays;\nimport java.util.Map;\n-import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_BINARY;\n-import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_CSV;\n-import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_LIBSVM;\n-import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_MATRIXMARKET;\n-import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_TEXT;\n-\npublic class FederatedWorkerHandler extends ChannelInboundHandlerAdapter {\nprotected static Logger log = Logger.getLogger(FederatedWorkerHandler.class);\n@@ -75,74 +69,150 @@ public class FederatedWorkerHandler extends ChannelInboundHandlerAdapter {\n@Override\npublic void channelRead(ChannelHandlerContext ctx, Object msg) {\n- //TODO could we modularize this method a bit?\n- log.debug(\"[Federated Worker] Received: \" + msg.getClass().getSimpleName());\n+ log.debug(\"Received: \" + msg.getClass().getSimpleName());\nFederatedRequest request;\nif (msg instanceof FederatedRequest)\nrequest = (FederatedRequest) msg;\nelse\nthrow new DMLRuntimeException(\"FederatedWorkerHandler: Received object no instance of `FederatedRequest`.\");\n- FederatedResponse response;\nFederatedRequest.FedMethod method = request.getMethod();\n- log.debug(\"[Federated Worker] Received command: \" + method.name());\n+ log.debug(\"Received command: \" + method.name());\n+\nsynchronized (_seq) {\n+ FederatedResponse response = constructResponse(request);\n+ if (!response.isSuccessful())\n+ log.error(\"Method \" + method + \" failed: \" + response.getErrorMessage());\n+ ctx.writeAndFlush(response).addListener(new CloseListener());\n+ }\n+ }\n+\n+ private FederatedResponse constructResponse(FederatedRequest request) {\n+ FederatedRequest.FedMethod method = request.getMethod();\n+ FederatedResponse response;\n+ try {\nswitch (method) {\ncase READ:\n- try {\n- // params: filename\n+ response = readMatrix(request);\n+ break;\n+ case MATVECMULT:\n+ response = executeMatVecMult(request);\n+ break;\n+ case TRANSFER:\n+ response = getVariableData(request);\n+ break;\n+ case AGGREGATE:\n+ response = executeAggregation(request);\n+ break;\n+\n+ default:\n+ String message = String.format(\"Method %s is not supported.\", method);\n+ response = new FederatedResponse(FederatedResponse.Type.ERROR, message);\n+ }\n+ }\n+ catch (Exception exception) {\n+ response = new FederatedResponse(FederatedResponse.Type.ERROR, ExceptionUtils.getFullStackTrace(exception));\n+ }\n+ return response;\n+ }\n+\n+ private FederatedResponse readMatrix(FederatedRequest request) {\ncheckNumParams(request.getNumParams(), 1);\nString filename = (String) request.getParam(0);\n- response = readMatrix(filename);\n- }\n- catch (DMLRuntimeException exception) {\n- response = new FederatedResponse(FederatedResponse.Type.ERROR,\n- ExceptionUtils.getFullStackTrace(exception));\n+ return readMatrix(filename);\n}\n- break;\n- case MATVECMULT:\n+ private FederatedResponse readMatrix(String filename) {\n+ MatrixCharacteristics mc = new MatrixCharacteristics();\n+ mc.setBlocksize(ConfigurationManager.getBlocksize());\n+ MatrixObject mo = new MatrixObject(Types.ValueType.FP64, filename);\n+ OutputInfo oi = null;\n+ InputInfo ii = null;\n+ // read metadata\ntry {\n- // params: vector, isMatVecMult, varID\n- int numParams = request.getNumParams();\n- checkNumParams(numParams, 3);\n+ String mtdname = DataExpression.getMTDFileName(filename);\n+ Path path = new Path(mtdname);\n+ try (FileSystem fs = IOUtilFunctions.getFileSystem(mtdname)) {\n+ try (BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path)))) {\n+ JSONObject mtd = JSONHelper.parse(br);\n+ if (mtd == null)\n+ return new FederatedResponse(FederatedResponse.Type.ERROR, \"Could not parse metadata file\");\n+ mc.setRows(mtd.getLong(DataExpression.READROWPARAM));\n+ mc.setCols(mtd.getLong(DataExpression.READCOLPARAM));\n+ String format = mtd.getString(DataExpression.FORMAT_TYPE);\n+ oi = OutputInfo.stringToOutputInfo(format);\n+ ii = OutputInfo.getMatchingInputInfo(oi);\n+ }\n+ }\n+ }\n+ catch (Exception ex) {\n+ throw new DMLRuntimeException(ex);\n+ }\n+ MetaDataFormat mdf = new MetaDataFormat(mc, oi, ii);\n+ mo.setMetaData(mdf);\n+ mo.acquireRead();\n+ mo.refreshMetaData();\n+ mo.release();\n+\n+ long id = _seq.getNextID();\n+ _vars.put(id, mo);\n+ return new FederatedResponse(FederatedResponse.Type.SUCCESS, id);\n+ }\n+\n+ private FederatedResponse executeMatVecMult(FederatedRequest request) {\n+ checkNumParams(request.getNumParams(), 3);\nMatrixBlock vector = (MatrixBlock) request.getParam(0);\nboolean isMatVecMult = (Boolean) request.getParam(1);\nlong varID = (Long) request.getParam(2);\n- response = executeMatVecMult(varID, vector, isMatVecMult);\n+ return executeMatVecMult(varID, vector, isMatVecMult);\n}\n- catch (Exception exception) {\n- response = new FederatedResponse(FederatedResponse.Type.ERROR,\n- ExceptionUtils.getFullStackTrace(exception));\n+\n+ private FederatedResponse executeMatVecMult(long varID, MatrixBlock vector, boolean isMatVecMult) {\n+ MatrixObject matTo = (MatrixObject) _vars.get(varID);\n+ MatrixBlock matBlock1 = matTo.acquireReadAndRelease();\n+ // TODO other datatypes\n+ AggregateBinaryOperator ab_op = new AggregateBinaryOperator(\n+ Multiply.getMultiplyFnObject(), new AggregateOperator(0, Plus.getPlusFnObject()));\n+ MatrixBlock result = isMatVecMult ?\n+ matBlock1.aggregateBinaryOperations(matBlock1, vector, new MatrixBlock(), ab_op) :\n+ vector.aggregateBinaryOperations(vector, matBlock1, new MatrixBlock(), ab_op);\n+ return new FederatedResponse(FederatedResponse.Type.SUCCESS, result);\n}\n- break;\n- case TRANSFER:\n- // params: varID\n- int numParams = request.getNumParams();\n- checkNumParams(numParams, 1);\n+ private FederatedResponse getVariableData(FederatedRequest request) {\n+ checkNumParams(request.getNumParams(), 1);\nlong varID = (Long) request.getParam(0);\n- response = getVariableData(varID);\n- break;\n+ return getVariableData(varID);\n+ }\n- case AGGREGATE:\n- // params: operatore, varID\n- numParams = request.getNumParams();\n- checkNumParams(numParams, 2);\n- AggregateUnaryOperator operator = (AggregateUnaryOperator) request.getParam(0);\n- varID = (Long) request.getParam(1);\n- response = executeAggregation(varID, operator);\n+ private FederatedResponse getVariableData(long varID) {\n+ FederatedResponse response;\n+ Data dataObject = _vars.get(varID);\n+ switch (dataObject.getDataType()) {\n+ case TENSOR:\n+ response = new FederatedResponse(FederatedResponse.Type.SUCCESS,\n+ ((TensorObject) dataObject).acquireReadAndRelease());\nbreak;\n-\n+ case MATRIX:\n+ response = new FederatedResponse(FederatedResponse.Type.SUCCESS,\n+ ((MatrixObject) dataObject).acquireReadAndRelease());\n+ break;\n+ case LIST:\n+ response = new FederatedResponse(FederatedResponse.Type.SUCCESS, ((ListObject) dataObject).getData());\n+ break;\n+ // TODO rest of the possible datatypes\ndefault:\n- String message = String.format(\n- \"[Federated Worker] Method %s is not supported.\", request.getMethod());\n- response = new FederatedResponse(FederatedResponse.Type.ERROR, message);\n+ response = new FederatedResponse(FederatedResponse.Type.ERROR,\n+ \"FederatedWorkerHandler: Not possible to send datatype \" + dataObject.getDataType().name());\n}\n- if (!response.isSuccessful())\n- log.error(\"[Federated Worker] Method \" + request.getMethod() + \" failed: \" + response.getErrorMessage());\n- ctx.writeAndFlush(response).addListener(new CloseListener());\n+ return response;\n}\n+\n+ private FederatedResponse executeAggregation(FederatedRequest request) {\n+ checkNumParams(request.getNumParams(), 2);\n+ AggregateUnaryOperator operator = (AggregateUnaryOperator) request.getParam(0);\n+ long varID = (Long) request.getParam(1);\n+ return executeAggregation(varID, operator);\n}\nprivate FederatedResponse executeAggregation(long varID, AggregateUnaryOperator operator) {\n@@ -181,101 +251,12 @@ public class FederatedWorkerHandler extends ChannelInboundHandlerAdapter {\nreturn new FederatedResponse(FederatedResponse.Type.SUCCESS, ret);\n}\n- private FederatedResponse getVariableData(long varID) {\n- FederatedResponse response;\n- Data dataObject = _vars.get(varID);\n- switch (dataObject.getDataType()) {\n- case TENSOR:\n- response = new FederatedResponse(FederatedResponse.Type.SUCCESS,\n- ((TensorObject) dataObject).acquireReadAndRelease());\n- break;\n- case MATRIX:\n- response = new FederatedResponse(FederatedResponse.Type.SUCCESS,\n- ((MatrixObject) dataObject).acquireReadAndRelease());\n- break;\n- case LIST:\n- response = new FederatedResponse(FederatedResponse.Type.SUCCESS, ((ListObject) dataObject).getData());\n- break;\n- // TODO rest of the possible datatypes\n- default:\n- response = new FederatedResponse(FederatedResponse.Type.ERROR,\n- \"FederatedWorkerHandler: Not possible to send datatype \" + dataObject.getDataType().name());\n- }\n- return response;\n- }\n-\n- private FederatedResponse executeMatVecMult(long varID, MatrixBlock vector, boolean isMatVecMult) {\n- MatrixObject matTo = (MatrixObject) _vars.get(varID);\n- MatrixBlock matBlock1 = matTo.acquireReadAndRelease();\n- // TODO other datatypes\n- AggregateBinaryOperator ab_op = new AggregateBinaryOperator(\n- Multiply.getMultiplyFnObject(), new AggregateOperator(0, Plus.getPlusFnObject()));\n- MatrixBlock result =isMatVecMult?\n- matBlock1.aggregateBinaryOperations(matBlock1, vector, new MatrixBlock(), ab_op) :\n- vector.aggregateBinaryOperations(vector, matBlock1, new MatrixBlock(), ab_op);\n- return new FederatedResponse(FederatedResponse.Type.SUCCESS, result);\n- }\n-\n- private FederatedResponse readMatrix(String filename) {\n- MatrixCharacteristics mc = new MatrixCharacteristics();\n- mc.setBlocksize(ConfigurationManager.getBlocksize());\n- MatrixObject mo = new MatrixObject(Types.ValueType.FP64, filename);\n- OutputInfo oi = null;\n- InputInfo ii = null;\n- // read metadata\n- try {\n- String mtdname = DataExpression.getMTDFileName(filename);\n- Path path = new Path(mtdname);\n- try (FileSystem fs = IOUtilFunctions.getFileSystem(mtdname)) {\n- try (BufferedReader br = new BufferedReader(new InputStreamReader(fs.open(path)))) {\n- JSONObject mtd = JSONHelper.parse(br);\n- if (mtd == null)\n- return new FederatedResponse(FederatedResponse.Type.ERROR, \"Could not parse metadata file\");\n- mc.setRows(mtd.getLong(DataExpression.READROWPARAM));\n- mc.setCols(mtd.getLong(DataExpression.READCOLPARAM));\n- String format = mtd.getString(DataExpression.FORMAT_TYPE);\n- if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_TEXT)) {\n- oi = OutputInfo.TextCellOutputInfo;\n- }\n- else if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_BINARY)) {\n- oi = OutputInfo.BinaryBlockOutputInfo;\n- }\n- else if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_MATRIXMARKET)) {\n- oi = OutputInfo.MatrixMarketOutputInfo;\n- }\n- else if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_LIBSVM)) {\n- oi = OutputInfo.LIBSVMOutputInfo;\n- }\n- else if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_CSV)) {\n- oi = OutputInfo.CSVOutputInfo;\n- }\n- else {\n- return new FederatedResponse(FederatedResponse.Type.ERROR,\n- \"Could not figure out correct file format from metadata file\");\n- }\n- ii = OutputInfo.getMatchingInputInfo(oi);\n- }\n- }\n- }\n- catch (Exception ex) {\n- throw new DMLRuntimeException(ex);\n- }\n- MetaDataFormat mdf = new MetaDataFormat(mc, oi, ii);\n- mo.setMetaData(mdf);\n- mo.acquireRead();\n- mo.refreshMetaData();\n- mo.release();\n-\n- long id = _seq.getNextID();\n- _vars.put(id, mo);\n- return new FederatedResponse(FederatedResponse.Type.SUCCESS, id);\n- }\n-\n@SuppressWarnings(\"unused\")\nprivate FederatedResponse createMatrixObject(MatrixBlock result) {\nMatrixObject resTo = new MatrixObject(Types.ValueType.FP64, OptimizerUtils.getUniqueTempFileName());\n- MetaDataFormat metadata = new MetaDataFormat(new MatrixCharacteristics(result.getNumRows(),\n- result.getNumColumns()), OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo);\n+ MetaDataFormat metadata = new MetaDataFormat(\n+ new MatrixCharacteristics(result.getNumRows(), result.getNumColumns()),\n+ OutputInfo.BinaryBlockOutputInfo, InputInfo.BinaryBlockInputInfo);\nresTo.setMetaData(metadata);\nresTo.acquireModify(result);\nresTo.release();\n@@ -287,8 +268,8 @@ public class FederatedWorkerHandler extends ChannelInboundHandlerAdapter {\nprivate static void checkNumParams(int actual, int... expected) {\nif (Arrays.stream(expected).anyMatch(x -> x == actual))\nreturn;\n- throw new DMLRuntimeException(\"FederatedWorkerHandler: Received wrong amount of params:\"\n- + \" expected=\" + Arrays.toString(expected) +\", actual=\" + actual);\n+ throw new DMLRuntimeException(\"FederatedWorkerHandler: Received wrong amount of params:\" + \" expected=\"\n+ + Arrays.toString(expected) + \", actual=\" + actual);\n}\n@Override\n@@ -299,9 +280,9 @@ public class FederatedWorkerHandler extends ChannelInboundHandlerAdapter {\nprivate static class CloseListener implements ChannelFutureListener {\n@Override\n- public void operationComplete(ChannelFuture channelFuture) throws Exception {\n+ public void operationComplete(ChannelFuture channelFuture) throws InterruptedException, DMLRuntimeException {\nif (!channelFuture.isSuccess())\n- throw new DMLRuntimeException(\"[Federated Worker] Write failed\");\n+ throw new DMLRuntimeException(\"Federated Worker Write failed\");\nchannelFuture.channel().close().sync();\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/InitFEDInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/InitFEDInstruction.java",
"diff": "@@ -145,9 +145,14 @@ public class InitFEDInstruction extends FEDInstruction {\nif (port.equals(\"-1\"))\nport = DMLConfig.DEFAULT_FEDERATED_PORT;\nString filePath = address.getPath();\n- if (filePath.length() == 0)\n+ if (filePath.length() <= 1)\nthrow new IllegalArgumentException(\"Missing File path for federated address\");\n-\n+ // Remove the first character making the path Dynamic from the location of the worker.\n+ // This is in contrast to before where it was static paths\n+ filePath = filePath.substring(1);\n+ // To make static file paths use double \"//\" EG:\n+ // example.dom//staticFile.txt\n+ // example.dom/dynamicFile.txt\nif (address.getQuery() != null)\nthrow new IllegalArgumentException(\"Query is not supported\");\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/OutputInfo.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/OutputInfo.java",
"diff": "package org.tugraz.sysds.runtime.matrix.data;\n+import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_BINARY;\n+import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_CSV;\n+import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_LIBSVM;\n+import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_MATRIXMARKET;\n+import static org.tugraz.sysds.parser.DataExpression.FORMAT_TYPE_VALUE_TEXT;\n+\nimport java.io.Serializable;\nimport java.util.Arrays;\n@@ -141,6 +147,20 @@ public class OutputInfo implements Serializable\nreturn \"specialized\";\n}\n+ public static OutputInfo outputInfoFromStringExternal(String format) {\n+ if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_TEXT))\n+ return OutputInfo.TextCellOutputInfo;\n+ else if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_BINARY))\n+ return OutputInfo.BinaryBlockOutputInfo;\n+ else if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_MATRIXMARKET))\n+ return OutputInfo.MatrixMarketOutputInfo;\n+ else if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_LIBSVM))\n+ return OutputInfo.LIBSVMOutputInfo;\n+ else if (format.equalsIgnoreCase(FORMAT_TYPE_VALUE_CSV))\n+ return OutputInfo.CSVOutputInfo;\n+ throw new DMLRuntimeException(\"Invalid external file format: \"+format);\n+ }\n+\n@Override\npublic int hashCode() {\nreturn Arrays.hashCode(new int[] {\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-227] Improved Federated Environment Startup
- Upgrade the startup of the Federated Environment
- Support for Default Port
- Relative and static file path URL for Federated Worker
- Minor Startup cleanup in Federated Worker
- No need for extra file argument to start a federated worker
Closes #98. |
49,730 | 16.02.2020 17:32:08 | -3,600 | 2abddc1ce4ce851641f15c8d930a67338439c5a6 | Extended slice finding for classification tasks
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -152,6 +152,7 @@ SYSTEMDS-190 New Builtin Functions III\n* 195 Builtin function mice for nominal features\n* 196 Builtin function intersect (set intersection) OK\n* 197 Builtin function for functional dependency discovery OK\n+ * 198 Extended slice finding (classification) OK\nSYSTEMDS-200 Various Fixes\n* 201 Fix spark append instruction zero columns OK\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/node.py",
"new_path": "scripts/staging/slicing/base/node.py",
"diff": "#\n#-------------------------------------------------------------\n-def logic_comparator(list_a, list_b, attributes):\n- result = [int(x) == y for (x, y) in zip(list_a, list_b)]\n- counter = 0\n- for item in result:\n- if item:\n- counter = counter + 1\n- return counter == attributes\n-\n-\nclass Node:\n+ error: float\nname: \"\"\nattributes: []\nparents: []\nchildren: []\nsize: int\n- l2_error: float\n+ loss: float\nscore: float\ne_max: float\ns_upper: int\n@@ -40,48 +32,78 @@ class Node:\nc_upper: float\ne_max_upper: float\n- def __init__(self, enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test):\n+ def __init__(self, all_features, model, complete_x, loss, x_size, y_test, preds):\n+ self.error = loss,\nself.parents = []\nself.attributes = []\nself.size = 0\nself.score = 0\n- self.enc = enc\nself.model = model\nself.complete_x = complete_x\n- self.complete_y = complete_y\n- self.f_l2 = f_l2\n+ self.loss = 0\nself.x_size = x_size\n- self.x_test = x_test\n+ self.preds = preds\nself.y_test = y_test\n- self.all_features = enc.get_feature_names()\n+ self.all_features = all_features\ndef calc_c_upper(self, w):\n- upper_score = w * (self.e_upper / self.s_lower) / (self.f_l2 / self.x_size) + (1 - w) * self.s_upper\n+ upper_score = w * (self.e_upper / self.s_lower) / (float(self.error) / self.x_size) + (1 - w) * self.s_upper\nreturn float(upper_score)\n- def eval_c_upper(self, w):\n- upper_score = w * (self.e_max_upper / (self.f_l2 / self.x_size)) + (1 - w) * self.s_upper\n- return upper_score\n-\ndef make_slice_mask(self):\nmask = []\n- attributes_indexes = []\nfor feature in self.attributes:\n- attributes_indexes.append(feature[1])\n- i = 0\n- while i < len(list(self.all_features)):\n- if i in attributes_indexes:\n- mask.append(1)\n- else:\n- mask.append(-1)\n- i = i + 1\n+ mask.append(feature[1])\nreturn mask\n- def make_slice(self):\n+ def process_slice(self, loss_type):\nmask = self.make_slice_mask()\n- subset = list(filter(lambda row: logic_comparator(list(row[1]), mask, len(self.attributes)) == True,\n- self.complete_x))\n- return subset\n+ if loss_type == 0:\n+ self.calc_l2(mask)\n+ if loss_type == 1:\n+ self.calc_class(mask)\n+\n+ def calc_class(self, mask):\n+ self.e_max = 1\n+ size = 0\n+ mistakes = 0\n+ for row in self.complete_x:\n+ flag = True\n+ for attr in mask:\n+ if row[1][attr] == 0:\n+ flag = False\n+ if flag:\n+ size = size + 1\n+ if self.y_test[row[0]][1] != self.preds[row[0]][1]:\n+ mistakes = mistakes + 1\n+ self.size = size\n+ if size != 0:\n+ self.loss = mistakes / size\n+ else:\n+ self.loss = 0\n+ self.e_upper = self.loss\n+\n+ def calc_l2(self, mask):\n+ max_tuple_error = 0\n+ sum_error = 0\n+ size = 0\n+ for row in self.complete_x:\n+ flag = True\n+ for attr in mask:\n+ if row[1][attr] == 0:\n+ flag = False\n+ if flag:\n+ size = size + 1\n+ if float(self.preds[row[0]][1]) > max_tuple_error:\n+ max_tuple_error = float(self.preds[row[0]][1])\n+ sum_error = sum_error + float(self.preds[row[0]][1])\n+ self.e_max = max_tuple_error\n+ self.e_upper = max_tuple_error\n+ if size != 0:\n+ self.loss = sum_error/size\n+ else:\n+ self.loss = 0\n+ self.size = size\ndef calc_s_upper(self, cur_lvl):\ncur_min = self.parents[0].size\n@@ -119,6 +141,13 @@ class Node:\nprev_e_uppers.append(parent.e_upper)\nreturn float(min(prev_e_uppers))\n+ def calc_bounds(self, cur_lvl, w):\n+ self.s_upper = self.calc_s_upper(cur_lvl)\n+ self.s_lower = self.calc_s_lower(cur_lvl)\n+ self.e_upper = self.calc_e_upper()\n+ self.e_max_upper = self.calc_e_max_upper(cur_lvl)\n+ self.c_upper = self.calc_c_upper(w)\n+\ndef make_name(self):\nname = \"\"\nfor attribute in self.attributes:\n@@ -129,19 +158,8 @@ class Node:\ndef make_key(self, new_id):\nreturn new_id, self.name\n- def calc_l2_error(self, subset):\n- fi_l2 = 0\n- for i in range(0, len(subset)):\n- fi_l2_sample = (self.model.predict(subset[i][1].reshape(1, -1)) - self.complete_y[subset[i][0]][1]) ** 2\n- fi_l2 = fi_l2 + float(fi_l2_sample)\n- if len(subset) > 0:\n- fi_l2 = fi_l2 / len(subset)\n- else:\n- fi_l2 = 0\n- return float(fi_l2)\n-\ndef print_debug(self, topk, level):\n- print(\"new node has been added: \" + self.make_name() + \"\\n\")\n+ print(\"new node has been created: \" + self.make_name() + \"\\n\")\nif level >= 1:\nprint(\"s_upper = \" + str(self.s_upper))\nprint(\"s_lower = \" + str(self.s_lower))\n@@ -151,4 +169,6 @@ class Node:\nprint(\"score = \" + str(self.score))\nprint(\"current topk min score = \" + str(topk.min_score))\nprint(\"-------------------------------------------------------------------------------------\")\n+core))\n+ print(\"-------------------------------------------------------------------------------------\")\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/slicer.py",
"new_path": "scripts/staging/slicing/base/slicer.py",
"diff": "@@ -20,16 +20,25 @@ from slicing.node import Node\nfrom slicing.top_k import Topk\n+# optimization function calculation:\n+# fi - error of subset, si - its size\n+# f - error of complete set, x_size - its size\n+# w - \"significance\" weight of error constraint\ndef opt_fun(fi, si, f, x_size, w):\nformula = w * (fi/f) + (1 - w) * (si/x_size)\nreturn float(formula)\n+# slice_name_nonsense function defines if combination of nodes on current level is fine or impossible:\n+# there is dependency between common nodes' common attributes number and current level is such that:\n+# commons == cur_lvl - 1\n+# valid combination example: node ABC + node BCD (on 4th level) // three attributes nodes have two common attributes\n+# invalid combination example: node ABC + CDE (on 4th level) // result node - ABCDE (absurd for 4th level)\ndef slice_name_nonsense(node_i, node_j, cur_lvl):\ncommons = 0\nfor attr1 in node_i.attributes:\nfor attr2 in node_j.attributes:\n- if attr1 == attr2:\n+ if attr1[0].split(\"_\")[0] == attr2[0].split(\"_\")[0]:\ncommons = commons + 1\nreturn commons != cur_lvl - 1\n@@ -39,18 +48,17 @@ def union(lst1, lst2):\nreturn final_list\n-def check_for_slicing(node, w, topk, x_size, alpha):\n- return node.s_upper >= x_size / alpha and node.eval_c_upper(w) >= topk.min_score\n+def check_for_slicing(node, topk, x_size, alpha):\n+ return node.s_upper >= x_size / alpha and node.c_upper >= topk.min_score\n-def check_for_excluding(node, topk, x_size, alpha, w):\n- return node.s_upper >= x_size / alpha or node.eval_c_upper(w) >= topk.min_score\n-\n-\n-def process(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test, debug, alpha, k, w):\n- # forming pairs of encoded features\n- all_features = enc.get_feature_names()\n- features_indexes = []\n+# alpha is size significance coefficient (required for optimization function)\n+# verbose option is for returning debug info while creating slices and printing it (in console)\n+# k is number of top-slices we want to receive as a result (maximum output, if less all of subsets will be printed)\n+# w is a weight of error function significance (1 - w) is a size significance propagated into optimization function\n+# loss_type = 0 (in case of regression model)\n+# loss_type = 1 (in case of classification model)\n+def process(all_features, model, complete_x, loss, x_size, y_test, errors, debug, alpha, k, w, loss_type):\ncounter = 0\n# First level slices are enumerated in a \"classic way\" (getting data and not analyzing bounds\nfirst_level = []\n@@ -58,46 +66,41 @@ def process(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test, de\nall_nodes = {}\ntop_k = Topk(k)\nfor feature in all_features:\n- features_indexes.append((feature, counter))\n- new_node = Node(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test)\n+ new_node = Node(all_features, model, complete_x, loss, x_size, y_test, errors)\nnew_node.parents = [(feature, counter)]\nnew_node.attributes.append((feature, counter))\nnew_node.name = new_node.make_name()\nnew_id = len(all_nodes)\nnew_node.key = new_node.make_key(new_id)\nall_nodes[new_node.key] = new_node\n- subset = new_node.make_slice()\n- new_node.size = len(subset)\n- fi_l2 = 0\n- tuple_errors = []\n- for j in range(0, len(subset)):\n- fi_l2_sample = (model.predict(subset[j][1].reshape(1, -1)) -\n- complete_y[subset[j][0]][1]) ** 2\n- tuple_errors.append(fi_l2_sample)\n- fi_l2 = fi_l2 + fi_l2_sample\n- new_node.e_max = max(tuple_errors)\n- new_node.l2_error = fi_l2 / new_node.size\n- new_node.score = opt_fun(new_node.l2_error, new_node.size, f_l2, x_size, w)\n- new_node.e_upper = max(tuple_errors)\n+ new_node.process_slice(loss_type)\n+ new_node.score = opt_fun(new_node.loss, new_node.size, loss, x_size, w)\nnew_node.c_upper = new_node.score\nfirst_level.append(new_node)\n+ new_node.print_debug(top_k, 0)\n+ # constraints for 1st level nodes to be problematic candidates\n+ if new_node.score > 1 and new_node.size >= x_size / alpha:\n+ # this method updates top k slices if needed\n+ top_k.add_new_top_slice(new_node)\ncounter = counter + 1\nlevels.append(first_level)\n- candidates = []\n- for sliced in first_level:\n- if sliced.score > 1 and sliced.size >= x_size / alpha:\n- candidates.append(sliced)\n+\n# cur_lvl - index of current level, correlates with number of slice forming features\ncur_lvl = 1 # currently filled level after first init iteration\n- for candidate in candidates:\n- top_k.add_new_top_slice(candidate)\n- while cur_lvl < len(all_features):\n+\n+ # currently for debug\n+ print(\"Level 1 had \" + str(len(all_features)) + \" candidates\")\n+ print()\n+ print(\"Current topk are: \")\n+ top_k.print_topk()\n+ # combining each candidate of previous level with every till it becomes useless (one node can't make a pair)\n+ while len(levels[cur_lvl - 1]) > 1:\ncur_lvl_nodes = []\nfor node_i in range(len(levels[cur_lvl - 1]) - 1):\n- for node_j in range(node_i + 1, len(levels[cur_lvl - 1]) - 1):\n+ for node_j in range(node_i + 1, len(levels[cur_lvl - 1])):\nflag = slice_name_nonsense(levels[cur_lvl - 1][node_i], levels[cur_lvl - 1][node_j], cur_lvl)\nif not flag:\n- new_node = Node(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test)\n+ new_node = Node(all_features, model, complete_x, loss, x_size, y_test, errors)\nparents_set = set(new_node.parents)\nparents_set.add(levels[cur_lvl - 1][node_i])\nparents_set.add(levels[cur_lvl - 1][node_j])\n@@ -109,35 +112,33 @@ def process(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test, de\nnew_node.name = new_node.make_name()\nnew_id = len(all_nodes)\nnew_node.key = new_node.make_key(new_id)\n- if new_node.key in all_nodes:\n- existing_item = all_nodes[new_node.key]\n+ if new_node.key[1] in all_nodes:\n+ existing_item = all_nodes[new_node.key[1]]\nparents_set = set(existing_item.parents)\n- parents_set.add(node_i)\n- parents_set.add(node_j)\nexisting_item.parents = parents_set\nelse:\n- new_node.s_upper = new_node.calc_s_upper(cur_lvl)\n- new_node.s_lower = new_node.calc_s_lower(cur_lvl)\n- new_node.e_upper = new_node.calc_e_upper()\n- new_node.e_max_upper = new_node.calc_e_max_upper(cur_lvl)\n- new_node.c_upper = new_node.calc_c_upper(w)\n- all_nodes[new_node.key] = new_node\n- to_slice = check_for_slicing(new_node, w, top_k, x_size, alpha)\n- # we make data slicing basing on score upper bound\n+ new_node.calc_bounds(cur_lvl, w)\n+ all_nodes[new_node.key[1]] = new_node\n+ # check if concrete data should be extracted or not (only for those that have score upper\n+ # big enough and if size of subset is big enough\n+ to_slice = check_for_slicing(new_node, top_k, x_size, alpha)\nif to_slice:\n- subset = new_node.make_slice()\n- new_node.size = len(subset)\n- new_node.l2_error = new_node.calc_l2_error(subset)\n- new_node.score = opt_fun(new_node.l2_error, new_node.size, f_l2, x_size, w)\n+ new_node.process_slice(loss_type)\n+ new_node.score = opt_fun(new_node.loss, new_node.size, loss, x_size, w)\n# we decide to add node to current level nodes (in order to make new combinations\n- # on the next one or not basing on its score value calculated according to actual size and\n- # L2 error of a sliced subset\n+ # on the next one or not basing on its score value\nif new_node.score >= top_k.min_score:\ncur_lvl_nodes.append(new_node)\ntop_k.add_new_top_slice(new_node)\nif debug:\nnew_node.print_debug(top_k, cur_lvl)\n+ print(\"Level \" + str(cur_lvl + 1) + \" had \" + str(len(levels[cur_lvl - 1]) * (len(levels[cur_lvl - 1]) - 1)) +\n+ \" candidates but after pruning only \" + str(len(cur_lvl_nodes)) + \" go to the next level\")\ncur_lvl = cur_lvl + 1\nlevels.append(cur_lvl_nodes)\ntop_k.print_topk()\n+ print(\"Program stopped at level \" + str(cur_lvl + 1))\n+ print()\n+ print(\"Selected slices are: \")\n+ top_k.print_topk()\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/slicing/base/tests/classification/test_adult.py",
"diff": "+import pandas as pd\n+from sklearn.preprocessing import OneHotEncoder\n+\n+import slicing.slicer as slicer\n+from sklearn.ensemble import RandomForestClassifier\n+from sklearn import preprocessing\n+from sklearn.model_selection import train_test_split\n+\n+\n+dataset = pd.read_csv('adult.csv')\n+attributes_amount = len(dataset.values[0])\n+x = dataset.iloc[:, 0:attributes_amount - 1].values\n+# enc = OneHotEncoder(handle_unknown='ignore')\n+# x = enc.fit_transform(x).toarray()\n+y = dataset.iloc[:, attributes_amount - 1]\n+le = preprocessing.LabelEncoder()\n+le.fit(y)\n+y = le.transform(y)\n+complete_x = []\n+complete_y = []\n+counter = 0\n+all_indexes = []\n+not_encoded_columns = [\n+ \"Age\", \"WorkClass\", \"fnlwgt\", \"Education\", \"EducationNum\",\n+ \"MaritalStatus\", \"Occupation\", \"Relationship\", \"Race\", \"Gender\",\n+ \"CapitalGain\", \"CapitalLoss\", \"HoursPerWeek\", \"NativeCountry\", \"Income\"\n+]\n+for row in x:\n+ row[0] = int(row[0] / 10)\n+ row[2] = int(row[2]) // 100000\n+ row[4] = int(row[4] / 5)\n+ row[10] = int(row[10] / 1000)\n+ row[12] = int(row[12] / 10)\n+enc = OneHotEncoder(handle_unknown='ignore')\n+x = enc.fit_transform(x).toarray()\n+all_features = enc.get_feature_names()\n+x_size = len(complete_x)\n+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)\n+for item in x_test:\n+ complete_x.append((counter, item))\n+ complete_y.append((counter, y_test[counter]))\n+ counter = counter + 1\n+x_size = counter\n+clf = RandomForestClassifier(n_jobs=2, random_state=0)\n+clf.fit(x_train, y_train)\n+RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n+ max_depth=None, max_features='auto', max_leaf_nodes=None,\n+ min_impurity_split=1e-07, min_samples_leaf=1,\n+ min_samples_split=2, min_weight_fraction_leaf=0.0,\n+ n_estimators=10, n_jobs=2, oob_score=False, random_state=0,\n+ verbose=0, warm_start=False)\n+\n+# alpha is size significance coefficient\n+# verbose option is for returning debug info while creating slices and printing it\n+# k is number of top-slices we want\n+# w is a weight of error function significance (1 - w) is a size significance propagated into optimization function\n+# loss_type = 0 (l2 in case of regression model\n+# loss_type = 1 (cross entropy in case of classification model)\n+preds = clf.predict(x_test)\n+predictions = []\n+counter = 0\n+mistakes = 0\n+for pred in preds:\n+ predictions.append((counter, pred))\n+ if y_test[counter] != pred:\n+ mistakes = mistakes + 1\n+ counter = counter + 1\n+lossF = mistakes / counter\n+slicer.process(all_features, clf, complete_x, lossF, x_size, complete_y, predictions, debug=True, alpha=4, k=10, w=0.5,\n+ loss_type=1)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/slicing/base/tests/classification/test_iris.py",
"diff": "+import pandas as pd\n+from sklearn.preprocessing import OneHotEncoder\n+\n+import slicing.slicer as slicer\n+from sklearn.ensemble import RandomForestClassifier\n+from sklearn import preprocessing\n+from sklearn.model_selection import train_test_split\n+\n+\n+dataset = pd.read_csv('iris.csv')\n+attributes_amount = len(dataset.values[0])\n+x = dataset.iloc[:, 0:attributes_amount - 1].values\n+enc = OneHotEncoder(handle_unknown='ignore')\n+x = enc.fit_transform(x).toarray()\n+y = dataset.iloc[:, attributes_amount - 1]\n+le = preprocessing.LabelEncoder()\n+le.fit(y)\n+y = le.transform(y)\n+complete_x = []\n+complete_y = []\n+counter = 0\n+all_indexes = []\n+all_features = enc.get_feature_names()\n+x_size = len(complete_x)\n+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)\n+for item in x_test:\n+ complete_x.append((counter, item))\n+ complete_y.append((counter, y_test[counter]))\n+ counter = counter + 1\n+x_size = counter\n+clf = RandomForestClassifier(n_jobs=2, random_state=0)\n+clf.fit(x_train, y_train)\n+RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',\n+ max_depth=None, max_features='auto', max_leaf_nodes=None,\n+ min_impurity_split=1e-07, min_samples_leaf=1,\n+ min_samples_split=2, min_weight_fraction_leaf=0.0,\n+ n_estimators=10, n_jobs=2, oob_score=False, random_state=0,\n+ verbose=0, warm_start=False)\n+\n+# alpha is size significance coefficient\n+# verbose option is for returning debug info while creating slices and printing it\n+# k is number of top-slices we want\n+# w is a weight of error function significance (1 - w) is a size significance propagated into optimization function\n+# loss_type = 0 (l2 in case of regression model\n+# loss_type = 1 (cross entropy in case of classification model)\n+preds = clf.predict(x_test)\n+predictions = []\n+counter = 0\n+mistakes = 0\n+for pred in preds:\n+ predictions.append((counter, pred))\n+ if y_test[counter] != pred:\n+ mistakes = mistakes + 1\n+ counter = counter + 1\n+lossF = mistakes / counter\n+slicer.process(all_features, clf, complete_x, lossF, x_size, complete_y, predictions, debug=True, alpha=6, k=10,\n+ w=0.5, loss_type=1)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/slicing/base/tests/regression/test_insurance.py",
"diff": "+import pandas as pd\n+from sklearn.linear_model import LinearRegression\n+from sklearn.model_selection import train_test_split\n+from sklearn.preprocessing import OneHotEncoder\n+\n+import slicing.slicer as slicer\n+\n+file_name = 'insurance.csv'\n+dataset = pd.read_csv(file_name)\n+attributes_amount = len(dataset.values[0])\n+# for now working with regression datasets, assuming that target attribute is the last one\n+# currently non-categorical features are not supported and should be binned\n+y = dataset.iloc[:, attributes_amount - 1:attributes_amount].values\n+# starting with one not including id field\n+x = dataset.iloc[:, 0:attributes_amount - 1].values\n+# list of numerical columns\n+non_categorical = [1, 3]\n+for row in x:\n+ for attribute in non_categorical:\n+ # <attribute - 2> as we already excluded from x id column\n+ row[attribute - 1] = int(row[attribute - 1] / 5)\n+# hot encoding of categorical features\n+enc = OneHotEncoder(handle_unknown='ignore')\n+x = enc.fit_transform(x).toarray()\n+complete_x = []\n+complete_y = []\n+counter = 0\n+all_features = enc.get_feature_names()\n+# train model on a whole dataset\n+x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)\n+for item in x_test:\n+ complete_x.append((counter, item))\n+ complete_y.append((counter, y_test[counter]))\n+ counter = counter + 1\n+x_size = counter\n+model = LinearRegression()\n+model.fit(x_train, y_train)\n+preds = (model.predict(x_test) - y_test) ** 2\n+f_l2 = sum(preds)/x_size\n+errors = []\n+counter = 0\n+for pred in preds:\n+ errors.append((counter, pred))\n+ counter = counter + 1\n+# alpha is size significance coefficient\n+# verbose option is for returning debug info while creating slices and printing it\n+# k is number of top-slices we want\n+# w is a weight of error function significance (1 - w) is a size significance propagated into optimization function\n+slicer.process(all_features, model, complete_x, f_l2, x_size, y_test, errors, debug=True, alpha=5, k=10,\n+ w=0.5, loss_type=0)\n"
},
{
"change_type": "RENAME",
"old_path": "scripts/staging/slicing/base/tests/salary_test_ex.py",
"new_path": "scripts/staging/slicing/base/tests/regression/test_salary.py",
"diff": "@@ -43,19 +43,27 @@ x = enc.fit_transform(x).toarray()\ncomplete_x = []\ncomplete_y = []\ncounter = 0\n-for item in x:\n- complete_row = (counter, item)\n- complete_x.append(complete_row)\n- complete_y.append((counter, y[counter]))\n- counter = counter + 1\n-x_size = counter\n+all_features = enc.get_feature_names()\n# train model on a whole dataset\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=0)\n+for item in x_test:\n+ complete_x.append((counter, item))\n+ complete_y.append((counter, y_test[counter]))\n+ counter = counter + 1\n+x_size = counter\nmodel = LinearRegression()\nmodel.fit(x_train, y_train)\n-f_l2 = sum((model.predict(x_test) - y_test) ** 2)/x_size\n+preds = (model.predict(x_test) - y_test) ** 2\n+f_l2 = sum(preds)/x_size\n+errors = []\n+counter = 0\n+for pred in preds:\n+ errors.append((counter, pred))\n+ counter = counter + 1\n# alpha is size significance coefficient\n# verbose option is for returning debug info while creating slices and printing it\n# k is number of top-slices we want\n# w is a weight of error function significance (1 - w) is a size significance propagated into optimization function\n-slicer.process(enc, model, complete_x, complete_y, f_l2, x_size, x_test, y_test, debug=True, alpha=4, k=10, w=0.5)\n+slicer.process(all_features, model, complete_x, f_l2, x_size, y_test, errors, debug=True, alpha=4, k=10, w=0.5,\n+ loss_type=0)\n+\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-198] Extended slice finding for classification tasks
Closes #103. |
49,738 | 16.02.2020 19:35:13 | -3,600 | b5aa876e0b74e75fb6c36ea771c424f7068d6592 | Fix parfor ID handling (hidden statement block ID) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/ParForStatementBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/ParForStatementBlock.java",
"diff": "@@ -96,7 +96,7 @@ public class ParForStatementBlock extends ForStatementBlock\nprivate static HashMap<String, LinearFunction> _fncache; //slower for most (small cases) cases\n//instance members\n- private final long _ID;\n+ private final long _PID;\nprivate VariableSet _vsParent = null;\nprivate ArrayList<ResultVar> _resultVars = null;\nprivate Bounds _bounds = null;\n@@ -153,14 +153,14 @@ public class ParForStatementBlock extends ForStatementBlock\n}\npublic ParForStatementBlock() {\n- _ID = _idSeq.getNextID();\n+ _PID = _idSeq.getNextID();\n_resultVars = new ArrayList<>();\n- LOG.trace(\"PARFOR(\"+_ID+\"): ParForStatementBlock instance created\");\n+ LOG.trace(\"PARFOR(\"+_PID+\"): ParForStatementBlock instance created\");\n}\npublic long getID() {\n- return _ID;\n+ return _PID;\n}\npublic ArrayList<ResultVar> getResultVariables() {\n@@ -179,7 +179,7 @@ public class ParForStatementBlock extends ForStatementBlock\n@Override\npublic VariableSet validate(DMLProgram dmlProg, VariableSet ids, HashMap<String,ConstIdentifier> constVars, boolean conditional)\n{\n- LOG.trace(\"PARFOR(\"+_ID+\"): validating ParForStatementBlock.\");\n+ LOG.trace(\"PARFOR(\"+_PID+\"): validating ParForStatementBlock.\");\n//create parent variable set via cloning\n_vsParent = new VariableSet( ids );\n@@ -326,7 +326,7 @@ public class ParForStatementBlock extends ForStatementBlock\n}\n}\nelse {\n- LOG.debug(\"INFO: PARFOR(\"+_ID+\"): loop dependency analysis skipped.\");\n+ LOG.debug(\"INFO: PARFOR(\"+_PID+\"): loop dependency analysis skipped.\");\n}\n//if successful, prepare result variables (all distinct vars in all candidates)\n@@ -348,7 +348,7 @@ public class ParForStatementBlock extends ForStatementBlock\nif( USE_FN_CACHE )\n_fncache.clear();\n- LOG.debug(\"INFO: PARFOR(\"+_ID+\"): validate successful (no dependencies) in \"+time.stop()+\"ms.\");\n+ LOG.debug(\"INFO: PARFOR(\"+_PID+\"): validate successful (no dependencies) in \"+time.stop()+\"ms.\");\nreturn vs;\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-236] Fix parfor ID handling (hidden statement block ID) |
49,738 | 16.02.2020 20:51:10 | -3,600 | c8c3d4181be0a91d6800b0862a85e3ca37f5d285 | [MINOR] Various fixes and cleanups of recent changes, part 2
1) Fixed corrupted print of stop/parse issues to stderr
2) Fixed missing handling of tensors in federated instruction wrapping | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/api/DMLScript.java",
"new_path": "src/main/java/org/tugraz/sysds/api/DMLScript.java",
"diff": "@@ -162,7 +162,7 @@ public class DMLScript\n}\ncatch (ParseException | DMLScriptException e) {\n// In case of DMLScriptException, simply print the error message.\n-\n+ System.err.println(e.getMessage());\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstructionUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/FEDInstructionUtils.java",
"diff": "@@ -65,8 +65,8 @@ public class FEDInstructionUtils {\n}\nelse if (inst instanceof AggregateUnarySPInstruction) {\nAggregateUnarySPInstruction instruction = (AggregateUnarySPInstruction) inst;\n- MatrixObject mo1 = ec.getMatrixObject(instruction.input1);\n- if (mo1.isFederated())\n+ Data data = ec.getVariable(instruction.input1);\n+ if (data instanceof MatrixObject && ((MatrixObject) data).isFederated())\nreturn AggregateUnaryFEDInstruction.parseInstruction(inst.getInstructionString());\n}\nelse if (inst instanceof WriteSPInstruction) {\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Various fixes and cleanups of recent changes, part 2
1) Fixed corrupted print of stop/parse issues to stderr
2) Fixed missing handling of tensors in federated instruction wrapping |
49,720 | 24.02.2020 16:33:45 | -3,600 | db2dbeb8339a7fb2f6771cda00671b1e062382a6 | Predict builtin for Multinomial Logistic Regression
Builtin function for Multinominal Logistic Regression
Function test verifying integration
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -153,6 +153,7 @@ SYSTEMDS-190 New Builtin Functions III\n* 196 Builtin function intersect (set intersection) OK\n* 197 Builtin function for functional dependency discovery OK\n* 198 Extended slice finding (classification) OK\n+ * 199 Builtin function Multinominal Logistic Regression Predict OK\nSYSTEMDS-200 Various Fixes\n* 201 Fix spark append instruction zero columns OK\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/builtin/multiLogRegPredict.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+\n+#THIS SCRIPT APPLIES THE ESTIMATED PARAMETERS OF MULTINOMIAL LOGISTIC REGRESSION TO A NEW (TEST) DATASET\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Double --- Data Matrix X\n+# B Double --- Regression parameters betas\n+# Y Double --- Response vector Y\n+# ---------------------------------------------------------------------------------------------\n+# OUTPUT: Matrix M of predicted means/probabilities, some statistics in CSV format (see below)\n+# OUTPUT:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# M Double --- Matrix M of predicted means/probabilities\n+# predicted_Y Double --- Predicted response vector\n+# accuracy Double --- scalar value of accuracy\n+# ---------------------------------------------------------------------------------------------\n+\n+\n+m_multiLogRegPredict = function(Matrix[Double] X, Matrix[Double] B, Matrix[Double] Y, Boolean verbose = FALSE)\n+return(Matrix[Double] M, Matrix[Double] predicted_Y, Double accuracy)\n+{\n+ if(min(Y) <= 0)\n+ stop(\"class labels should be greater than zero\")\n+\n+ num_records = nrow (X);\n+ num_features = ncol (X);\n+ beta = B [1 : ncol (X), ];\n+ intercept = B [nrow(B), ];\n+\n+ if (nrow (B) == ncol (X))\n+ intercept = 0.0 * intercept;\n+ else\n+ num_features = num_features + 1;\n+\n+ ones_rec = matrix (1, rows = num_records, cols = 1);\n+ linear_terms = X %*% beta + ones_rec %*% intercept;\n+\n+ M = probabilities(linear_terms); # compute the probablitites on unknown data\n+ predicted_Y = rowIndexMax(M); # extract the class labels\n+\n+ if(nrow(Y) != 0)\n+ accuracy = sum((predicted_Y - Y) == 0) / num_records * 100;\n+\n+ if(verbose)\n+ {\n+ acc_str = \"Accuracy (%): \" + accuracy\n+ print(acc_str)\n+ }\n+}\n+\n+probabilities = function (Matrix[double] linear_terms)\n+ return (Matrix[double] means) {\n+ # PROBABLITIES FOR MULTINOMIAL LOGIT DISTRIBUTION\n+ num_points = nrow (linear_terms);\n+ elt = exp (linear_terms);\n+ ones_pts = matrix (1, rows = num_points, cols = 1);\n+ elt = cbind (elt, ones_pts);\n+ ones_ctg = matrix (1, rows = ncol (elt), cols = 1);\n+ means = elt / (rowSums (elt) %*% t(ones_ctg));\n+}\n+\n+\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"new_path": "src/main/java/org/tugraz/sysds/common/Builtins.java",
"diff": "@@ -119,6 +119,7 @@ public enum Builtins {\nMOMENT(\"moment\", \"centralMoment\", false),\nMSVM(\"msvm\", true),\nMULTILOGREG(\"multiLogReg\", true),\n+ MULTILOGREGPREDICT(\"multiLogRegPredict\", true),\nNCOL(\"ncol\", false),\nNORMALIZE(\"normalize\", true),\nNROW(\"nrow\", false),\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinMultiLogRegPredictTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.builtin;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.common.Types;\n+import org.tugraz.sysds.lops.LopProperties;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+import java.util.HashMap;\n+\n+public class BuiltinMultiLogRegPredictTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"multiLogRegPredict\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinMultiLogRegPredictTest.class.getSimpleName() + \"/\";\n+\n+ private final static double eps = 2;\n+ private final static int rows = 1000;\n+ private final static int cols = 150;\n+ private final static double spSparse = 0.3;\n+ private final static double spDense = 0.7;\n+\n+ @Override\n+ public void setUp() {\n+ addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{\"B\"}));\n+ }\n+\n+ @Test\n+ public void testLmPredictMatrixDenseCP() {\n+ runPredictionTest(false, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testLmPredictMatrixSparseCP() {\n+ runPredictionTest(true, LopProperties.ExecType.CP);\n+ }\n+\n+\n+ private void runPredictionTest(boolean sparse, LopProperties.ExecType instType)\n+ {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+\n+ try\n+ {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ double sparsity = sparse ? spSparse : spDense;\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+\n+\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{\"-explain\", \"-args\", input(\"A\"), input(\"B\"), input(\"C\"), input(\"D\"), output(\"O\") };\n+ fullRScriptName = HOME + TEST_NAME + \".R\";\n+ rCmd = \"Rscript\" + \" \" + fullRScriptName + \" \" + inputDir() + \" \" + expectedDir();\n+\n+\n+ //generate actual dataset\n+ double[][] A = getRandomMatrix(rows, cols, 1, 100, sparsity, 7);\n+ A = TestUtils.round(A);\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+\n+ double[][] B = getRandomMatrix(rows, 1, 1, 5, 1.0, 3);\n+ B = TestUtils.round(B);\n+ writeInputMatrixWithMTD(\"B\", B, true);\n+\n+ double[][] C = getRandomMatrix(rows, cols, 1, 100, sparsity, 7);\n+ C = TestUtils.round(C);\n+ writeInputMatrixWithMTD(\"C\", C, true);\n+\n+ double[][] D = getRandomMatrix(rows, 1, 1, 5, 1.0, 3);\n+ D = TestUtils.round(D);\n+ writeInputMatrixWithMTD(\"D\", D, true);\n+\n+\n+ runTest(true, false, null, -1);\n+ runRScript(true);\n+\n+ //compare matrices\n+ HashMap<MatrixValue.CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"O\");\n+ HashMap<MatrixValue.CellIndex, Double> rfile = readRMatrixFromFS(\"O\");\n+ TestUtils.compareMatrices(dmlfile, rfile, eps, \"Stat-DML\", \"Stat-R\");\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/builtin/multiLogRegPredict.R",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+\n+args<-commandArgs(TRUE)\n+options(digits=22)\n+library(\"Matrix\")\n+library(\"nnet\")\n+\n+X = as.matrix(readMM(paste(args[1], \"A.mtx\", sep=\"\")))\n+Y = as.matrix(readMM(paste(args[1], \"B.mtx\", sep=\"\")))\n+X_test = as.matrix(readMM(paste(args[1], \"C.mtx\", sep=\"\")))\n+Y_test = as.matrix(readMM(paste(args[1], \"D.mtx\", sep=\"\")))\n+\n+X = cbind(Y, X)\n+X_test = cbind(Y_test, X_test)\n+X = as.data.frame(X)\n+# set a baseline variable\n+X$V1 <- relevel(as.factor(X$V1), ref = \"3\")\n+X_test = as.data.frame(X_test)\n+model = multinom(V1~., data = X) # train model\n+pred <- predict(model, newdata = X_test, \"class\") # predict unknown data\n+acc = (sum(pred == Y_test)/nrow(Y_test))*100\n+\n+writeMM(as(as.matrix(acc), \"CsparseMatrix\"), paste(args[2], \"O\", sep=\"\"))\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/builtin/multiLogRegPredict.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+\n+X = read($1) # Training data\n+Y = read($2) # response values\n+X_test = read($3) # random data to predict\n+Y_test = read($4) # random data labels\n+\n+w = multiLogReg(X=X, Y=Y, icpt=2, tol=0.00000001, reg=1.0, maxi=100, maxii=0, verbose=FALSE)\n+[prob, y, accuracy] = multiLogRegPredict(X=X_test, B=w, Y=Y_test, verbose=TRUE)\n+acc = matrix(accuracy, 1, 1)\n+write(acc, $5)\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-199] Predict builtin for Multinomial Logistic Regression
- Builtin function for Multinominal Logistic Regression
- Function test verifying integration
Closes #107 |
49,690 | 21.02.2020 21:58:44 | -3,600 | 6c6506be8ce92a6646be73f6ce0319f00989e2e4 | AWS deploy script
Added scripts for deployment of SystemDS on the Amazon EMR
Located in /scripts/aws/*
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -32,6 +32,7 @@ SYSTEMDS-30 Builtin and Packaging\n* 33 Cleanup hadoop dependency for local runs\n* 34 Wrapper blocks for sequence files\n* 35 Replace unnecessary dependencies w/ custom\n+ * 36 Shell script for AWS execution OK\nSYSTEMDS-40 Preprocessing builtins\n* 41 Add new winsorize builtin function OK\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/aws/README.md",
"diff": "+<!--\n+{% comment %}\n+Copyright 2018 Graz University of Technology\n+\n+Licensed to the Apache Software Foundation (ASF) under one or more\n+contributor license agreements. See the NOTICE file distributed with\n+this work for additional information regarding copyright ownership.\n+The ASF licenses this file to you under the Apache License, Version 2.0\n+(the \"License\"); you may not use this file except in compliance with\n+the License. You may obtain a copy of the License at\n+\n+http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+{% endcomment %}\n+-->\n+\n+Instructions:\n+\n+1. Create aws account / use your existing aws account\n+\n+2. Install aws-cli on your system\n+\n+(https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html)\n+\n+3. Create a user\n+\n+ * Create a new user (https://console.aws.amazon.com/iam/home?#/users)\n+\n+ * Create new group and add the following policies to it:\n+\n+ - AmazonElasticMapReduceRole\n+\n+ - AmazonElasticMapReduceforEC2Role\n+\n+ - AdministratorAccess\n+\n+ - AmazonElasticMapReduceFullAccess\n+\n+ - AWSKeyManagementServicePowerUser\n+\n+ - IAMUserSSHKeys\n+\n+4. Configure your aws-cli (https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html#cli-quick-configuration)\n+\n+5. Spin up an EMR cluster with SystemDS\n+\n+ * Put your SystemDS artifacts (dml-scripts, jars, config-file) in the directory systemds\n+\n+ * Edit configuration in: systemds_cluster.config\n+\n+ * Run: ./spinup_systemds_cluster.sh\n+\n+6. Run a SystemDS script\n+\n+ * Run: ./run_systemds_script.sh path/to/script.dml\n+ With args: ./run_systemds_script.sh path/to/script.dml \"1.0, 2.6\"\n+\n+7. Terminate the EMR cluster: ./terminate_systemds_cluster.sh\n+\n+#### Further work\n+\n+* Finetune the memory\n+\n+ https://aws.amazon.com/blogs/big-data/best-practices-for-successfully-managing-memory-for-apache-spark-applications-on-amazon-emr/\n+ https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-configure.html#spark-defaults\n+* Test if Scale to 100 nodes\n+\n+* Make the cluster WebUIs (Ganglia, SparkUI,..) accessible from outside\n+\n+* Integrate spot up instances\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/aws/run_systemds_script.sh",
"diff": "+#!/bin/bash\n+#-------------------------------------------------------------\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#-------------------------------------------------------------\n+\n+# $1 Dml script name.\n+# $2 Args\n+\n+# If number of arguments are not equal to 1.\n+if [[ ($# -ne 2 && $# -ne 1) ]] ; then\n+ echo \"Usage: \"$0\" <DML script path> (<Arguments>)\"\n+ exit 2\n+fi\n+\n+\n+source systemds_cluster.config\n+\n+aws s3 cp $1 s3://system-ds-bucket/ --exclude \"*\" --include \"*.dml\"\n+\n+if [ ! -z \"$2\" ]\n+then\n+ args=\"-args,${2}\"\n+fi\n+\n+dml_filename=$(basename $1)\n+\n+STEP_INFO=$(aws emr add-steps --cluster-id $CLUSTER_ID --steps \"Type=Spark,\n+ Name='SystemDS Spark Program',\n+ ActionOnFailure=CONTINUE,\n+ Args=[\n+ --deploy-mode,$SPARK_DEPLOY_MODE,\n+ --master,yarn,\n+ --driver-memory,$SPARK_DRIVER_MEMORY,\n+ --num-executors,$SPARK_NUM_EXECUTORS,\n+ --conf,spark.driver.maxResultSize=0,\n+ $SYSTEMDS_JAR_PATH, -f, s3://system-ds-bucket/$dml_filename, -exec, $SYSTEMDS_EXEC_MODE,$args,-stats, -explain]\")\n+\n+STEP_ID=$(echo $STEP_INFO | jq .StepIds | tr -d '\"' | tr -d ']' | tr -d '[' | tr -d '[:space:]' )\n+echo \"Waiting for the step to finish\"\n+aws emr wait step-complete --cluster-id $CLUSTER_ID --step-id $STEP_ID\n+\n+aws emr ssh --cluster-id $CLUSTER_ID --key-pair-file ${KEYPAIR_NAME}.pem --command \"cat /mnt/var/log/hadoop/steps/$STEP_ID/stderr\"\n+aws emr ssh --cluster-id $CLUSTER_ID --key-pair-file ${KEYPAIR_NAME}.pem --command \"cat /mnt/var/log/hadoop/steps/$STEP_ID/stdout\"\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/aws/spinup_systemds_cluster.sh",
"diff": "+#!/bin/bash\n+#-------------------------------------------------------------\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#-------------------------------------------------------------\n+\n+source systemds_cluster.config\n+\n+# $1 is the instance type\n+get_memory_and_cores () {\n+ while IFS=\",\" read -r field1 name memory vCPUs field5 field6\n+ do\n+ if [ \"$1\" = \"$name\" ]; then\n+ SPARK_EXECUTOR_MEMORY=$( bc <<< $memory*0.60*1000) #60% of the total memory (beacause of yarn.scheduler.maximum-allocation-mb)\n+ SPARK_EXECUTOR_CORES=$vCPUs\n+ fi\n+ done < aws_ec2_table.csv\n+\n+}\n+# $1 key, $2 value\n+function set_config(){\n+ sed -i \"\" \"s/\\($1 *= *\\).*/\\1$2/\" systemds_cluster.config\n+}\n+\n+get_memory_and_cores $INSTANCES_TYPE\n+SPARK_EXECUTOR_MEMORY=\"${SPARK_EXECUTOR_MEMORY}MB\"\n+set_config \"SPARK_NUM_EXECUTORS\" $CORE_INSTANCES_COUNT\n+set_config \"SPARK_EXECUTOR_CORES\" $SPARK_EXECUTOR_CORES\n+set_config \"SPARK_EXECUTOR_MEMORY\" $SPARK_EXECUTOR_MEMORY\n+set_config \"SPARK_DRIVER_MEMORY\" \"1G\"\n+\n+#Create systemDS bucket\n+aws s3api create-bucket --bucket system-ds-bucket --region $REGION &> /dev/null\n+aws s3api create-bucket --bucket system-ds-logs-bucket --region $REGION &> /dev/null\n+\n+# Upload Jar and scripts to s3\n+aws s3 sync $SYSTEMDS_TARGET_DIRECTORY s3://system-ds-bucket/ --exclude \"*\" --include \"*.dml\" --include \"*config.xml\" --include \"*DS.jar*\"\n+\n+# Create keypair\n+if [ ! -f ${KEYPAIR_NAME}.pem ]; then\n+ aws ec2 create-key-pair --key-name $KEYPAIR_NAME --query \"KeyMaterial\" --output text > \"$KEYPAIR_NAME.pem\"\n+ chmod 700 \"${KEYPAIR_NAME}.pem\"\n+ echo \"${KEYPAIR_NAME}.pem private key created!\"\n+fi\n+\n+#Create the cluster\n+CLUSTER_INFO=$(aws emr create-cluster \\\n+ --applications Name=Ganglia Name=Spark \\\n+ --ec2-attributes '{\"KeyName\":\"'${KEYPAIR_NAME}'\",\n+ \"InstanceProfile\":\"EMR_EC2_DefaultRole\"}'\\\n+ --service-role EMR_DefaultRole \\\n+ --enable-debugging \\\n+ --release-label $EMR_VERSION \\\n+ --log-uri \"s3n://system-ds-logs/\" \\\n+ --name \"SystemDS cluster\" \\\n+ --instance-groups '[{\"InstanceCount\":'${MASTER_INSTANCES_COUNT}',\n+ \"InstanceGroupType\":\"MASTER\",\n+ \"InstanceType\":\"'${INSTANCES_TYPE}'\",\n+ \"Name\":\"Master Instance Group\"},\n+ {\"InstanceCount\":'${CORE_INSTANCES_COUNT}',\n+ \"InstanceGroupType\":\"CORE\",\n+ \"InstanceType\":\"'${INSTANCES_TYPE}'\",\n+ \"Name\":\"Core Instance Group\"}]'\\\n+ --configurations '[{\"Classification\":\"spark\",\"Properties\":{\"maximizeResourceAllocation\": \"true\"}}]'\\\n+ --scale-down-behavior TERMINATE_AT_TASK_COMPLETION \\\n+ --region $REGION)\n+\n+CLUSTER_ID=$(echo $CLUSTER_INFO | jq .ClusterId | tr -d '\"')\n+echo \"Cluster successfully initialized. Save your ClusterID: \"${CLUSTER_ID}\n+set_config \"CLUSTER_ID\" $CLUSTER_ID\n+\n+ip_address=$(curl ipecho.net/plain ; echo)\n+\n+#Add your ip to the security group\n+aws ec2 create-security-group --group-name ElasticMapReduce-master --description \"info\" &> /dev/null\n+aws ec2 authorize-security-group-ingress \\\n+ --group-name ElasticMapReduce-master \\\n+ --protocol tcp \\\n+ --port 22 \\\n+ --cidr \"${ip_address}\"/24 &> /dev/null\n+\n+# Wait for cluster to start\n+echo \"Waiting for cluster running state\"\n+aws emr wait cluster-running --cluster-id $CLUSTER_ID\n+\n+echo \"Cluster info:\"\n+export CLUSTER_URL=$(aws emr describe-cluster --cluster-id $CLUSTER_ID | jq .Cluster.MasterPublicDnsName | tr -d '\"')\n+\n+aws emr ssh --cluster-id $CLUSTER_ID --key-pair-file ${KEYPAIR_NAME}.pem --command 'aws s3 cp s3://system-ds-bucket/target . --recursive --exclude \"*\" --include \"*DS.jar*\"'\n+\n+echo \"Spinup finished.\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/aws/systemds_cluster.config",
"diff": "+# Configuration\n+\n+KEYPAIR_NAME=\"SystemDSkeynamex\"\n+REGION=\"us-east-1\"\n+EMR_VERSION=\"emr-5.28.0\"\n+\n+INSTANCES_TYPE=\"m5.xlarge\"\n+MASTER_INSTANCES_COUNT=1\n+CORE_INSTANCES_COUNT=5\n+SPARK_DEPLOY_MODE=\"client\"\n+\n+# SystemDS specific\n+SYSTEMDS_TARGET_DIRECTORY=\"systemds/\"\n+SYSTEMDS_EXEC_MODE=\"spark\"\n+SYSTEMDS_ARGS=\"\"\n+\n+\n+# Readonly #\n+CLUSTER_ID=j-cluster_id\n+SPARK_NUM_EXECUTORS=4\n+SPARK_EXECUTOR_CORES=2\n+SPARK_EXECUTOR_MEMORY=4800.00MB\n+SPARK_DRIVER_MEMORY=1G\n+SYSTEMDS_JAR_PATH=\"/home/hadoop/SystemDS.jar\"\n+# End - Readonly #\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/aws/terminate_systemds_cluster.sh",
"diff": "+#!/bin/bash\n+#-------------------------------------------------------------\n+# Copyright 2019 Graz University of Technology\n+#\n+# Licensed to the Apache Software Foundation (ASF) under one\n+# or more contributor license agreements. See the NOTICE file\n+# distributed with this work for additional information\n+# regarding copyright ownership. The ASF licenses this file\n+# to you under the Apache License, Version 2.0 (the\n+# \"License\"); you may not use this file except in compliance\n+# with the License. You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing,\n+# software distributed under the License is distributed on an\n+# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+# KIND, either express or implied. See the License for the\n+# specific language governing permissions and limitations\n+# under the License.\n+#-------------------------------------------------------------\n+\n+source systemds_cluster.config\n+\n+aws emr terminate-clusters --cluster-ids $CLUSTER_ID\n+\n+# Wait for cluster to start\n+echo \"Waiting for cluster terminated state\"\n+aws emr wait cluster-terminated --cluster-id $CLUSTER_ID\n+\n+echo \"Cluster: ${CLUSTER_ID} terminated.\"\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-36] AWS deploy script
- Added scripts for deployment of SystemDS on the Amazon EMR
- Located in /scripts/aws/*
Closes #112 |
49,706 | 01.03.2020 15:55:24 | -3,600 | 857e45c61e965ac6e59b1e256174d62a216110c0 | [MINOR] Contributing file
Added a Contributing file specifying the basic guidelines for contribution to SystemDS
Added CodeStyle
Added licenses
Closes | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "CONTRIBUTING.md",
"diff": "+<!--\n+{% comment %}\n+Copyright 2020 Graz University of Technology\n+\n+Licensed to the Apache Software Foundation (ASF) under one or more\n+contributor license agreements. See the NOTICE file distributed with\n+this work for additional information regarding copyright ownership.\n+The ASF licenses this file to you under the Apache License, Version 2.0\n+(the \"License\"); you may not use this file except in compliance with\n+the License. You may obtain a copy of the License at\n+\n+http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+{% end comment %}\n+-->\n+\n+# Contributing to SystemDS\n+\n+Thanks for taking the time to contribute to SystemDS!\n+\n+The following are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.\n+\n+___\n+\n+## Code Style\n+\n+Before contributing a pull request, we highly suggest applying a code formatter to the written code.\n+\n+We have provided at profile for java located in [Codestyle File ./docs/CodeStyle.eclipse.xml](./docs/CodeStyle_eclipse.xml). This can be loaded in most editors e.g.:\n+\n+- [Eclipse](https://stackoverflow.com/questions/10432538/eclipse-import-conf-xml-files#10433986)\n+- [IntelliJ](https://imagej.net/Eclipse_code_style_profiles_and_IntelliJ)\n+- [Visual Studio Code](https://stackoverflow.com/questions/46030629/need-to-import-eclipse-java-formatter-profile-in-visual-studio-code)\n+\n+## License\n+\n+Each file in the project has a header license, when adding files remember to add an appropriate comment for that filetype containing the license. One Example is this file: [RAW Link](https://raw.githubusercontent.com/tugraz-isds/systemds/master/CONTRIBUTING.md).\n+\n+The specific type of commenting `\\** *\\` or `# ...` varies depending on filetype, but the content is the same except for year and \"Modifications\".\n+A rule of thumb is that the License should be updated if more than 5 lines of code changed in the file. The following it the two types of license headers:\n+\n+License header for new Files:\n+\n+```code\n+Copyright 2020 Graz University of Technology\n+\n+Licensed to the Apache Software Foundation (ASF) under one or more\n+contributor license agreements. See the NOTICE file distributed with\n+this work for additional information regarding copyright ownership.\n+The ASF licenses this file to you under the Apache License, Version 2.0\n+(the \"License\"); you may not use this file except in compliance with\n+the License. You may obtain a copy of the License at\n+\n+http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+```\n+\n+License for modified files:\n+\n+```code\n+Modifications Copyright 2020 Graz University of Technology\n+\n+Licensed to the Apache Software Foundation (ASF) under one or more\n+contributor license agreements. See the NOTICE file distributed with\n+this work for additional information regarding copyright ownership.\n+The ASF licenses this file to you under the Apache License, Version 2.0\n+(the \"License\"); you may not use this file except in compliance with\n+the License. You may obtain a copy of the License at\n+\n+http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+```\n+\n+___\n+\n+Thanks again for taking your time to help improve SystemDS! :+1:\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Contributing file
Added a Contributing file specifying the basic guidelines for contribution to SystemDS
- Added CodeStyle
- Added licenses
Closes #113 |
49,689 | 01.03.2020 20:18:19 | -3,600 | f373cdf13545bcdeb90809f38d3da47743dd42fa | Lineage support for codegen (fused operators)
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -184,7 +184,7 @@ SYSTEMDS-220 Federated Tensors and Instructions\nSYSTEMDS-230 Lineage Integration\n* 231 Use lineage in buffer pool\n- * 232 Lineage of code generated operators\n+ * 232 Lineage of code generated operators OK\n* 233 Lineage cache and reuse of function results OK\n* 234 Lineage tracing for spark instructions OK\n* 235 Lineage tracing for remote-spark parfor OK\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/Hop.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/Hop.java",
"diff": "@@ -1068,7 +1068,7 @@ public abstract class Hop implements ParseInfo\nHopsData2Lops.put(DataOpTypes.TRANSIENTREAD, org.tugraz.sysds.lops.Data.OperationTypes.READ);\n}\n- protected static final HashMap<Hop.OpOp2, Binary.OperationTypes> HopsOpOp2LopsB;\n+ public static final HashMap<Hop.OpOp2, Binary.OperationTypes> HopsOpOp2LopsB;\nstatic {\nHopsOpOp2LopsB = new HashMap<>();\nHopsOpOp2LopsB.put(OpOp2.PLUS, Binary.OperationTypes.ADD);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/codegen/SpoofCompiler.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/codegen/SpoofCompiler.java",
"diff": "@@ -97,6 +97,7 @@ import org.tugraz.sysds.runtime.controlprogram.Program;\nimport org.tugraz.sysds.runtime.controlprogram.ProgramBlock;\nimport org.tugraz.sysds.runtime.controlprogram.WhileProgramBlock;\nimport org.tugraz.sysds.runtime.instructions.Instruction;\n+import org.tugraz.sysds.runtime.lineage.LineageItemUtils;\nimport org.tugraz.sysds.runtime.matrix.data.Pair;\nimport org.tugraz.sysds.utils.Explain;\nimport org.tugraz.sysds.utils.Statistics;\n@@ -420,6 +421,7 @@ public class SpoofCompiler\n//create modified hop dag (operator replacement and CSE)\nif( !cplans.isEmpty() )\n{\n+\n//generate final hop dag\nret = constructModifiedHopDag(roots, cplans, clas);\n@@ -602,6 +604,12 @@ public class SpoofCompiler\n//replace sub-dag with generated operator\nPair<Hop[], Class<?>> tmpCla = clas.get(hop.getHopID());\nCNodeTpl tmpCNode = cplans.get(hop.getHopID()).getValue();\n+\n+ if (DMLScript.LINEAGE) {\n+ //construct and save lineage DAG from pre-modification HOP DAG\n+ LineageItemUtils.constructLineageFromHops(hop, tmpCla.getValue().getName());\n+ }\n+\nhnew = new SpoofFusedOp(hop.getName(), hop.getDataType(), hop.getValueType(),\ntmpCla.getValue(), false, tmpCNode.getOutputDimType());\nHop[] inHops = tmpCla.getKey();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/SpoofCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/SpoofCPInstruction.java",
"diff": "@@ -28,6 +28,7 @@ import org.tugraz.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.tugraz.sysds.runtime.instructions.InstructionUtils;\nimport org.tugraz.sysds.runtime.lineage.LineageItem;\nimport org.tugraz.sysds.runtime.lineage.LineageItemUtils;\n+import org.tugraz.sysds.runtime.lineage.LineageCodegenItem;\nimport org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\npublic class SpoofCPInstruction extends ComputationCPInstruction {\n@@ -96,8 +97,17 @@ public class SpoofCPInstruction extends ComputationCPInstruction {\n}\n@Override\n- public LineageItem[] getLineageItems(ExecutionContext ec) {\n- return new LineageItem[]{new LineageItem(output.getName(),\n- getOpcode(), LineageItemUtils.getLineage(ec, _in))};\n+ public LineageItem[] getLineageItems(ExecutionContext ec)\n+ {\n+ //read and deepcopy the corresponding lineage DAG (pre-codegen)\n+ LineageItem LIroot = LineageCodegenItem.getCodegenLTrace(this.getOperatorClass().getName()).deepCopy();\n+\n+ //replace the placeholders with original instruction inputs.\n+ LineageItemUtils.replaceDagLeaves(ec, LIroot, _in);\n+\n+ //replace the placeholder name with original output's name\n+ LIroot.setName(output.getName());\n+\n+ return new LineageItem[] {LIroot};\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCodegenItem.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.runtime.lineage;\n+\n+import java.util.HashMap;\n+import java.util.Map;\n+\n+public class LineageCodegenItem {\n+ private static Map<String, LineageItem> _codegentraces = new HashMap<>();\n+\n+ public static LineageItem setCodegenLTrace(String classname, LineageItem li) {\n+ return _codegentraces.put(classname, li);\n+ }\n+\n+ public static LineageItem getCodegenLTrace(String classname) {\n+ return _codegentraces.get(classname);\n+ //TODO: test with parfor (synchronization, placeholders, etc)\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItem.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItem.java",
"diff": "@@ -25,7 +25,7 @@ public class LineageItem {\nprivate final long _id;\nprivate final String _opcode;\n- private final String _name;\n+ private String _name;\nprivate final String _data;\nprivate final LineageItem[] _inputs;\nprivate int _hash = 0;\n@@ -84,6 +84,10 @@ public class LineageItem {\nreturn _name;\n}\n+ public void setName(String name) {\n+ _name = name;\n+ }\n+\npublic String getData() {\nreturn _data;\n}\n@@ -176,6 +180,16 @@ public class LineageItem {\nreturn _hash;\n}\n+ public LineageItem deepCopy() { //bottom-up\n+ if (isLeaf())\n+ return new LineageItem(this);\n+\n+ LineageItem[] copyInputs = new LineageItem[getInputs().length];\n+ for (int i=0; i<_inputs.length; i++)\n+ copyInputs[i] = _inputs[i].deepCopy();\n+ return new LineageItem(_name, _opcode, copyInputs);\n+ }\n+\npublic boolean isLeaf() {\nreturn _inputs == null || _inputs.length == 0;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"diff": "@@ -27,15 +27,20 @@ import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\nimport org.tugraz.sysds.runtime.lineage.LineageItem.LineageItemType;\nimport org.tugraz.sysds.common.Types.DataType;\nimport org.tugraz.sysds.common.Types.OpOpN;\n+import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.conf.ConfigurationManager;\n+import org.tugraz.sysds.hops.AggBinaryOp;\n+import org.tugraz.sysds.hops.BinaryOp;\nimport org.tugraz.sysds.hops.DataGenOp;\nimport org.tugraz.sysds.hops.DataOp;\nimport org.tugraz.sysds.hops.Hop;\nimport org.tugraz.sysds.hops.LiteralOp;\n+import org.tugraz.sysds.hops.ReorgOp;\nimport org.tugraz.sysds.hops.Hop.DataGenMethod;\nimport org.tugraz.sysds.hops.Hop.DataOpTypes;\nimport org.tugraz.sysds.hops.rewrite.HopRewriteUtils;\n+import org.tugraz.sysds.lops.Binary;\nimport org.tugraz.sysds.lops.Lop;\nimport org.tugraz.sysds.lops.compile.Dag;\nimport org.tugraz.sysds.parser.DataExpression;\n@@ -250,6 +255,12 @@ public class LineageItemUtils {\noperands.put(item.getId(), unary);\nbreak;\n}\n+ case Reorg: {\n+ Hop input = operands.get(item.getInputs()[0].getId());\n+ Hop reorg = HopRewriteUtils.createReorg(input, ReOrgOp.TRANS);\n+ operands.put(item.getId(), reorg);\n+ break;\n+ }\ncase Binary: {\n//handle special cases of binary operations\nString opcode = (\"^2\".equals(item.getOpcode())\n@@ -261,6 +272,13 @@ public class LineageItemUtils {\noperands.put(item.getId(), binary);\nbreak;\n}\n+ case AggregateBinary: {\n+ Hop input1 = operands.get(item.getInputs()[0].getId());\n+ Hop input2 = operands.get(item.getInputs()[1].getId());\n+ Hop aggbinary = HopRewriteUtils.createMatrixMultiply(input1, input2);\n+ operands.put(item.getId(), aggbinary);\n+ break;\n+ }\ncase Ternary: {\noperands.put(item.getId(), HopRewriteUtils.createTernaryOp(\noperands.get(item.getInputs()[0].getId()),\n@@ -336,6 +354,62 @@ public class LineageItemUtils {\nitem.setVisited();\n}\n+ public static void constructLineageFromHops(Hop root, String claName) {\n+ //probe existence and only generate lineage if non-existing\n+ //(a fused operator might be used in multiple places of a program)\n+ if( LineageCodegenItem.getCodegenLTrace(claName) == null ) {\n+ //recursively construct lineage for fused operator\n+ Map<Long, LineageItem> operands = new HashMap<>();\n+ root.resetVisitStatus(); // ensure non-visited\n+ rConstructLineageFromHops(root, operands);\n+\n+ //cache to avoid reconstruction\n+ LineageCodegenItem.setCodegenLTrace(claName, operands.get(root.getHopID()));\n+ }\n+ }\n+\n+ public static void rConstructLineageFromHops(Hop root, Map<Long, LineageItem> operands) {\n+ if (root.isVisited())\n+ return;\n+\n+ for (int i = 0; i < root.getInput().size(); i++)\n+ rConstructLineageFromHops(root.getInput().get(i), operands);\n+\n+ if ((root instanceof DataOp) && (((DataOp)root).getDataOpType() == DataOpTypes.TRANSIENTREAD)) {\n+ LineageItem li = new LineageItem(root.getName(), \"InputPlaceholder\", \"Create\"+String.valueOf(root.getHopID()));\n+ operands.put(root.getHopID(), li);\n+ return;\n+ }\n+\n+ LineageItem li = null;\n+ ArrayList<LineageItem> LIinputs = new ArrayList<>();\n+ root.getInput().forEach(input->LIinputs.add(operands.get(input.getHopID())));\n+ String name = Dag.getNextUniqueVarname(root.getDataType());\n+\n+ if (root instanceof ReorgOp)\n+ li = new LineageItem(name, \"r'\", LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ else if (root instanceof AggBinaryOp)\n+ li = new LineageItem(name, \"ba+*\", LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ else if (root instanceof BinaryOp)\n+ li = new LineageItem(name, Binary.getOpcode(Hop.HopsOpOp2LopsB.get(((BinaryOp)root).getOp())),\n+ LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+\n+ else if (root instanceof LiteralOp) { //TODO: remove redundancy\n+ StringBuilder sb = new StringBuilder(root.getName());\n+ sb.append(Instruction.VALUETYPE_PREFIX);\n+ sb.append(root.getDataType().toString());\n+ sb.append(Instruction.VALUETYPE_PREFIX);\n+ sb.append(root.getValueType().toString());\n+ sb.append(Instruction.VALUETYPE_PREFIX);\n+ sb.append(true); //isLiteral = true\n+ li = new LineageItem(root.getName(), sb.toString());\n+ }\n+ //TODO: include all the other hops\n+ operands.put(root.getHopID(), li);\n+\n+ root.setVisited();\n+ }\n+\nprivate static Hop constructIndexingOp(LineageItem item, Map<Long, Hop> operands) {\n//TODO fix\nif( \"rightIndex\".equals(item.getOpcode()) )\n@@ -436,6 +510,35 @@ public class LineageItemUtils {\ncurrent.setVisited();\n}\n+ public static void replaceDagLeaves(ExecutionContext ec, LineageItem root, CPOperand[] newLeaves) {\n+ LineageItem[] newLIleaves = LineageItemUtils.getLineage(ec, newLeaves);\n+ HashMap<String, LineageItem> newLImap = new HashMap<>();\n+ for (int i=0; i<newLIleaves.length; i++)\n+ newLImap.put(newLeaves[i].getName(), newLIleaves[i]);\n+\n+ //find and replace the old leaves\n+ HashSet<LineageItem> oldLeaves = new HashSet<>();\n+ root.resetVisitStatus();\n+ rGetDagLeaves(oldLeaves, root);\n+ for (LineageItem leaf : oldLeaves) {\n+ if (leaf.getType() != LineageItemType.Literal)\n+ replace(root, leaf, newLImap.get(leaf.getName()));\n+ }\n+ }\n+\n+ public static void rGetDagLeaves(HashSet<LineageItem> leaves, LineageItem root) {\n+ if (root.isVisited())\n+ return;\n+\n+ if (root.isLeaf())\n+ leaves.add(root);\n+ else {\n+ for (LineageItem li : root.getInputs())\n+ rGetDagLeaves(leaves, li);\n+ }\n+ root.setVisited();\n+ }\n+\nprivate static Hop[] createNaryInputs(LineageItem item, Map<Long, Hop> operands) {\nint len = item.getInputs().length;\nHop[] ret = new Hop[len];\n@@ -502,4 +605,5 @@ public class LineageItemUtils {\nreturn(CPOpInputs != null ? LineageItemUtils.getLineage(ec,\nCPOpInputs.toArray(new CPOperand[CPOpInputs.size()])) : null);\n}\n+\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/LineageCodegenTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.lineage;\n+import java.io.File;\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.hops.OptimizerUtils;\n+import org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\n+import org.tugraz.sysds.runtime.instructions.cp.Data;\n+import org.tugraz.sysds.runtime.lineage.Lineage;\n+import org.tugraz.sysds.runtime.lineage.LineageItem;\n+import org.tugraz.sysds.runtime.lineage.LineageItemUtils;\n+import org.tugraz.sysds.runtime.lineage.LineageParser;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixBlock;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+public class LineageCodegenTest extends AutomatedTestBase {\n+\n+ protected static final String TEST_DIR = \"functions/lineage/\";\n+ protected static final String TEST_NAME1 = \"LineageCodegen1\"; //rand - matrix result\n+\n+ protected String TEST_CLASS_DIR = TEST_DIR + LineageCodegenTest.class.getSimpleName() + \"/\";\n+ private final static String TEST_CONF = \"SystemDS-config-codegen.xml\";\n+ private final static File TEST_CONF_FILE = new File(SCRIPT_DIR + TEST_DIR, TEST_CONF);\n+\n+ protected static final int numRecords = 10;\n+ protected static final int numFeatures = 5;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] {\"R\"}) );\n+ }\n+\n+ @Test\n+ public void testLineageTraceExec1() {\n+ testLineageTraceExec(TEST_NAME1);\n+ }\n+\n+ private void testLineageTraceExec(String testname) {\n+ boolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ boolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n+\n+ try {\n+ System.out.println(\"------------ BEGIN \" + testname + \"------------\");\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = false;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = false;\n+\n+ getAndLoadTestConfiguration(testname);\n+ List<String> proArgs = new ArrayList<>();\n+\n+ proArgs.add(\"-explain\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(output(\"R\"));\n+ proArgs.add(String.valueOf(numRecords));\n+ proArgs.add(String.valueOf(numFeatures));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+ fullDMLScriptName = getScript();\n+\n+ Lineage.resetInternalState();\n+ //run the test\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ //get lineage and generate program\n+ String Rtrace = readDMLLineageFromHDFS(\"R\");\n+ LineageItem R = LineageParser.parseLineageTrace(Rtrace);\n+ Data ret = LineageItemUtils.computeByLineage(R);\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"R\");\n+ MatrixBlock tmp = ((MatrixObject)ret).acquireReadAndRelease();\n+ TestUtils.compareMatrices(dmlfile, tmp, 1e-6);\n+ }\n+ finally {\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = old_simplification;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = old_sum_product;\n+ }\n+ }\n+\n+ /**\n+ * Override default configuration with custom test configuration to ensure\n+ * scratch space and local temporary directory locations are also updated.\n+ */\n+ @Override\n+ protected File getConfigTemplateFile() {\n+ // Instrumentation in this test's output log to show custom configuration file used for template.\n+ System.out.println(\"This test case overrides default configuration with \" + TEST_CONF_FILE.getPath());\n+ return TEST_CONF_FILE;\n+ }\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/LineageCodegen1.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = matrix( 3, rows=4000, cols=2000)\n+U = matrix( 4, rows=4000, cols=10)\n+V = matrix( 5, rows=2000, cols=10)\n+while(FALSE){}\n+eps = 0.1\n+R= t(t(U) %*% (X/(U%*%t(V)+eps)))\n+\n+write(R, $1)\n+\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/SystemDS-config-codegen.xml",
"diff": "+<!--\n+ * Modifications Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed to the Apache Software Foundation (ASF) under one\n+ * or more contributor license agreements. See the NOTICE file\n+ * distributed with this work for additional information\n+ * regarding copyright ownership. The ASF licenses this file\n+ * to you under the Apache License, Version 2.0 (the\n+ * \"License\"); you may not use this file except in compliance\n+ * with the License. You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing,\n+ * software distributed under the License is distributed on an\n+ * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n+ * KIND, either express or implied. See the License for the\n+ * specific language governing permissions and limitations\n+ * under the License.\n+-->\n+\n+<root>\n+ <sysds.localtmpdir>/tmp/systemds</sysds.localtmpdir>\n+ <sysds.scratch>scratch_space</sysds.scratch>\n+ <sysds.optlevel>7</sysds.optlevel>\n+ <sysds.codegen.enabled>true</sysds.codegen.enabled>\n+ <sysds.codegen.plancache>true</sysds.codegen.plancache>\n+ <sysds.codegen.literals>1</sysds.codegen.literals>\n+</root>\n\\ No newline at end of file\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-232] Lineage support for codegen (fused operators)
Closes #109. |
49,730 | 01.03.2020 21:49:05 | -3,600 | f9ba1dbddf1cf2fa3ff939ebf104152df7555e90 | Alternative slice enumeration algorithm (union)
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -193,8 +193,9 @@ SYSTEMDS-230 Lineage Integration\nSYSTEMDS-240 GPU Backend Improvements\n* 241 Dense GPU cumulative aggregates\n-SYSTEMDS-250 Large-Scale Slice Finding\n- * 251 Initial data slicing implementation Python\n+SYSTEMDS-250 Extended Slice Finding\n+ * 251 Alternative slice enumeration approach OK\n+ * 252 Initial data slicing implementation Python\nSYSTEMDS-260 Misc Tools\n* 261 Stable marriage algorithm OK\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/node.py",
"new_path": "scripts/staging/slicing/base/node.py",
"diff": "@@ -31,6 +31,7 @@ class Node:\ne_upper: float\nc_upper: float\ne_max_upper: float\n+ key: \"\"\ndef __init__(self, all_features, model, complete_x, loss, x_size, y_test, preds):\nself.error = loss,\n@@ -43,11 +44,13 @@ class Node:\nself.loss = 0\nself.x_size = x_size\nself.preds = preds\n+ self.s_lower = 1\nself.y_test = y_test\nself.all_features = all_features\n+ self.key = ''\ndef calc_c_upper(self, w):\n- upper_score = w * (self.e_upper / self.s_lower) / (float(self.error) / self.x_size) + (1 - w) * self.s_upper\n+ upper_score = w * (self.e_upper / self.s_lower) / (float(self.error[0]) / self.x_size) + (1 - w) * self.s_upper\nreturn float(upper_score)\ndef make_slice_mask(self):\n@@ -129,9 +132,6 @@ class Node:\ndef calc_s_lower(self, cur_lvl):\nsize_value = self.x_size\nfor parent in self.parents:\n- if cur_lvl == 1:\n- size_value = size_value - (self.x_size - parent.size)\n- else:\nsize_value = size_value - (self.x_size - parent.s_lower)\nreturn max(size_value, 1)\n@@ -158,6 +158,12 @@ class Node:\ndef make_key(self, new_id):\nreturn new_id, self.name\n+ def check_constraint(self, top_k, x_size, alpha):\n+ return self.score >= top_k.min_score and self.size >= x_size / alpha\n+\n+ def check_bounds(self, top_k, x_size, alpha):\n+ return self.s_upper >= x_size / alpha and self.c_upper >= top_k.min_score\n+\ndef print_debug(self, topk, level):\nprint(\"new node has been created: \" + self.make_name() + \"\\n\")\nif level >= 1:\n@@ -169,6 +175,3 @@ class Node:\nprint(\"score = \" + str(self.score))\nprint(\"current topk min score = \" + str(topk.min_score))\nprint(\"-------------------------------------------------------------------------------------\")\n-core))\n- print(\"-------------------------------------------------------------------------------------\")\n-\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/slicer.py",
"new_path": "scripts/staging/slicing/base/slicer.py",
"diff": "@@ -30,7 +30,7 @@ def opt_fun(fi, si, f, x_size, w):\n# slice_name_nonsense function defines if combination of nodes on current level is fine or impossible:\n-# there is dependency between common nodes' common attributes number and current level is such that:\n+# there is a dependency between common nodes' attributes number and current level is such that:\n# commons == cur_lvl - 1\n# valid combination example: node ABC + node BCD (on 4th level) // three attributes nodes have two common attributes\n# invalid combination example: node ABC + CDE (on 4th level) // result node - ABCDE (absurd for 4th level)\n@@ -48,10 +48,6 @@ def union(lst1, lst2):\nreturn final_list\n-def check_for_slicing(node, topk, x_size, alpha):\n- return node.s_upper >= x_size / alpha and node.c_upper >= topk.min_score\n-\n-\n# alpha is size significance coefficient (required for optimization function)\n# verbose option is for returning debug info while creating slices and printing it (in console)\n# k is number of top-slices we want to receive as a result (maximum output, if less all of subsets will be printed)\n@@ -79,7 +75,7 @@ def process(all_features, model, complete_x, loss, x_size, y_test, errors, debug\nfirst_level.append(new_node)\nnew_node.print_debug(top_k, 0)\n# constraints for 1st level nodes to be problematic candidates\n- if new_node.score > 1 and new_node.size >= x_size / alpha:\n+ if new_node.check_constraint(top_k, x_size, alpha):\n# this method updates top k slices if needed\ntop_k.add_new_top_slice(new_node)\ncounter = counter + 1\n@@ -121,15 +117,20 @@ def process(all_features, model, complete_x, loss, x_size, y_test, errors, debug\nall_nodes[new_node.key[1]] = new_node\n# check if concrete data should be extracted or not (only for those that have score upper\n# big enough and if size of subset is big enough\n- to_slice = check_for_slicing(new_node, top_k, x_size, alpha)\n+ to_slice = new_node.check_bounds(top_k, x_size, alpha)\nif to_slice:\nnew_node.process_slice(loss_type)\nnew_node.score = opt_fun(new_node.loss, new_node.size, loss, x_size, w)\n# we decide to add node to current level nodes (in order to make new combinations\n# on the next one or not basing on its score value\n- if new_node.score >= top_k.min_score:\n+ if new_node.check_constraint(top_k, x_size, alpha) and new_node.key not in top_k.keys:\ncur_lvl_nodes.append(new_node)\ntop_k.add_new_top_slice(new_node)\n+ elif new_node.check_bounds(top_k, x_size, alpha):\n+ cur_lvl_nodes.append(new_node)\n+ else:\n+ if new_node.check_bounds(top_k, x_size, alpha):\n+ cur_lvl_nodes.append(new_node)\nif debug:\nnew_node.print_debug(top_k, cur_lvl)\nprint(\"Level \" + str(cur_lvl + 1) + \" had \" + str(len(levels[cur_lvl - 1]) * (len(levels[cur_lvl - 1]) - 1)) +\n@@ -141,4 +142,3 @@ def process(all_features, model, complete_x, loss, x_size, y_test, errors, debug\nprint()\nprint(\"Selected slices are: \")\ntop_k.print_topk()\n-\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/tests/classification/test_adult.py",
"new_path": "scripts/staging/slicing/base/tests/classification/test_adult.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\n@@ -66,5 +84,15 @@ for pred in preds:\nmistakes = mistakes + 1\ncounter = counter + 1\nlossF = mistakes / counter\n-slicer.process(all_features, clf, complete_x, lossF, x_size, complete_y, predictions, debug=True, alpha=4, k=10, w=0.5,\n- loss_type=1)\n+\n+# enumerator <union>/<join> indicates an approach of next level slices combination process:\n+# in case of <join> in order to create new node of current level slicer\n+# combines only nodes of previous layer with each other\n+# <union> case implementation is based on DPSize algorithm\n+enumerator = \"union\"\n+if enumerator == \"join\":\n+ slicer.process(all_features, clf, complete_x, lossF, x_size, complete_y, predictions, debug=True, alpha=4, k=10,\n+ w=0.5, loss_type=1)\n+elif enumerator == \"union\":\n+ union_slicer.process(all_features, clf, complete_x, lossF, x_size, complete_y, predictions, debug=True, alpha=4,\n+ k=10, w=0.5, loss_type=1)\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/tests/classification/test_iris.py",
"new_path": "scripts/staging/slicing/base/tests/classification/test_iris.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\nimport pandas as pd\nfrom sklearn.preprocessing import OneHotEncoder\n@@ -53,5 +71,15 @@ for pred in preds:\nmistakes = mistakes + 1\ncounter = counter + 1\nlossF = mistakes / counter\n+\n+# enumerator <union>/<join> indicates an approach of next level slices combination process:\n+# in case of <join> in order to create new node of current level slicer\n+# combines only nodes of previous layer with each other\n+# <union> case implementation is based on DPSize algorithm\n+enumerator = \"join\"\n+if enumerator == \"join\":\nslicer.process(all_features, clf, complete_x, lossF, x_size, complete_y, predictions, debug=True, alpha=6, k=10,\nw=0.5, loss_type=1)\n+elif enumerator == \"union\":\n+ union_slicer.process(all_features, clf, complete_x, lossF, x_size, complete_y, predictions, debug=True, alpha=6, k=10,\n+ w=0.5, loss_type=1)\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/tests/regression/test_insurance.py",
"new_path": "scripts/staging/slicing/base/tests/regression/test_insurance.py",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n@@ -46,5 +64,15 @@ for pred in preds:\n# verbose option is for returning debug info while creating slices and printing it\n# k is number of top-slices we want\n# w is a weight of error function significance (1 - w) is a size significance propagated into optimization function\n+\n+# enumerator <union>/<join> indicates an approach of next level slices combination process:\n+# in case of <join> in order to create new node of current level slicer\n+# combines only nodes of previous layer with each other\n+# <union> case implementation is based on DPSize algorithm\n+enumerator = \"union\"\n+if enumerator == \"join\":\nslicer.process(all_features, model, complete_x, f_l2, x_size, y_test, errors, debug=True, alpha=5, k=10,\nw=0.5, loss_type=0)\n+elif enumerator == \"union\":\n+ union_slicer.process(all_features, model, complete_x, f_l2, x_size, y_test, errors, debug=True, alpha=5, k=10,\n+ w=0.5, loss_type=0)\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/tests/regression/test_salary.py",
"new_path": "scripts/staging/slicing/base/tests/regression/test_salary.py",
"diff": "@@ -64,6 +64,21 @@ for pred in preds:\n# verbose option is for returning debug info while creating slices and printing it\n# k is number of top-slices we want\n# w is a weight of error function significance (1 - w) is a size significance propagated into optimization function\n+<<<<<<< HEAD:scripts/staging/slicing/base/tests/regression/test_salary.py\nslicer.process(all_features, model, complete_x, f_l2, x_size, y_test, errors, debug=True, alpha=4, k=10, w=0.5,\nloss_type=0)\n+=======\n+\n+# enumerator <union>/<join> indicates an approach of next level slices combination process:\n+# in case of <join> in order to create new node of current level slicer\n+# combines only nodes of previous layer with each other\n+# <union> case implementation is based on DPSize algorithm\n+enumerator = \"union\"\n+if enumerator == \"join\":\n+ slicer.process(all_features, model, complete_x, f_l2, x_size, y_test, errors, debug=True, alpha=4, k=10, w=0.5,\n+ loss_type=0)\n+elif enumerator == \"union\":\n+ union_slicer.process(all_features, model, complete_x, f_l2, x_size, y_test, errors, debug=True, alpha=4, k=10, w=0.5,\n+ loss_type=0)\n+>>>>>>> [SYSTEMDS-xxx] Alternative slice enumeration algorithm:scripts/staging/slicing/base/tests/regression/test_salary.py\n"
},
{
"change_type": "MODIFY",
"old_path": "scripts/staging/slicing/base/top_k.py",
"new_path": "scripts/staging/slicing/base/top_k.py",
"diff": "@@ -20,10 +20,12 @@ class Topk:\nk: int\nmin_score: float\nslices: []\n+ keys: []\ndef __init__(self, k):\nself.k = k\nself.slices = []\n+ self.keys = []\nself.min_score = 1\ndef top_k_min_score(self):\n@@ -35,12 +37,16 @@ class Topk:\nself.min_score = new_top_slice.score\nif len(self.slices) < self.k:\nself.slices.append(new_top_slice)\n+ self.keys.append(new_top_slice.key)\nreturn self.top_k_min_score()\nelse:\nself.slices[len(self.slices) - 1] = new_top_slice\n+ self.keys[len(self.slices) - 1] = new_top_slice.key\nreturn self.top_k_min_score()\ndef print_topk(self):\nfor candidate in self.slices:\nprint(candidate.name + \": \" + \"score = \" + str(candidate.score) + \"; size = \" + str(candidate.size))\n+ print(candidate.name + \": \" + \"score = \" + str(candidate.score) + \"; size = \" + str(candidate.size))\n+\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "scripts/staging/slicing/base/union_slicer.py",
"diff": "+from slicing.node import Node\n+from slicing.top_k import Topk\n+from slicing.slicer import opt_fun, union\n+\n+\n+def check_attributes(left_node, right_node):\n+ flag = False\n+ for attr1 in left_node.attributes:\n+ for attr2 in right_node.attributes:\n+ if attr1[0].split(\"_\")[0] == attr2[0].split(\"_\")[0]:\n+ # there are common attributes which is not the case we need\n+ flag = True\n+ break\n+ return flag\n+\n+\n+def process(all_features, model, complete_x, loss, x_size, y_test, errors, debug, alpha, k, w, loss_type):\n+ counter = 0\n+ # First level slices are enumerated in a \"classic way\" (getting data and not analyzing bounds\n+ first_level = []\n+ levels = []\n+ all_nodes = {}\n+ top_k = Topk(k)\n+ for feature in all_features:\n+ new_node = Node(all_features, model, complete_x, loss, x_size, y_test, errors)\n+ new_node.parents = [(feature, counter)]\n+ new_node.attributes.append((feature, counter))\n+ new_node.name = new_node.make_name()\n+ new_id = len(all_nodes)\n+ new_node.key = new_node.make_key(new_id)\n+ all_nodes[new_node.key] = new_node\n+ new_node.process_slice(loss_type)\n+ # for first level nodes all bounds are strict as concrete metrics\n+ new_node.s_upper = new_node.size\n+ new_node.s_lower = 0\n+ new_node.e_upper = new_node.loss\n+ new_node.e_max_upper = new_node.e_max\n+ new_node.score = opt_fun(new_node.loss, new_node.size, loss, x_size, w)\n+ new_node.c_upper = new_node.score\n+ first_level.append(new_node)\n+ new_node.print_debug(top_k, 0)\n+ # constraints for 1st level nodes to be problematic candidates\n+ if new_node.score > 1 and new_node.size >= x_size / alpha:\n+ # this method updates top k slices if needed\n+ top_k.add_new_top_slice(new_node)\n+ counter = counter + 1\n+ # double appending of first level nodes in order to enumerating second level in the same way as others\n+ levels.append((first_level, len(all_features)))\n+ levels.append((first_level, len(all_features)))\n+\n+ # cur_lvl - index of current level, correlates with number of slice forming features\n+ cur_lvl = 2 # level that is planned to be filled later\n+ cur_lvl_nodes = first_level\n+ # currently for debug\n+ print(\"Level 1 had \" + str(len(all_features)) + \" candidates\")\n+ print()\n+ print(\"Current topk are: \")\n+ top_k.print_topk()\n+ # DPSize algorithm approach of previous levels nodes combinations and updating bounds for those that already exist\n+ while len(cur_lvl_nodes) > 0:\n+ cur_lvl_nodes = []\n+ count = 0\n+ for left in range(int(cur_lvl / 2)):\n+ right = cur_lvl - 1 - left\n+ for node_i in range(len(levels[left][0])):\n+ for node_j in range(len(levels[right][0])):\n+ flag = check_attributes(levels[left][0][node_i], levels[right][0][node_j])\n+ if not flag:\n+ new_node = Node(all_features, model, complete_x, loss, x_size, y_test, errors)\n+ parents_set = set(new_node.parents)\n+ parents_set.add(levels[left][0][node_i])\n+ parents_set.add(levels[right][0][node_j])\n+ new_node.parents = list(parents_set)\n+ parent1_attr = levels[left][0][node_i].attributes\n+ parent2_attr = levels[right][0][node_j].attributes\n+ new_node_attr = union(parent1_attr, parent2_attr)\n+ new_node.attributes = new_node_attr\n+ new_node.name = new_node.make_name()\n+ new_id = len(all_nodes)\n+ new_node.key = new_node.make_key(new_id)\n+ if new_node.key[1] in all_nodes:\n+ existing_item = all_nodes[new_node.key[1]]\n+ parents_set = set(existing_item.parents)\n+ existing_item.parents = parents_set\n+ s_upper = new_node.calc_s_upper(cur_lvl)\n+ s_lower = new_node.calc_s_lower(cur_lvl)\n+ e_upper = new_node.calc_e_upper()\n+ e_max_upper = new_node.calc_e_max_upper(cur_lvl)\n+ try:\n+ minimized = min(s_upper, new_node.s_upper)\n+ new_node.s_upper = minimized\n+ minimized = min(s_lower, new_node.s_lower)\n+ new_node.s_lower = minimized\n+ minimized = min(e_upper, new_node.e_upper)\n+ new_node.e_upper = minimized\n+ minimized= min(e_max_upper, new_node.e_max_upper)\n+ new_node.e_max_upper = minimized\n+ c_upper = new_node.calc_c_upper(w)\n+ minimized= min(c_upper, new_node.c_upper)\n+ new_node.c_upper = minimized\n+ except AttributeError:\n+ # initial bounds calculation\n+ new_node.s_upper = s_upper\n+ new_node.s_lower = s_lower\n+ new_node.e_upper = e_upper\n+ new_node.e_max_upper = e_max_upper\n+ c_upper = new_node.calc_c_upper(w)\n+ new_node.c_upper = c_upper\n+ minimized = min(c_upper, new_node.c_upper)\n+ new_node.c_upper = minimized\n+ else:\n+ new_node.calc_bounds(cur_lvl, w)\n+ all_nodes[new_node.key[1]] = new_node\n+ # check if concrete data should be extracted or not (only for those that have score upper\n+ # big enough and if size of subset is big enough\n+ to_slice = new_node.check_bounds(top_k, x_size, alpha)\n+ if to_slice:\n+ new_node.process_slice(loss_type)\n+ new_node.score = opt_fun(new_node.loss, new_node.size, loss, x_size, w)\n+ # we decide to add node to current level nodes (in order to make new combinations\n+ # on the next one or not basing on its score value\n+ if new_node.score >= top_k.min_score and new_node.size >= x_size / alpha \\\n+ and new_node.key not in top_k.keys:\n+ cur_lvl_nodes.append(new_node)\n+ top_k.add_new_top_slice(new_node)\n+ else:\n+ if new_node.s_upper >= x_size / alpha and new_node.c_upper >= top_k.min_score:\n+ cur_lvl_nodes.append(new_node)\n+ if debug:\n+ new_node.print_debug(top_k, cur_lvl)\n+ count = count + levels[left][1] * levels[right][1]\n+ print(\"Level \" + str(cur_lvl) + \" had \" + str(count) +\n+ \" candidates but after pruning only \" + str(len(cur_lvl_nodes)) + \" go to the next level\")\n+ cur_lvl = cur_lvl + 1\n+ levels.append((cur_lvl_nodes, count))\n+ top_k.print_topk()\n+ print(\"Program stopped at level \" + str(cur_lvl))\n+ print()\n+ print(\"Selected slices are: \")\n+ top_k.print_topk()\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-251] Alternative slice enumeration algorithm (union)
Closes #105. |
49,714 | 01.03.2020 22:26:31 | -3,600 | e2b985807c485b3c3f1b63e2926a2f5478441641 | Fix named arguments in MNIST LeNet example script
Closes | [
{
"change_type": "MODIFY",
"old_path": "scripts/nn/examples/mnist_lenet.dml",
"new_path": "scripts/nn/examples/mnist_lenet.dml",
"diff": "@@ -118,13 +118,13 @@ train = function(matrix[double] X, matrix[double] Y,\nstride, stride, pad, pad)\noutr1 = relu::forward(outc1)\n[outp1, Houtp1, Woutp1] = max_pool2d::forward(outr1, F1, Houtc1, Woutc1, Hf=2, Wf=2,\n- strideh=2, stridew=2, pad=0, pad=0)\n+ strideh=2, stridew=2, padh=0, padw=0)\n## layer 2: conv2 -> relu2 -> pool2\n[outc2, Houtc2, Woutc2] = conv2d::forward(outp1, W2, b2, F1, Houtp1, Woutp1, Hf, Wf,\nstride, stride, pad, pad)\noutr2 = relu::forward(outc2)\n[outp2, Houtp2, Woutp2] = max_pool2d::forward(outr2, F2, Houtc2, Woutc2, Hf=2, Wf=2,\n- strideh=2, stridew=2, pad=0, pad=0)\n+ strideh=2, stridew=2, padh=0, padw=0)\n## layer 3: affine3 -> relu3 -> dropout\nouta3 = affine::forward(outp2, W3, b3)\noutr3 = relu::forward(outa3)\n@@ -166,13 +166,13 @@ train = function(matrix[double] X, matrix[double] Y,\n[doutp2, dW3, db3] = affine::backward(douta3, outp2, W3, b3)\n## layer 2: conv2 -> relu2 -> pool2\ndoutr2 = max_pool2d::backward(doutp2, Houtp2, Woutp2, outr2, F2, Houtc2, Woutc2, Hf=2, Wf=2,\n- strideh=2, stridew=2, pad=0, pad=0)\n+ strideh=2, stridew=2, padh=0, padw=0)\ndoutc2 = relu::backward(doutr2, outc2)\n[doutp1, dW2, db2] = conv2d::backward(doutc2, Houtc2, Woutc2, outp1, W2, b2, F1,\nHoutp1, Woutp1, Hf, Wf, stride, stride, pad, pad)\n## layer 1: conv1 -> relu1 -> pool1\ndoutr1 = max_pool2d::backward(doutp1, Houtp1, Woutp1, outr1, F1, Houtc1, Woutc1, Hf=2, Wf=2,\n- strideh=2, stridew=2, pad=0, pad=0)\n+ strideh=2, stridew=2, padh=0, padw=0)\ndoutc1 = relu::backward(doutr1, outc1)\n[dX_batch, dW1, db1] = conv2d::backward(doutc1, Houtc1, Woutc1, X_batch, W1, b1, C, Hin, Win,\nHf, Wf, stride, stride, pad, pad)\n@@ -264,13 +264,13 @@ predict = function(matrix[double] X, int C, int Hin, int Win,\npad, pad)\noutr1 = relu::forward(outc1)\n[outp1, Houtp1, Woutp1] = max_pool2d::forward(outr1, F1, Houtc1, Woutc1, Hf=2, Wf=2,\n- strideh=2, stridew=2, pad=0, pad=0)\n+ strideh=2, stridew=2, padh=0, padw=0)\n## layer 2: conv2 -> relu2 -> pool2\n[outc2, Houtc2, Woutc2] = conv2d::forward(outp1, W2, b2, F1, Houtp1, Woutp1, Hf, Wf,\nstride, stride, pad, pad)\noutr2 = relu::forward(outc2)\n[outp2, Houtp2, Woutp2] = max_pool2d::forward(outr2, F2, Houtc2, Woutc2, Hf=2, Wf=2,\n- strideh=2, stridew=2, pad=0, pad=0)\n+ strideh=2, stridew=2, padh=0, padw=0)\n## layer 3: affine3 -> relu3\nouta3 = affine::forward(outp2, W3, b3)\noutr3 = relu::forward(outa3)\n@@ -328,4 +328,3 @@ generate_dummy_data = function()\nclasses = round(rand(rows=N, cols=1, min=1, max=K, pdf=\"uniform\"))\nY = table(seq(1, N), classes) # one-hot encoding\n}\n-\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMML-2533] Fix named arguments in MNIST LeNet example script
Closes #866. |
49,693 | 03.03.2020 13:39:02 | -3,600 | 64ed73deefeb38bb3e0fb4759bab7d8f31095ce7 | [BUGFIX] fix for the latest codegen bugfix (cleanup while squash-merging changed the behavior) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/codegen/template/TemplateOuterProduct.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/codegen/template/TemplateOuterProduct.java",
"diff": "@@ -134,9 +134,14 @@ public class TemplateOuterProduct extends TemplateBase {\nHop U = inHops2.get(\"_U\");\nHop V = inHops2.get(\"_V\");\nLinkedList<Hop> sinHops = new LinkedList<>(inHops);\n- sinHops.remove(V); sinHops.addFirst(V);\n- sinHops.remove(U); sinHops.addFirst(U);\n- sinHops.remove(X); sinHops.addFirst(X);\n+\n+ // order of adds and removes is important here\n+ sinHops.remove(V);\n+ sinHops.remove(U);\n+ sinHops.remove(X);\n+ sinHops.addFirst(V);\n+ sinHops.addFirst(U);\n+ sinHops.addFirst(X);\n//construct template node\nArrayList<CNode> inputs = new ArrayList<>();\n@@ -160,7 +165,7 @@ public class TemplateOuterProduct extends TemplateBase {\nif( tmp.containsKey(hop.getHopID()) )\nreturn;\n- //recursively process required childs\n+ //recursively process required children\nMemoTableEntry me = memo.getBest(hop.getHopID(), TemplateType.OUTER, TemplateType.CELL);\nfor( int i=0; i<hop.getInput().size(); i++ ) {\nHop c = hop.getInput().get(i);\n@@ -223,9 +228,12 @@ public class TemplateOuterProduct extends TemplateBase {\nelse\ninHops2.put(\"_V\", hop.getInput().get(1));\n- //TODO find out why we need to propagate this at all\n- //(maybe a more generic treatment will yield the same result?)\n- if(hop instanceof AggBinaryOp)\n+ /* TODO find out why we need to propagate this at all\n+ * (maybe a more generic treatment will yield the same result?)\n+ * At the moment this is needed to decide whether we need to add\n+ * a duplicate input (CNodeOuterProduct constructor) and if we\n+ * need to fill in a transpose in rConstructModifiedHopDag in SpoofCompiler.\n+ */\nmmtsj = ((AggBinaryOp) hop).checkTransposeSelf(); //determine tsmm pattern\nout = new CNodeBinary(cdata1, cdata2, BinType.DOT_PRODUCT);\n"
}
] | Java | Apache License 2.0 | apache/systemds | [BUGFIX] fix for the latest codegen bugfix (cleanup while squash-merging changed the behavior) |
49,689 | 05.03.2020 23:37:44 | -3,600 | c01a98c99f1d878eb25f24b044de0ae1452cc402 | Reuse of spoof operator result
This patch includes changes in LineageCache to enable reuse of spoof
instruction results. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "@@ -316,7 +316,8 @@ public class LineageCache {\n|| inst.getOpcode().equalsIgnoreCase(\"groupedagg\")\n|| inst.getOpcode().equalsIgnoreCase(\"r'\")\n|| (inst.getOpcode().equalsIgnoreCase(\"append\") && isVectorAppend(inst, ec))\n- || inst.getOpcode().equalsIgnoreCase(\"solve\");\n+ || inst.getOpcode().equalsIgnoreCase(\"solve\")\n+ || inst.getOpcode().contains(\"spoof\");\n}\nprivate static boolean isVectorAppend(Instruction inst, ExecutionContext ec) {\n@@ -380,7 +381,8 @@ public class LineageCache {\nprivate static double getRecomputeEstimate(Instruction inst, ExecutionContext ec) {\nlong t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;\ndouble nflops = 0;\n- CPType cptype = CPInstructionParser.String2CPInstructionType.get(inst.getOpcode());\n+ String instop= inst.getOpcode().contains(\"spoof\") ? \"spoof\" : inst.getOpcode();\n+ CPType cptype = CPInstructionParser.String2CPInstructionType.get(instop);\n//TODO: All other relevant instruction types.\nswitch (cptype)\n{\n@@ -500,6 +502,12 @@ public class LineageCache {\nbreak;\n}\n+ case SpoofFused: //spoof\n+ {\n+ nflops = 0; //FIXME: this method will be deprecated\n+ break;\n+ }\n+\ndefault:\nthrow new DMLRuntimeException(\"Lineage Cache: unsupported instruction: \"+inst.getOpcode());\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/LineageCodegenTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/LineageCodegenTest.java",
"diff": "@@ -25,6 +25,7 @@ import org.tugraz.sysds.hops.OptimizerUtils;\nimport org.tugraz.sysds.runtime.controlprogram.caching.MatrixObject;\nimport org.tugraz.sysds.runtime.instructions.cp.Data;\nimport org.tugraz.sysds.runtime.lineage.Lineage;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\nimport org.tugraz.sysds.runtime.lineage.LineageItem;\nimport org.tugraz.sysds.runtime.lineage.LineageItemUtils;\nimport org.tugraz.sysds.runtime.lineage.LineageParser;\n@@ -37,7 +38,9 @@ import org.tugraz.sysds.test.TestUtils;\npublic class LineageCodegenTest extends AutomatedTestBase {\nprotected static final String TEST_DIR = \"functions/lineage/\";\n- protected static final String TEST_NAME1 = \"LineageCodegen1\"; //rand - matrix result\n+ protected static final String TEST_NAME1 = \"LineageCodegenTrace\"; //rand - matrix result\n+ protected static final String TEST_NAME2 = \"CodegenReuse1\";\n+ protected static final String TEST_NAME3 = \"CodegenReuse2\";\nprotected String TEST_CLASS_DIR = TEST_DIR + LineageCodegenTest.class.getSimpleName() + \"/\";\nprivate final static String TEST_CONF = \"SystemDS-config-codegen.xml\";\n@@ -50,14 +53,26 @@ public class LineageCodegenTest extends AutomatedTestBase {\npublic void setUp() {\nTestUtils.clearAssertionInformation();\naddTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] {\"R\"}) );\n+ addTestConfiguration( TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] {\"R\"}) );\n+ addTestConfiguration( TEST_NAME3, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME3, new String[] {\"R\"}) );\n}\n@Test\n- public void testLineageTraceExec1() {\n- testLineageTraceExec(TEST_NAME1);\n+ public void testCodegenLineageTrace() { //Tracing of spoof instruction\n+ testLineageTrace(TEST_NAME1);\n}\n- private void testLineageTraceExec(String testname) {\n+ @Test\n+ public void testCodegenReuse1() { //Cache hit\n+ testLineageTrace(TEST_NAME2);\n+ }\n+\n+ @Test\n+ public void testCodegenReuse2() { //Cache miss\n+ testLineageTrace(TEST_NAME3);\n+ }\n+\n+ private void testLineageTrace(String testname) {\nboolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\nboolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n@@ -70,7 +85,9 @@ public class LineageCodegenTest extends AutomatedTestBase {\nList<String> proArgs = new ArrayList<>();\nproArgs.add(\"-explain\");\n+ proArgs.add(\"-stats\");\nproArgs.add(\"-lineage\");\n+ proArgs.add(ReuseCacheType.REUSE_FULL.name().toLowerCase());\nproArgs.add(\"-args\");\nproArgs.add(output(\"R\"));\nproArgs.add(String.valueOf(numRecords));\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/CodegenReuse1.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = matrix( 3, rows=4000, cols=2000)\n+U = matrix( 4, rows=4000, cols=10)\n+V = matrix( 5, rows=2000, cols=10)\n+while(FALSE){}\n+eps = 0.1\n+R1 = t(t(U) %*% (X/(U%*%t(V)+eps)))\n+\n+while(FALSE){}\n+R2 = t(t(U) %*% (X/(U%*%t(V)+eps))) #cache hit\n+R = R1 + R2;\n+\n+write(R, $1)\n+\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/CodegenReuse2.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = matrix( 3, rows=4000, cols=2000)\n+U = matrix( 4, rows=4000, cols=10)\n+V = matrix( 5, rows=2000, cols=10)\n+while(FALSE){}\n+eps = 0.1\n+R1 = t(t(U) %*% (X/(U%*%t(V)+eps)))\n+\n+while(FALSE){}\n+eps = 0.2; #generate cache miss\n+R2 = t(t(U) %*% (X/(U%*%t(V)+eps))) #cache miss\n+R = R1 + R2;\n+\n+write(R, $1)\n+\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/scripts/functions/lineage/LineageCodegen1.dml",
"new_path": "src/test/scripts/functions/lineage/LineageCodegenTrace.dml",
"diff": "X = matrix( 3, rows=4000, cols=2000)\nU = matrix( 4, rows=4000, cols=10)\nV = matrix( 5, rows=2000, cols=10)\n+\nwhile(FALSE){}\neps = 0.1\nR = t(t(U) %*% (X/(U%*%t(V)+eps)))\n"
}
] | Java | Apache License 2.0 | apache/systemds | Reuse of spoof operator result
This patch includes changes in LineageCache to enable reuse of spoof
instruction results. |
49,738 | 08.03.2020 19:29:53 | -3,600 | a6983be0c0216ec53b9234281e4ab388cc6d355a | [MINOR] Fix various warnings (unnecessary casts/imports, hidden fields) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/compress/ColGroupOffset.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/compress/ColGroupOffset.java",
"diff": "@@ -472,12 +472,12 @@ public abstract class ColGroupOffset extends ColGroupValue {\n}\nprotected class ZeroValueIterator implements Iterator<Integer> {\n- private final boolean[] _zeros;\n+ private final boolean[] _zeroVect;\nprivate final int _ru;\nprivate int _rpos;\npublic ZeroValueIterator(int rl, int ru) {\n- _zeros = computeZeroIndicatorVector();\n+ _zeroVect = computeZeroIndicatorVector();\n_ru = ru;\n_rpos = rl - 1;\ngetNextValue();\n@@ -499,7 +499,7 @@ public abstract class ColGroupOffset extends ColGroupValue {\ndo {\n_rpos++;\n}\n- while(_rpos < _ru && !_zeros[_rpos]);\n+ while(_rpos < _ru && !_zeroVect[_rpos]);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/compress/ColGroupUncompressed.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/compress/ColGroupUncompressed.java",
"diff": "@@ -300,7 +300,7 @@ public class ColGroupUncompressed extends ColGroup {\n@Override\npublic ColGroup scalarOperation(ScalarOperator op) {\n// execute scalar operations\n- MatrixBlock retContent = (MatrixBlock) _data.scalarOperations(op, new MatrixBlock());\n+ MatrixBlock retContent = _data.scalarOperations(op, new MatrixBlock());\n// construct new uncompressed column group\nreturn new ColGroupUncompressed(getColIndices(), _data.getNumRows(), retContent);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/compress/CompressedMatrixBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/compress/CompressedMatrixBlock.java",
"diff": "@@ -109,7 +109,7 @@ public class CompressedMatrixBlock extends MatrixBlock {\nstatic {\n// for internal debugging only\nif(LOCAL_DEBUG) {\n- Logger.getLogger(\"org.tugraz.sysds.runtime.compress\").setLevel((Level) LOCAL_DEBUG_LEVEL);\n+ Logger.getLogger(\"org.tugraz.sysds.runtime.compress\").setLevel(LOCAL_DEBUG_LEVEL);\n}\n}\n// ------------------------------\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/compress/estim/CompressedSizeEstimatorSample.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/compress/estim/CompressedSizeEstimatorSample.java",
"diff": "@@ -406,7 +406,7 @@ public class CompressedSizeEstimatorSample extends CompressedSizeEstimator {\n*\n*\n*/\n- double A = (int) nRows - NTilde;\n+ double A = nRows - NTilde;\ndouble B = A - sampleSize + 1;\ndouble C = nRows;\ndouble D = nRows - sampleSize + 1;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/AutomatedTestBase.java",
"new_path": "src/test/java/org/tugraz/sysds/test/AutomatedTestBase.java",
"diff": "@@ -1179,16 +1179,13 @@ public abstract class AutomatedTestBase {\n}\nprotected int getRandomAvailablePort(){\n- try {\n- ServerSocket availableSocket = new ServerSocket(0);\n- int port = availableSocket.getLocalPort();\n- availableSocket.close();\n- return port;\n+ try (ServerSocket availableSocket = new ServerSocket(0) ) {\n+ return availableSocket.getLocalPort();\n}\ncatch(IOException e) {\n// If no port was found just use 9999\n+ return 9990;\n}\n- return 9999;\n}\nprotected Thread startLocalFedWorker(int port) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/applications/L2SVMTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/applications/L2SVMTest.java",
"diff": "@@ -108,6 +108,7 @@ public class L2SVMTest extends ApplicationTestBase {\n}\n@After\n+ @Override\npublic void teardown() {\nrtplatform = platformOld;\nDMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/component/compress/CompressedMatrixTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/component/compress/CompressedMatrixTest.java",
"diff": "@@ -159,12 +159,10 @@ public class CompressedMatrixTest extends CompressedTestBase {\n.convertToMatrixBlock(TestUtils.generateTestMatrix(rows, 1, 0, 1, 1.0, 3)) : null;\n// matrix-vector uncompressed\n- MatrixBlock ret1 = (MatrixBlock) mb\n- .chainMatrixMultOperations(vector1, vector2, new MatrixBlock(), ctype);\n+ MatrixBlock ret1 = mb.chainMatrixMultOperations(vector1, vector2, new MatrixBlock(), ctype);\n// matrix-vector compressed\n- MatrixBlock ret2 = (MatrixBlock) cmb\n- .chainMatrixMultOperations(vector1, vector2, new MatrixBlock(), ctype);\n+ MatrixBlock ret2 = cmb.chainMatrixMultOperations(vector1, vector2, new MatrixBlock(), ctype);\n// compare result with input\ndouble[][] d1 = DataConverter.convertToDoubleMatrix(ret1);\n@@ -273,10 +271,10 @@ public class CompressedMatrixTest extends CompressedTestBase {\n// matrix-scalar uncompressed\nScalarOperator sop = new RightScalarOperator(Plus.getPlusFnObject(), 7);\n- MatrixBlock ret1 = (MatrixBlock) mb.scalarOperations(sop, new MatrixBlock());\n+ MatrixBlock ret1 = mb.scalarOperations(sop, new MatrixBlock());\n// matrix-scalar compressed\n- MatrixBlock ret2 = (MatrixBlock) cmb.scalarOperations(sop, new MatrixBlock());\n+ MatrixBlock ret2 = cmb.scalarOperations(sop, new MatrixBlock());\nif(compress)\nret2 = ((CompressedMatrixBlock) ret2).decompress();\n@@ -300,10 +298,10 @@ public class CompressedMatrixTest extends CompressedTestBase {\n// matrix-scalar uncompressed\nScalarOperator sop = new RightScalarOperator(Multiply.getMultiplyFnObject(), 7);\n- MatrixBlock ret1 = (MatrixBlock) mb.scalarOperations(sop, new MatrixBlock());\n+ MatrixBlock ret1 = mb.scalarOperations(sop, new MatrixBlock());\n// matrix-scalar compressed\n- MatrixBlock ret2 = (MatrixBlock) cmb.scalarOperations(sop, new MatrixBlock());\n+ MatrixBlock ret2 = cmb.scalarOperations(sop, new MatrixBlock());\nif(compress)\nret2 = ((CompressedMatrixBlock) ret2).decompress();\n@@ -370,12 +368,10 @@ public class CompressedMatrixTest extends CompressedTestBase {\nbreak;\n}\n// matrix-vector uncompressed\n- MatrixBlock ret1 = (MatrixBlock) mb\n- .aggregateUnaryOperations(auop, new MatrixBlock(), Math.max(rows, cols), null, true);\n+ MatrixBlock ret1 = mb.aggregateUnaryOperations(auop, new MatrixBlock(), Math.max(rows, cols), null, true);\n// matrix-vector compressed\n- MatrixBlock ret2 = (MatrixBlock) cmb\n- .aggregateUnaryOperations(auop, new MatrixBlock(), Math.max(rows, cols), null, true);\n+ MatrixBlock ret2 = cmb.aggregateUnaryOperations(auop, new MatrixBlock(), Math.max(rows, cols), null, true);\n// compare result with input\ndouble[][] d1 = DataConverter.convertToDoubleMatrix(ret1);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/component/compress/CompressedVectorTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/component/compress/CompressedVectorTest.java",
"diff": "@@ -57,7 +57,7 @@ public class CompressedVectorTest extends CompressedTestBase {\nMatrixBlock cmbDeCompressed;\ndouble[][] deCompressed;\n- protected static MatrixType[] usedMatrixType = new MatrixType[] {// types\n+ protected static MatrixType[] usedMatrixTypeLocal = new MatrixType[] {// types\nMatrixType.SINGLE_COL, MatrixType.SINGLE_COL_L};\n@Parameters\n@@ -67,7 +67,7 @@ public class CompressedVectorTest extends CompressedTestBase {\nfor(ValueType vt : usedValueTypes) {\nfor(ValueRange vr : usedValueRanges) {\nfor(CompressionType ct : usedCompressionTypes) {\n- for(MatrixType mt : usedMatrixType) {\n+ for(MatrixType mt : usedMatrixTypeLocal) {\nfor(double sr : samplingRatio) {\ntests.add(new Object[] {st, vt, vr, ct, mt, true, sr});\n}\n@@ -125,11 +125,11 @@ public class CompressedVectorTest extends CompressedTestBase {\npublic void testQuantile() {\ntry {\n// quantile uncompressed\n- MatrixBlock tmp1 = (MatrixBlock) mb.sortOperations(null, new MatrixBlock());\n+ MatrixBlock tmp1 = mb.sortOperations(null, new MatrixBlock());\ndouble ret1 = tmp1.pickValue(0.95);\n// quantile compressed\n- MatrixBlock tmp2 = (MatrixBlock) cmb.sortOperations(null, new MatrixBlock());\n+ MatrixBlock tmp2 = cmb.sortOperations(null, new MatrixBlock());\ndouble ret2 = tmp2.pickValue(0.95);\n// compare result with input\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/component/compress/ParCompressedMatrixTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/component/compress/ParCompressedMatrixTest.java",
"diff": "package org.tugraz.sysds.test.component.compress;\n-import java.util.ArrayList;\n-import java.util.Collection;\n-\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\n-import org.junit.runners.Parameterized.Parameters;\nimport org.tugraz.sysds.lops.MMTSJ.MMTSJType;\nimport org.tugraz.sysds.lops.MapMultChain.ChainType;\nimport org.tugraz.sysds.runtime.compress.CompressedMatrixBlock;\n@@ -130,12 +126,10 @@ public class ParCompressedMatrixTest extends CompressedTestBase {\n.convertToMatrixBlock(TestUtils.generateTestMatrix(rows, 1, 0, 1, 1.0, 3)) : null;\n// matrix-vector uncompressed\n- MatrixBlock ret1 = (MatrixBlock) mb\n- .chainMatrixMultOperations(vector1, vector2, new MatrixBlock(), ctype, k);\n+ MatrixBlock ret1 = mb.chainMatrixMultOperations(vector1, vector2, new MatrixBlock(), ctype, k);\n// matrix-vector compressed\n- MatrixBlock ret2 = (MatrixBlock) cmb\n- .chainMatrixMultOperations(vector1, vector2, new MatrixBlock(), ctype, k);\n+ MatrixBlock ret2 = cmb.chainMatrixMultOperations(vector1, vector2, new MatrixBlock(), ctype, k);\n// compare result with input\ndouble[][] d1 = DataConverter.convertToDoubleMatrix(ret1);\n@@ -255,11 +249,10 @@ public class ParCompressedMatrixTest extends CompressedTestBase {\nbreak;\n}\n// matrix-vector uncompressed\n- MatrixBlock ret1 = (MatrixBlock) mb.aggregateUnaryOperations(auop, new MatrixBlock(), 1000, null, true);\n+ MatrixBlock ret1 = mb.aggregateUnaryOperations(auop, new MatrixBlock(), 1000, null, true);\n// matrix-vector compressed\n- MatrixBlock ret2 = (MatrixBlock) cmb\n- .aggregateUnaryOperations(auop, new MatrixBlock(), 1000, null, true);\n+ MatrixBlock ret2 = cmb.aggregateUnaryOperations(auop, new MatrixBlock(), 1000, null, true);\n// compare result with input\ndouble[][] d1 = DataConverter.convertToDoubleMatrix(ret1);\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix various warnings (unnecessary casts/imports, hidden fields) |
49,689 | 09.03.2020 22:38:43 | -3,600 | 851506174f1e62feecfca36ab5a73c743a494df8 | [MINOR] Fix bug in function result reuse code.
bug: | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "@@ -218,6 +218,8 @@ public class LineageCache {\nString boundVarName = outputs.get(i);\nLineageItem boundLI = ec.getLineage().get(boundVarName);\nData boundValue = ec.getVariable(boundVarName);\n+ if (boundLI != null)\n+ boundLI.resetVisitStatus();\nif (boundLI == null\n|| !LineageCache.probe(li)\n|| LineageItemUtils.containsRandDataGen(new HashSet<>(Arrays.asList(liInputs)), boundLI)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"diff": "@@ -60,7 +60,6 @@ import org.tugraz.sysds.runtime.instructions.cp.ScalarObject;\nimport org.tugraz.sysds.runtime.instructions.cp.ScalarObjectFactory;\nimport org.tugraz.sysds.runtime.instructions.cp.VariableCPInstruction;\nimport org.tugraz.sysds.runtime.instructions.spark.SPInstruction.SPType;\n-import org.tugraz.sysds.runtime.instructions.cp.CPInstruction;\nimport org.tugraz.sysds.runtime.instructions.cp.CPInstruction.CPType;\nimport org.tugraz.sysds.runtime.util.HDFSTool;\n@@ -548,14 +547,16 @@ public class LineageItemUtils {\n}\npublic static boolean containsRandDataGen(HashSet<LineageItem> entries, LineageItem root) {\n- boolean isRand = false;\n- if (entries.contains(root))\n+ if (entries.contains(root) || root.isVisited())\nreturn false;\n+\n+ boolean isRand = false;\nif (isNonDeterministic(root))\nisRand |= true;\nif (!root.isLeaf())\nfor (LineageItem input : root.getInputs())\nisRand = isRand ? true : containsRandDataGen(entries, input);\n+ root.setVisited();\nreturn isRand;\n//TODO: unmark for caching in compile time\n}\n@@ -565,15 +566,25 @@ public class LineageItemUtils {\nreturn false;\nboolean isND = false;\n- CPInstruction CPins = (CPInstruction) InstructionParser.parseSingleInstruction(li.getData());\n- if (!(CPins instanceof DataGenCPInstruction))\n+ DataGenCPInstruction cprand = null;\n+ RandSPInstruction sprand = null;\n+ Instruction ins = InstructionParser.parseSingleInstruction(li.getData());\n+\n+ if (ins instanceof DataGenCPInstruction)\n+ cprand = (DataGenCPInstruction)ins;\n+ else if (ins instanceof RandSPInstruction)\n+ sprand = (RandSPInstruction)ins;\n+ else\nreturn false;\n- DataGenCPInstruction ins = (DataGenCPInstruction)CPins;\nswitch(li.getOpcode().toUpperCase())\n{\ncase \"RAND\":\n- if ((ins.getMinValue() != ins.getMaxValue()) || (ins.getSparsity() != 1))\n+ if (cprand != null)\n+ if ((cprand.getMinValue() != cprand.getMaxValue()) || (cprand.getSparsity() != 1))\n+ isND = true;\n+ if (sprand!= null)\n+ if ((sprand.getMinValue() != sprand.getMaxValue()) || (sprand.getSparsity() != 1))\nisND = true;\n//NOTE:It is hard to detect in runtime if rand was called with unspecified seed\n//as -1 is already replaced by computed seed. Solution is to unmark for caching in\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix bug in function result reuse code.
:bug: |
49,689 | 12.03.2020 14:32:57 | -3,600 | 66d0f549f3a27574210e0e2313e9f788b0cf7cdf | Extend Lineage support for codegen :art:
This patch supports few more hop types for HOP DAG to Lineage DAG conversion. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/Hop.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/Hop.java",
"diff": "@@ -1184,7 +1184,7 @@ public abstract class Hop implements ParseInfo\nHopsOpOp1LopsU.put(OpOp1.CAST_AS_FRAME, org.tugraz.sysds.lops.Unary.OperationTypes.CAST_AS_FRAME);\n}\n- protected static final HashMap<Hop.OpOp1, org.tugraz.sysds.lops.UnaryCP.OperationTypes> HopsOpOp1LopsUS;\n+ public static final HashMap<Hop.OpOp1, org.tugraz.sysds.lops.UnaryCP.OperationTypes> HopsOpOp1LopsUS;\nstatic {\nHopsOpOp1LopsUS = new HashMap<>();\nHopsOpOp1LopsUS.put(OpOp1.NOT, org.tugraz.sysds.lops.UnaryCP.OperationTypes.NOT);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/codegen/SpoofFusedOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/codegen/SpoofFusedOp.java",
"diff": "@@ -145,6 +145,10 @@ public class SpoofFusedOp extends MultiThreadedHop\nreturn \"spoof(\"+_class.getSimpleName()+\")\";\n}\n+ public String getClassName() {\n+ return _class.getName();\n+ }\n+\n@Override\nprotected DataCharacteristics inferOutputCharacteristics( MemoTable memo )\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/lops/UnaryCP.java",
"new_path": "src/main/java/org/tugraz/sysds/lops/UnaryCP.java",
"diff": "@@ -74,7 +74,11 @@ public class UnaryCP extends Lop\n}\nprivate String getOpCode() {\n- switch (operation) {\n+ return getOpCode(operation);\n+ }\n+\n+ public static String getOpCode(OperationTypes op) {\n+ switch (op) {\ncase NOT:\nreturn \"!\";\n@@ -168,7 +172,7 @@ public class UnaryCP extends Lop\nreturn \"softmax\";\ndefault:\n- throw new LopsException(this.printErrorLocation() + \"Unknown operation: \" + operation);\n+ throw new LopsException(\"Unknown operation: \" + op);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"diff": "@@ -25,7 +25,9 @@ import org.tugraz.sysds.runtime.instructions.spark.RandSPInstruction;\nimport org.tugraz.sysds.runtime.io.IOUtilFunctions;\nimport org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\nimport org.tugraz.sysds.runtime.lineage.LineageItem.LineageItemType;\n+import org.tugraz.sysds.common.Types.AggOp;\nimport org.tugraz.sysds.common.Types.DataType;\n+import org.tugraz.sysds.common.Types.Direction;\nimport org.tugraz.sysds.common.Types.OpOpDG;\nimport org.tugraz.sysds.common.Types.OpOpData;\nimport org.tugraz.sysds.common.Types.OpOpN;\n@@ -33,15 +35,22 @@ import org.tugraz.sysds.common.Types.ReOrgOp;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.conf.ConfigurationManager;\nimport org.tugraz.sysds.hops.AggBinaryOp;\n+import org.tugraz.sysds.hops.AggUnaryOp;\nimport org.tugraz.sysds.hops.BinaryOp;\nimport org.tugraz.sysds.hops.DataGenOp;\nimport org.tugraz.sysds.hops.DataOp;\nimport org.tugraz.sysds.hops.Hop;\n+import org.tugraz.sysds.hops.IndexingOp;\nimport org.tugraz.sysds.hops.LiteralOp;\nimport org.tugraz.sysds.hops.ReorgOp;\n+import org.tugraz.sysds.hops.TernaryOp;\n+import org.tugraz.sysds.hops.UnaryOp;\n+import org.tugraz.sysds.hops.codegen.SpoofFusedOp;\nimport org.tugraz.sysds.hops.rewrite.HopRewriteUtils;\nimport org.tugraz.sysds.lops.Binary;\nimport org.tugraz.sysds.lops.Lop;\n+import org.tugraz.sysds.lops.PartialAggregate;\n+import org.tugraz.sysds.lops.UnaryCP;\nimport org.tugraz.sysds.lops.compile.Dag;\nimport org.tugraz.sysds.parser.DataExpression;\nimport org.tugraz.sysds.parser.DataIdentifier;\n@@ -387,11 +396,29 @@ public class LineageItemUtils {\nif (root instanceof ReorgOp)\nli = new LineageItem(name, \"r'\", LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ else if (root instanceof UnaryOp) {\n+ String opcode = UnaryCP.getOpCode(Hop.HopsOpOp1LopsUS.get(((UnaryOp) root).getOp()));\n+ li = new LineageItem(name, opcode, LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ }\nelse if (root instanceof AggBinaryOp)\nli = new LineageItem(name, \"ba+*\", LIinputs.toArray(new LineageItem[LIinputs.size()]));\nelse if (root instanceof BinaryOp)\nli = new LineageItem(name, Binary.getOpcode(Hop.HopsOpOp2LopsB.get(((BinaryOp)root).getOp())),\nLIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ else if (root instanceof TernaryOp) {\n+ String opcode = ((TernaryOp) root).getOp().toString();\n+ li = new LineageItem(name, opcode, LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ }\n+ else if (root instanceof AggUnaryOp) {\n+ AggOp op = ((AggUnaryOp) root).getOp();\n+ Direction dir = ((AggUnaryOp) root).getDirection();\n+ String opcode = PartialAggregate.getOpcode(op, dir);\n+ li = new LineageItem(name, opcode, LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ }\n+ else if (root instanceof IndexingOp)\n+ li = new LineageItem(name, \"rightIndex\", LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ else if (root instanceof SpoofFusedOp)\n+ li = LineageCodegenItem.getCodegenLTrace(((SpoofFusedOp) root).getClassName());\nelse if (root instanceof LiteralOp) { //TODO: remove redundancy\nStringBuilder sb = new StringBuilder(root.getName());\n@@ -403,6 +430,8 @@ public class LineageItemUtils {\nsb.append(true); //isLiteral = true\nli = new LineageItem(root.getName(), sb.toString());\n}\n+ else\n+ throw new DMLRuntimeException(\"Unsupported hop: \"+root.getOpString());\n//TODO: include all the other hops\noperands.put(root.getHopID(), li);\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-232] Extend Lineage support for codegen :art:
- This patch supports few more hop types for HOP DAG to Lineage DAG conversion. |
49,738 | 16.03.2020 22:08:44 | -3,600 | 13f25073c23d3e089f5b1af16375b742f42bb6dd | [MINOR] Resolve warnings w/ strict compilation flags | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/AggregateBinaryFEDInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/fed/AggregateBinaryFEDInstruction.java",
"diff": "@@ -98,7 +98,7 @@ public class AggregateBinaryFEDInstruction extends BinaryFEDInstruction {\n* @param mo2 the other matrix object\n* @param out output matrix object\n*/\n- private void federatedAggregateBinary(MatrixObject mo1, MatrixObject mo2, MatrixObject out) {\n+ private static void federatedAggregateBinary(MatrixObject mo1, MatrixObject mo2, MatrixObject out) {\nboolean distributeCols = false;\n// if distributeCols = true we distribute cols of mo2 and do a MV multiplications, otherwise we\n// distribute rows of mo1 and do VM multiplications\n@@ -138,7 +138,7 @@ public class AggregateBinaryFEDInstruction extends BinaryFEDInstruction {\nout.release();\n}\n- private MatrixBlock combinePartialMMResults(ArrayList<Pair<FederatedRange, MatrixBlock>> results,\n+ private static MatrixBlock combinePartialMMResults(ArrayList<Pair<FederatedRange, MatrixBlock>> results,\nint rows, int cols) {\n// TODO support large blocks with > int size\nMatrixBlock resultBlock = new MatrixBlock(rows, cols, false);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RemoveUnnecessaryCTableTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RemoveUnnecessaryCTableTest.java",
"diff": "@@ -136,7 +136,7 @@ public class RemoveUnnecessaryCTableTest extends AutomatedTestBase\nOptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = true;\n- ArrayList<String> programArgsBuilder = new ArrayList<String>(\n+ ArrayList<String> programArgsBuilder = new ArrayList<>(\nArrays.asList(\"-explain\", \"-stats\", \"-args\" ));\n// Get Matrix Input\nif (A != null){\n@@ -155,7 +155,7 @@ public class RemoveUnnecessaryCTableTest extends AutomatedTestBase\nprogramArgsBuilder.add(output(config.getOutputFiles()[0]));\nString[] argsArray = new String[programArgsBuilder.size()];\n- argsArray = (String[]) programArgsBuilder.toArray(argsArray);\n+ argsArray = programArgsBuilder.toArray(argsArray);\nprogramArgs = argsArray;\n//run test\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RewriteEliminateRemoveEmptyTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/misc/RewriteEliminateRemoveEmptyTest.java",
"diff": "@@ -133,7 +133,7 @@ public class RewriteEliminateRemoveEmptyTest extends AutomatedTestBase\ntestRewriteEliminateRmEmpty(TEST_NAME6, true, A, AColSum, false);\n}\n- private double sum(double[][] A) {\n+ private static double sum(double[][] A) {\ndouble sum = 0;\nfor (double[] na : A) {\nfor (double n : na) {\n@@ -143,7 +143,7 @@ public class RewriteEliminateRemoveEmptyTest extends AutomatedTestBase\nreturn sum;\n}\n- private double[][] rowSum(double[][] A) {\n+ private static double[][] rowSum(double[][] A) {\ndouble[][] matrixRowSum = new double[rows][1];\nfor (int i = 0; i < rows; i++) {\nfor (int j = 0; j < cols; j++) {\n@@ -153,7 +153,7 @@ public class RewriteEliminateRemoveEmptyTest extends AutomatedTestBase\nreturn matrixRowSum;\n}\n- private double[][] colSum(double[][] A) {\n+ private static double[][] colSum(double[][] A) {\ndouble[][] matrixColSum = new double[1][cols];\nfor (int i = 0; i < rows; i++) {\nfor (int j = 0; j < cols; j++) {\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Resolve warnings w/ strict compilation flags |
49,706 | 17.03.2020 13:28:03 | -3,600 | 19845c4a373d9c8a9a41c7e46d0c06cd89093e39 | [MINOR] Fix R install in actions
Federated function Test not thread safe annotation | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/applicationTests.yml",
"new_path": ".github/workflows/applicationTests.yml",
"diff": "@@ -30,7 +30,9 @@ jobs:\nrun: mvn clean compile test-compile\n- name: install R\n- run: sudo apt -y install r-base\n+ run: |\n+ sudo apt-get update\n+ sudo apt-get -y install r-base\n- name: set R environment\nrun: |\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/workflows/functionsTests.yml",
"new_path": ".github/workflows/functionsTests.yml",
"diff": "@@ -65,7 +65,9 @@ jobs:\nrun: mvn clean compile test-compile\n- name: install R\n- run: sudo apt -y install r-base\n+ run: |\n+ sudo apt-get update\n+ sudo apt-get -y install r-base\n- name: set R environment\nrun: |\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/federated/FederatedMatrixScalarOperationsTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/federated/FederatedMatrixScalarOperationsTest.java",
"diff": "@@ -35,6 +35,7 @@ import static java.lang.Thread.sleep;\n@RunWith(Parameterized.class)\[email protected]\npublic class FederatedMatrixScalarOperationsTest extends AutomatedTestBase\n{\[email protected]\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/federated/FederatedMultiplyTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/federated/FederatedMultiplyTest.java",
"diff": "@@ -113,7 +113,7 @@ public class FederatedMultiplyTest extends AutomatedTestBase {\n// Run actual dml script with federated matrix\nfullDMLScriptName = HOME + TEST_NAME + \".dml\";\n- programArgs = new String[] {\"-explain\", \"-nvargs\",\n+ programArgs = new String[] {\"-nvargs\",\n\"X1=\" + TestUtils.federatedAddress(\"localhost\", port1, input(\"X1\")),\n\"X2=\" + TestUtils.federatedAddress(\"localhost\", port2, input(\"X2\")),\n\"Y1=\" + TestUtils.federatedAddress(\"localhost\", port1, input(\"Y1\")),\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix R install in actions
- Federated function Test not thread safe annotation |
49,738 | 17.03.2020 14:57:10 | -3,600 | fe0cbb6f8a86d64646f24a5c921c6db77158c48c | Fix rewrite ctable bypass (rewiring, direction) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/UnaryOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/UnaryOp.java",
"diff": "@@ -62,7 +62,7 @@ public class UnaryOp extends MultiThreadedHop\npublic UnaryOp(String l, DataType dt, ValueType vt, OpOp1 o, Hop inp) {\nsuper(l, dt, vt);\n- getInput().add(0, inp);\n+ getInput().add(inp);\ninp.getParent().add(this);\n_op = o;\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/RewriteAlgebraicSimplificationStatic.java",
"diff": "@@ -693,15 +693,16 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\n}\nprivate static Hop removeUnnecessaryCTable( Hop parent, Hop hi, int pos ) {\n- if ( HopRewriteUtils.isAggUnaryOp(hi, AggOp.SUM)\n+ if ( HopRewriteUtils.isAggUnaryOp(hi, AggOp.SUM, Direction.RowCol)\n&& HopRewriteUtils.isTernary(hi.getInput().get(0), OpOp3.CTABLE)\n&& HopRewriteUtils.isLiteralOfValue(hi.getInput().get(0).getInput().get(2), 1.0))\n{\nHop matrixInput = hi.getInput().get(0).getInput().get(0);\n- HopRewriteUtils.removeChildReference(hi, hi.getInput().get(0));\n- Hop newOpLength = new UnaryOp(\"length\", DataType.SCALAR, ValueType.INT64, OpOp1.LENGTH, matrixInput);\n+ OpOp1 opcode = matrixInput.getDim2() == 1 ? OpOp1.NROW : OpOp1.LENGTH;\n+ Hop newOpLength = new UnaryOp(\"tmp\", DataType.SCALAR, ValueType.INT64, opcode, matrixInput);\nHopRewriteUtils.replaceChildReference(parent, hi, newOpLength, pos);\n- hi = parent.getInput().get(pos);\n+ HopRewriteUtils.cleanupUnreferenced(hi, hi.getInput().get(0));\n+ hi = newOpLength;\n}\nreturn hi;\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-281] Fix rewrite ctable bypass (rewiring, direction) |
49,738 | 17.03.2020 15:14:39 | -3,600 | bf19244c909ae8354bc8b3da0985eaf448aa5f0c | [MINOR] Fix qpick instruction (common layout for fed conversion) | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/QuantilePickCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/QuantilePickCPInstruction.java",
"diff": "@@ -65,7 +65,7 @@ public class QuantilePickCPInstruction extends BinaryCPInstruction {\nCPOperand out = new CPOperand(parts[2]);\nOperationTypes ptype = OperationTypes.valueOf(parts[3]);\nboolean inmem = Boolean.parseBoolean(parts[4]);\n- return new QuantilePickCPInstruction(null, in1, out, ptype, inmem, opcode, str);\n+ return new QuantilePickCPInstruction(null, in1, new CPOperand(), out, ptype, inmem, opcode, str);\n}\nelse if( parts.length == 6 ) {\nCPOperand in1 = new CPOperand(parts[1]);\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix qpick instruction (common layout for fed conversion) |
49,738 | 17.03.2020 21:11:08 | -3,600 | 3f3f4973d825d49464b05ca5d3160ebb2e8b542c | [MINOR] Increased error threshold for GLM, binomial two-column.cauchit | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/applications/GLMTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/applications/GLMTest.java",
"diff": "@@ -340,7 +340,8 @@ public class GLMTest extends AutomatedTestBase\nHashMap<CellIndex, Double> wR = readRMatrixFromFS (\"betas_R\");\ndouble eps = 0.000001;\n- if( distParam==0 && linkType==1 ) // Gaussian.log\n+ if( (distParam==0 && linkType==1) // Gaussian.log\n+ || (distParam==1 && linkType==5) )\n{\n//NOTE MB: Gaussian.log was the only test failing when we introduced multi-threaded\n//matrix multplications (mmchain). After discussions with Sasha, we decided to change the eps\n@@ -350,7 +351,9 @@ public class GLMTest extends AutomatedTestBase\n//of rows if these rewrites are enabled. Users can turn off rewrites if high accuracy is required.\n//However, in the future we might also consider to use Kahan plus for aggregations in matrix mult\n//(at least for the final aggregation of partial results from individual threads).\n- eps = 0.000002; //2x the error threshold\n+\n+ //NOTE MB: similar issues occurred with other tests when moving to github action tests\n+ eps *= 2;\n}\nTestUtils.compareMatrices (wR, wSYSTEMDS, eps * max_abs_beta, \"wR\", \"wSYSTEMDS\");\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Increased error threshold for GLM, binomial two-column.cauchit |
49,738 | 17.03.2020 21:24:49 | -3,600 | cde2196890a95148ad7c3d556b14f2127ce335ba | [MINOR] Remove R plotrix test dependency (for std error) | [
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/applications/descriptivestats/Scale.R",
"new_path": "src/test/scripts/applications/descriptivestats/Scale.R",
"diff": "args <- commandArgs(TRUE)\noptions(digits=22)\n-library(\"plotrix\");\nlibrary(\"psych\")\nlibrary(\"moments\")\n-#library(\"batch\")\nlibrary(\"Matrix\")\nV = readMM(paste(args[1], \"vector.mtx\", sep=\"\"))\n@@ -46,7 +44,7 @@ var = var(V[,1])\nstd_dev = sd(V[,1], na.rm = FALSE)\n# standard errors of mean\n-SE = std.error(V[,1], na.rm)\n+SE = sd(V[,1])/sqrt(sum(!is.na(V[,1])))\n# coefficients of variation\ncv = std_dev/mu\n@@ -118,5 +116,3 @@ write(iqm, paste(args[2], \"iqm\", sep=\"\"));\nwriteMM(as(t(out_minus),\"CsparseMatrix\"), paste(args[2], \"out_minus\", sep=\"\"), format=\"text\");\nwriteMM(as(t(out_plus),\"CsparseMatrix\"), paste(args[2], \"out_plus\", sep=\"\"), format=\"text\");\nwriteMM(as(t(Q),\"CsparseMatrix\"), paste(args[2], \"quantile\", sep=\"\"), format=\"text\");\n-\n-\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/applications/descriptivestats/WeightedScaleTest.R",
"new_path": "src/test/scripts/applications/descriptivestats/WeightedScaleTest.R",
"diff": "args <- commandArgs(TRUE)\noptions(digits=22)\n-library(\"plotrix\");\nlibrary(\"psych\")\nlibrary(\"moments\")\n-#library(\"batch\")\nlibrary(\"Matrix\")\n# Usage: R --vanilla -args Xfile X < DescriptiveStatistics.R\n@@ -59,7 +57,7 @@ var = var(V)\nstd_dev = sd(V, na.rm = FALSE)\n# standard errors of mean\n-SE = std.error(V, na.rm)\n+SE = sd(V)/sqrt(sum(!is.na(V)))\n# coefficients of variation\ncv = std_dev/mu\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/installDependencies.R",
"new_path": "src/test/scripts/installDependencies.R",
"diff": "@@ -42,7 +42,6 @@ custom_install(\"moments\");\ncustom_install(\"boot\");\ncustom_install(\"matrixStats\");\n-# custom_install(\"plotrix\");\n# custom_install(\"batch\");\n# custom_install(\"outliers\");\n# custom_install(\"caret\");\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Remove R plotrix test dependency (for std error) |
49,706 | 17.03.2020 21:30:54 | -3,600 | 22cfef4a78b3812e28807173e7367dc509bd4140 | [MINOR] Revert uncommented workflow action | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/applicationTests.yml",
"new_path": ".github/workflows/applicationTests.yml",
"diff": "-# name: Application Test\n-\n-# on:\n-# push:\n-# branches:\n-# - master\n-# pull_request:\n-# branches:\n-# - master\n-\n-# jobs:\n-# applicationsTests:\n-# runs-on: ${{ matrix.os }}\n-# strategy:\n-# fail-fast: false\n-# matrix:\n-# tests: [A,B,C,G,H,I,L,M,N,O,P,S,U,W]\n-# os: [ubuntu-latest]\n-# java: [ 1.8 ]\n-# name: Ap Test ${{ matrix.tests }}\n-# steps:\n-# - uses: actions/checkout@v2\n-\n-# - name: Setup Java\n-# uses: actions/setup-java@v1\n-# with:\n-# java-version: ${{ matrix.java }}\n-\n-# - name: clean, compile & test-compile\n-# run: mvn clean compile test-compile\n-\n-# - name: install R\n-# run: |\n-# sudo apt-get update\n-# sudo apt-get -y install r-base\n-\n-# - name: set R environment\n-# run: |\n-# echo \"R_LIBS=/tmp/Rpackages/\" > ~/.Renviron\n-# mkdir /tmp/Rpackages\n-\n-# - name: install R Dependencies\n-# # TODO: Find out how to make if statement correctly: suggestion but not working: if: ${{ matrix.tests }} == P\n-# run: Rscript ./src/test/scripts/installDependencies.R \"/tmp/Rpackages/\"\n-\n-# - name: Run all tests starting with \"${{ matrix.tests }}\"\n-# run: mvn surefire:test -DskipTests=false -Dtest=org.tugraz.sysds.test.applications.${{ matrix.tests }}**\n+name: Application Test\n+\n+on:\n+ push:\n+ branches:\n+ - master\n+ pull_request:\n+ branches:\n+ - master\n+\n+jobs:\n+ applicationsTests:\n+ runs-on: ${{ matrix.os }}\n+ strategy:\n+ fail-fast: false\n+ matrix:\n+ tests: [A,B,C,G,H,I,L,M,N,O,P,S,U,W]\n+ os: [ubuntu-latest]\n+ java: [ 1.8 ]\n+ name: Ap Test ${{ matrix.tests }}\n+ steps:\n+ - uses: actions/checkout@v2\n+\n+ - name: Setup Java\n+ uses: actions/setup-java@v1\n+ with:\n+ java-version: ${{ matrix.java }}\n+\n+ - name: clean, compile & test-compile\n+ run: mvn clean compile test-compile\n+\n+ - name: install R\n+ run: |\n+ sudo apt-get update\n+ sudo apt-get -y install r-base\n+\n+ - name: set R environment\n+ run: |\n+ echo \"R_LIBS=/tmp/Rpackages/\" > ~/.Renviron\n+ mkdir /tmp/Rpackages\n+\n+ - name: install R Dependencies\n+ # TODO: Find out how to make if statement correctly: suggestion but not working: if: ${{ matrix.tests }} == P\n+ run: Rscript ./src/test/scripts/installDependencies.R \"/tmp/Rpackages/\"\n+\n+ - name: Run all tests starting with \"${{ matrix.tests }}\"\n+ run: mvn surefire:test -DskipTests=false -Dtest=org.tugraz.sysds.test.applications.${{ matrix.tests }}**\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/workflows/functionsTests.yml",
"new_path": ".github/workflows/functionsTests.yml",
"diff": "-# name: Function Test\n+name: Function Test\n-# on:\n-# push:\n-# branches:\n-# - master\n-# pull_request:\n-# branches:\n-# - master\n+on:\n+ push:\n+ branches:\n+ - master\n+ pull_request:\n+ branches:\n+ - master\n-# jobs:\n-# applicationsTests:\n-# runs-on: ${{ matrix.os }}\n-# strategy:\n-# fail-fast: false\n-# matrix:\n-# tests: [\n-# aggregate,\n-# append,\n-# binary.matrix,\n-# binary.matrix_full_cellwise,\n-# binary.matrix_full_other,\n-# binary.scalar,\n-# binary.tensor,\n-# blocks,\n-# builtin,\n-# caching,\n-# codegen,\n-# codegenalg,\n-# data,\n-# dnn,\n-# federated,\n-# frame,\n-# indexing,\n-# io,\n-# jmlc,\n-# lineage,\n-# misc,\n-# mlcontext,\n-# nary,\n-# paramserv,\n-# parfor,\n-# quaternary,\n-# recompile,\n-# reorg,\n-# ternary,\n-# transform,\n-# unary.matrix,\n-# unary.scalar,\n-# updateinplace,\n-# vect\n-# ]\n-# os: [ubuntu-latest]\n-# java: [ 1.8 ]\n-# name: Func Test ${{ matrix.tests }}\n-# steps:\n-# - uses: actions/checkout@v2\n+jobs:\n+ applicationsTests:\n+ runs-on: ${{ matrix.os }}\n+ strategy:\n+ fail-fast: false\n+ matrix:\n+ tests: [\n+ aggregate,\n+ append,\n+ binary.matrix,\n+ binary.matrix_full_cellwise,\n+ binary.matrix_full_other,\n+ binary.scalar,\n+ binary.tensor,\n+ blocks,\n+ builtin,\n+ caching,\n+ codegen,\n+ codegenalg,\n+ data,\n+ dnn,\n+ federated,\n+ frame,\n+ indexing,\n+ io,\n+ jmlc,\n+ lineage,\n+ misc,\n+ mlcontext,\n+ nary,\n+ paramserv,\n+ parfor,\n+ quaternary,\n+ recompile,\n+ reorg,\n+ ternary,\n+ transform,\n+ unary.matrix,\n+ unary.scalar,\n+ updateinplace,\n+ vect\n+ ]\n+ os: [ubuntu-latest]\n+ java: [ 1.8 ]\n+ name: Func Test ${{ matrix.tests }}\n+ steps:\n+ - uses: actions/checkout@v2\n-# - name: Setup Java\n-# uses: actions/setup-java@v1\n-# with:\n-# java-version: ${{ matrix.java }}\n+ - name: Setup Java\n+ uses: actions/setup-java@v1\n+ with:\n+ java-version: ${{ matrix.java }}\n-# - name: clean, compile & test-compile\n-# run: mvn clean compile test-compile\n+ - name: clean, compile & test-compile\n+ run: mvn clean compile test-compile\n-# - name: install R\n-# run: |\n-# sudo apt-get update\n-# sudo apt-get -y install r-base\n+ - name: install R\n+ run: |\n+ sudo apt-get update\n+ sudo apt-get -y install r-base\n-# - name: set R environment\n-# run: |\n-# echo \"R_LIBS=/tmp/Rpackages/\" > ~/.Renviron\n-# mkdir /tmp/Rpackages\n+ - name: set R environment\n+ run: |\n+ echo \"R_LIBS=/tmp/Rpackages/\" > ~/.Renviron\n+ mkdir /tmp/Rpackages\n-# - name: install R Dependencies\n-# # TODO: Find out how to make if statement correctly: suggestion but not working: if: ${{ matrix.tests }} == P\n-# run: Rscript ./src/test/scripts/installDependencies.R \"/tmp/Rpackages/\"\n+ - name: install R Dependencies\n+ # TODO: Find out how to make if statement correctly: suggestion but not working: if: ${{ matrix.tests }} == P\n+ run: Rscript ./src/test/scripts/installDependencies.R \"/tmp/Rpackages/\"\n-# - name: Run all tests starting with \"${{ matrix.tests }}\"\n-# run: mvn surefire:test -DskipTests=false -Dtest=org.tugraz.sysds.test.functions.${{ matrix.tests }}.**\n+ - name: Run all tests starting with \"${{ matrix.tests }}\"\n+ run: mvn surefire:test -DskipTests=false -Dtest=org.tugraz.sysds.test.functions.${{ matrix.tests }}.**\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Revert uncommented workflow action |
49,738 | 17.03.2020 22:26:22 | -3,600 | 474cf08253b30ab52f99cb33cb4533c82cfab06c | [MINOR] Fix additional tests (R packages, GLM eps parameter)
* GLM eps increase for right parameterized test
* Remove partially unavailable R package dependencies and fix install
dependency script (typos r packages) | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/applications/GLMTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/applications/GLMTest.java",
"diff": "@@ -340,9 +340,7 @@ public class GLMTest extends AutomatedTestBase\nHashMap<CellIndex, Double> wR = readRMatrixFromFS (\"betas_R\");\ndouble eps = 0.000001;\n- if( (distParam==0 && linkType==1) // Gaussian.log\n- || (distParam==1 && linkType==5) )\n- {\n+ if( (distParam==0 && linkType==1) ) { // Gaussian.*\n//NOTE MB: Gaussian.log was the only test failing when we introduced multi-threaded\n//matrix multplications (mmchain). After discussions with Sasha, we decided to change the eps\n//because accuracy is anyway affected by various rewrites like binary to unary (-1*x->-x),\n@@ -353,7 +351,7 @@ public class GLMTest extends AutomatedTestBase\n//(at least for the final aggregation of partial results from individual threads).\n//NOTE MB: similar issues occurred with other tests when moving to github action tests\n- eps *= 2;\n+ eps *= (linkPower==-1) ? 4 : 2; //Gaussian.inverse vs Gaussian.*;\n}\nTestUtils.compareMatrices (wR, wSYSTEMDS, eps * max_abs_beta, \"wR\", \"wSYSTEMDS\");\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/applications/descriptivestats/Categorical.R",
"new_path": "src/test/scripts/applications/descriptivestats/Categorical.R",
"diff": "args <- commandArgs(TRUE)\noptions(digits=22)\n-#library(\"batch\")\nlibrary(\"Matrix\")\nV = readMM(paste(args[1], \"vector.mtx\", sep=\"\"))\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/applications/descriptivestats/WeightedCategoricalTest.R",
"new_path": "src/test/scripts/applications/descriptivestats/WeightedCategoricalTest.R",
"diff": "args <- commandArgs(TRUE)\noptions(digits=22)\n-#library(\"batch\")\nlibrary(\"Matrix\")\n# Usage: R --vanilla -args Xfile X < DescriptiveStatistics.R\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/applications/hits/HITS.R",
"new_path": "src/test/scripts/applications/hits/HITS.R",
"diff": "#\n#-------------------------------------------------------------\n-#library(\"batch\")\n# Usage: R --vanilla --args graphfile G tol 1e-8 maxiter 100 < HITS.R\n#parseCommandArgs()\n# JUnit test class: dml.test.integration.applications.HITSTest.java\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/applications/linearLogReg/LinearLogReg.R",
"new_path": "src/test/scripts/applications/linearLogReg/LinearLogReg.R",
"diff": "args <- commandArgs(TRUE)\nlibrary(\"Matrix\")\n-#library(\"batch\")\n# Usage: /home/vikas/R-2.10.1/bin/R --vanilla --args Xfile X yfile y Cval 2 tol 0.01 maxiter 100 < linearLogReg.r\n# Solves Linear Logistic Regression using Trust Region methods.\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/installDependencies.R",
"new_path": "src/test/scripts/installDependencies.R",
"diff": "@@ -41,11 +41,9 @@ custom_install(\"psych\");\ncustom_install(\"moments\");\ncustom_install(\"boot\");\ncustom_install(\"matrixStats\");\n-\n-# custom_install(\"batch\");\n-# custom_install(\"outliers\");\n-# custom_install(\"caret\");\n-# custom_install(\"Sigmoid\");\n-# custom_install(\"DescTools\");\n+custom_install(\"outliers\");\n+custom_install(\"caret\");\n+custom_install(\"sigmoid\");\n+custom_install(\"DescTools\");\nprint(\"Done\")\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix additional tests (R packages, GLM eps parameter)
* GLM eps increase for right parameterized test
* Remove partially unavailable R package dependencies and fix install
dependency script (typos r packages) |
49,738 | 17.03.2020 23:39:46 | -3,600 | 782d58a95a20263e039618a7b989a6212be9e242 | [MINOR] Fix additional tests (R packages, case-sensitive names), part II | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/compress/utils/Py4jConverterUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/compress/utils/Py4jConverterUtils.java",
"diff": "@@ -94,6 +94,8 @@ public class Py4jConverterUtils {\nfor (int i = 0; i < rlen * clen; i++)\ndenseBlock[i] = buf.getDouble();\nbreak;\n+ default:\n+ throw new DMLRuntimeException(\"Unsupported value type: \"+valueType.name());\n}\nmb.init(denseBlock, rlen, clen);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinMultiLogRegTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinMultiLogRegTest.java",
"diff": "@@ -27,7 +27,7 @@ import org.tugraz.sysds.test.TestUtils;\npublic class BuiltinMultiLogRegTest extends AutomatedTestBase {\n- private final static String TEST_NAME = \"multiLogReg\";\n+ private final static String TEST_NAME = \"MultiLogReg\";\nprivate final static String TEST_DIR = \"functions/builtin/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + BuiltinMultiLogRegTest.class.getSimpleName() + \"/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/builtin/multipleBuiltins.R",
"new_path": "src/test/scripts/functions/builtin/multipleBuiltins.R",
"diff": "@@ -20,7 +20,6 @@ args<-commandArgs(TRUE)\noptions(digits=22)\nlibrary(\"Matrix\")\nlibrary(\"outliers\")\n-library(\"stats\")\nlibrary(\"DescTools\")\nX = as.matrix(readMM(paste(args[1], \"A.mtx\", sep=\"\")))\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/builtin/winsorize.R",
"new_path": "src/test/scripts/functions/builtin/winsorize.R",
"diff": "args<-commandArgs(TRUE)\noptions(digits=22)\nlibrary(\"Matrix\")\n-library(\"stats\")\nlibrary(\"DescTools\")\nX = as.matrix(readMM(paste(args[1], \"A.mtx\", sep=\"\")))\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix additional tests (R packages, case-sensitive names), part II |
49,693 | 10.07.2019 20:00:25 | -7,200 | 571b12a2f66273366c12998951592d9fc61d8b58 | Follow-up to improve BLAS loading and building JNI helpers with CMake | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -90,3 +90,11 @@ Gemfile.lock\n**/metastore_db\nderby.log\n/systemds/\n+\n+# native cpp code build artifacts\n+src/main/cpp/build\n+src/main/cpp/bin\n+src/main/cpp/lib\n+\n+# legacy dml\n+*.dmlt\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -192,7 +192,7 @@ SYSTEMDS-230 Lineage Integration\n* 236 Extended multi-level lineage cache for statement blocks OK\nSYSTEMDS-240 GPU Backend Improvements\n- * 241 Dense GPU cumulative aggregates\n+ * 241 Dense GPU cumulative aggregates OK\nSYSTEMDS-250 Extended Slice Finding\n* 251 Alternative slice enumeration approach OK\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/CMakeLists.txt",
"new_path": "src/main/cpp/CMakeLists.txt",
"diff": "#\n#-------------------------------------------------------------\n-cmake_minimum_required(VERSION 2.8)\n-\n+cmake_minimum_required(VERSION 3.8)\n+cmake_policy(SET CMP0074 NEW) # make use of <package>_ROOT variable\nproject (systemds)\n# All custom find modules\n@@ -28,9 +28,13 @@ option(USE_OPEN_BLAS \"Whether to use OpenBLAS (Defaults to compiling with Intel\noption(USE_INTEL_MKL \"Whether to use Intel MKL (Defaults to compiling with Intel MKL)\" OFF)\n# Build a shared libraray\n-add_library(systemds SHARED libmatrixdnn.cpp libmatrixmult.cpp systemds.cpp)\n-set_target_properties(systemds PROPERTIES MACOSX_RPATH 1)\n+set(HEADER_FILES libmatrixdnn.h libmatrixmult.h systemds.h)\n+set(SOURCE_FILES libmatrixdnn.cpp libmatrixmult.cpp systemds.cpp)\n+\n+# Build a shared libraray\n+add_library(systemds SHARED ${SOURCE_FILES} ${HEADER_FILES})\n+set_target_properties(systemds PROPERTIES MACOSX_RPATH 1)\nset(MATH_LIBRARIES \"\")\n# sets the installation path to src/main/cpp/lib\n@@ -45,17 +49,16 @@ if (USE_OPEN_BLAS)\nset_target_properties(systemds PROPERTIES OUTPUT_NAME \"systemds_openblas-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}\")\ninclude_directories(${OpenBLAS_INCLUDE_DIR})\nset(MATH_LIBRARIES \"${OpenBLAS_LIB}\")\n+ add_definitions(-DUSE_OPEN_BLAS)\nelseif(USE_INTEL_MKL)\nfind_package(MKL REQUIRED)\n# sets the name of the output to include the os and the architecture\nset_target_properties(systemds PROPERTIES OUTPUT_NAME \"systemds_mkl-${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}\")\ninclude_directories(${MKL_INCLUDE_DIR})\nset(MATH_LIBRARIES \"${MKL_LIBRARIES}\")\n+ add_definitions(-DUSE_INTEL_MKL)\nendif()\n-# Option written to a config.h file\n-configure_file(${CMAKE_SOURCE_DIR}/config.h.cmake ${CMAKE_BINARY_DIR}/config.h)\n-\n# Include directories. (added for Linux & Darwin, fix later for windows)\n# include paths can be spurious\ninclude_directories($ENV{JAVA_HOME}/include/)\n@@ -63,10 +66,6 @@ include_directories($ENV{JAVA_HOME}/include/darwin)\ninclude_directories($ENV{JAVA_HOME}/include/linux)\ninclude_directories($ENV{JAVA_HOME}/include/win32)\n-# Include the binary dir which contains \"config.h\"\n-include_directories(${CMAKE_BINARY_DIR})\n-\n-\n# Setting CXX compiler flags\nif (USE_OPEN_BLAS)\n# OpenMP is required\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/build.sh",
"new_path": "src/main/cpp/build.sh",
"diff": "#!/bin/bash\n#-------------------------------------------------------------\n#\n-# Copyright 2019 Graz University of Technology\n+# Copyright 2020 Graz University of Technology\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n@@ -32,15 +32,27 @@ intel_mkl=\"libmkl_rt.so\"\n# GCC __float128 shared support library: libquadmath.so.0\nopenblas=\"libopenblas.so\\|libgfortran.so\\|libquadmath.so\"\n+\n+if ! [ -x \"$(command -v cmake)\" ]; then\n+ echo 'Error: cmake is not installed.' >&2\n+ exit 1\n+fi\n+\n+if ! [ -x \"$(command -v patchelf)\" ]; then\n+ echo 'Error: patchelf is not installed.' >&2\n+ exit 1\n+fi\n+\n# configure and compile INTEL MKL\n-mkdir INTEL && cd INTEL\n-cmake -DUSE_INTEL_MKL=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DCMAKE_CXX_FLAGS=\"-DUSE_GNU_THREADING -m64\" ..\n-make install && cd .. && rm -R INTEL\n+cmake . -B INTEL -DUSE_INTEL_MKL=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DCMAKE_CXX_FLAGS=\"-DUSE_GNU_THREADING -m64\"\n+cmake --build INTEL --target install --config Release\n+rm -R INTEL\n# configure and compile OPENBLAS\n-mkdir OPENBLAS && cd OPENBLAS\n-cmake -DUSE_OPEN_BLAS=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DCMAKE_CXX_FLAGS=\"-m64\" ..\n-make install && cd .. && rm -R OPENBLAS\n+cmake . -B OPENBLAS -DUSE_OPEN_BLAS=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DCMAKE_CXX_FLAGS=\"-m64\"\n+cmake --build OPENBLAS --target install --config Release\n+patchelf --add-needed libopenblas.so.0 libsystemds_openblas-Linux-x86_64.so\n+rm -R OPENBLAS\n# check dependencies linux x86_64\necho \"-----------------------------------------------------------------------\"\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/cmake/FindMKL.cmake",
"new_path": "src/main/cpp/cmake/FindMKL.cmake",
"diff": "@@ -38,7 +38,7 @@ option(MKL_MULTI_THREADED \"Use multi-threading\" ON)\n# ---[ Root folders\nset(INTEL_ROOT \"/opt/intel\" CACHE PATH \"Folder contains intel libs\")\n-find_path(MKL_ROOT include/mkl.h PATHS $ENV{MKLROOT} ${INTEL_ROOT}/mkl\n+find_path(MKL_ROOT include/mkl.h PATHS $ENV{MKLROOT} $ENV{MKL_ROOT} ${INTEL_ROOT}/mkl\nDOC \"Folder contains MKL\")\n# ---[ Find include dir\n@@ -122,6 +122,7 @@ include(FindPackageHandleStandardArgs)\nfind_package_handle_standard_args(MKL DEFAULT_MSG ${__looked_for})\nif(MKL_FOUND)\n+ set(MKL_LIBRARIES \\\"${MKL_LIBRARIES}\\\")\nmessage(STATUS \"Found MKL (include: ${MKL_INCLUDE_DIR}, lib: ${MKL_LIBRARIES}\")\nendif()\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/cmake/FindOpenBLAS.cmake",
"new_path": "src/main/cpp/cmake/FindOpenBLAS.cmake",
"diff": "@@ -26,6 +26,7 @@ SET(Open_BLAS_INCLUDE_SEARCH_PATHS\n/opt/OpenBLAS/include\n$ENV{OpenBLAS_HOME}\n$ENV{OpenBLAS_HOME}/include\n+ $ENV{OpenBLAS_HOME}/include/openblas\n)\nSET(Open_BLAS_LIB_SEARCH_PATHS\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/lib/libsystemds_mkl-Linux-x86_64.so",
"new_path": "src/main/cpp/lib/libsystemds_mkl-Linux-x86_64.so",
"diff": "Binary files a/src/main/cpp/lib/libsystemds_mkl-Linux-x86_64.so and b/src/main/cpp/lib/libsystemds_mkl-Linux-x86_64.so differ\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/lib/libsystemds_openblas-Linux-x86_64.so",
"new_path": "src/main/cpp/lib/libsystemds_openblas-Linux-x86_64.so",
"diff": "Binary files a/src/main/cpp/lib/libsystemds_openblas-Linux-x86_64.so and b/src/main/cpp/lib/libsystemds_openblas-Linux-x86_64.so differ\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/lib/systemds_mkl-Windows-AMD64.dll",
"new_path": "src/main/cpp/lib/systemds_mkl-Windows-AMD64.dll",
"diff": "Binary files a/src/main/cpp/lib/systemds_mkl-Windows-AMD64.dll and b/src/main/cpp/lib/systemds_mkl-Windows-AMD64.dll differ\n"
},
{
"change_type": "ADD",
"old_path": "src/main/cpp/lib/systemds_openblas-Windows-AMD64.dll",
"new_path": "src/main/cpp/lib/systemds_openblas-Windows-AMD64.dll",
"diff": "Binary files /dev/null and b/src/main/cpp/lib/systemds_openblas-Windows-AMD64.dll differ\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/libmatrixdnn.cpp",
"new_path": "src/main/cpp/libmatrixdnn.cpp",
"diff": "* under the License.\n*/\n-#include \"config.h\"\n#include \"libmatrixmult.h\"\n#include \"libmatrixdnn.h\"\n#include <cstdlib>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/libmatrixmult.cpp",
"new_path": "src/main/cpp/libmatrixmult.cpp",
"diff": "*/\n#include \"libmatrixmult.h\"\n-#include \"config.h\"\n#include \"omp.h\"\n#include <cmath>\n#include <cstdlib>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/cpp/systemds.cpp",
"new_path": "src/main/cpp/systemds.cpp",
"diff": "* under the License.\n*/\n-#include \"config.h\"\n#include \"systemds.h\"\n#include \"libmatrixmult.h\"\n#include \"libmatrixdnn.h\"\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/LibMatrixNative.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/LibMatrixNative.java",
"diff": "@@ -130,7 +130,7 @@ public class LibMatrixNative\nif( NativeHelper.tsmm(m1.getDenseBlockValues(),\nret.getDenseBlockValues(), m1.rlen, m1.clen, leftTrans, k) )\n{\n- LOG.info(\"Using native TSMM()\");\n+ // ToDo: add native tsmm() to stats\nlong nnz = (ret.clen==1) ? ret.recomputeNonZeros() :\nLibMatrixMult.copyUpperToLowerTriangle(ret);\nret.setNonZeros(nnz);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/utils/NativeHelper.java",
"new_path": "src/main/java/org/tugraz/sysds/utils/NativeHelper.java",
"diff": "/*\n+ * Modifications Copyright 2020 Graz University of Technology\n+ *\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n* distributed with this work for additional information\n@@ -23,6 +25,8 @@ import java.io.IOException;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n+import org.apache.log4j.Level;\n+import org.apache.log4j.Logger;\nimport org.tugraz.sysds.conf.ConfigurationManager;\nimport org.tugraz.sysds.conf.DMLConfig;\nimport org.tugraz.sysds.hops.OptimizerUtils;\n@@ -45,7 +49,7 @@ import org.apache.commons.lang.SystemUtils;\n*/\npublic class NativeHelper {\n- public static enum NativeBlasState {\n+ public enum NativeBlasState {\nNOT_ATTEMPTED_LOADING_NATIVE_BLAS,\nSUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE,\nSUCCESSFULLY_LOADED_NATIVE_BLAS_AND_NOT_IN_USE,\n@@ -54,12 +58,22 @@ public class NativeHelper {\npublic static NativeBlasState CURRENT_NATIVE_BLAS_STATE = NativeBlasState.NOT_ATTEMPTED_LOADING_NATIVE_BLAS;\nprivate static String blasType;\n- private static final Log LOG = LogFactory.getLog(NativeHelper.class.getName());\n// Useful for deciding whether to use native BLAS in parfor environment.\nprivate static int maxNumThreads = -1;\nprivate static boolean setMaxNumThreads = false;\n+ // local flag for debug output\n+ private static final boolean LTRACE = false;\n+ private static final Log LOG = LogFactory.getLog(NativeHelper.class.getName());\n+\n+ static {\n+ // for internal debugging only\n+ if( LTRACE ) {\n+ Logger.getLogger(NativeHelper.class.getName()).setLevel(Level.TRACE);\n+ }\n+ }\n+\n/**\n* Called by Statistics to print the loaded BLAS.\n*\n@@ -77,16 +91,22 @@ public class NativeHelper {\npublic static boolean isNativeLibraryLoaded() {\nif(!isBLASLoaded()) {\nDMLConfig dmlConfig = ConfigurationManager.getDMLConfig();\n- String userSpecifiedBLAS = (dmlConfig == null) ? \"auto\" : dmlConfig.getTextValue(DMLConfig.NATIVE_BLAS).trim().toLowerCase();\n+ String userSpecifiedBLAS = (dmlConfig == null) ? \"auto\" : dmlConfig.getTextValue(DMLConfig.NATIVE_BLAS)\n+ .trim().toLowerCase();\nString customLibPath = (dmlConfig == null) ? \"none\" : dmlConfig.getTextValue(DMLConfig.NATIVE_BLAS_DIR).trim();\nperformLoading(customLibPath, userSpecifiedBLAS);\n}\n+\nif(maxNumThreads == -1)\nmaxNumThreads = OptimizerUtils.getConstrainedNumThreads(-1);\n- if(CURRENT_NATIVE_BLAS_STATE == NativeBlasState.SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE && !setMaxNumThreads && maxNumThreads != -1) {\n- // This method helps us decide whether to use GetPrimitiveArrayCritical or GetDoubleArrayElements in JNI as each has different tradeoffs.\n- // In current implementation, we always use GetPrimitiveArrayCritical as it has proven to be fastest.\n- // We can revisit this decision later and hence I would not recommend removing this method.\n+\n+ if(CURRENT_NATIVE_BLAS_STATE == NativeBlasState.SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE && !setMaxNumThreads\n+ && maxNumThreads != -1) {\n+ /* This method helps us decide whether to use GetPrimitiveArrayCritical or GetDoubleArrayElements in JNI as\n+ * each has different tradeoffs. In current implementation, we always use GetPrimitiveArrayCritical as it\n+ * has proven to be fastest.\n+ * We can revisit this decision later and hence I would not recommend removing this method.\n+ * */\nsetMaxNumThreads(maxNumThreads);\nsetMaxNumThreads = true;\n}\n@@ -101,7 +121,8 @@ public class NativeHelper {\n*/\npublic static void initialize(String customLibPath, String userSpecifiedBLAS) {\nif(isBLASLoaded() && isSupportedBLAS(userSpecifiedBLAS) && !blasType.equalsIgnoreCase(userSpecifiedBLAS)) {\n- throw new DMLRuntimeException(\"Cannot replace previously loaded blas \\\"\" + blasType + \"\\\" with \\\"\" + userSpecifiedBLAS + \"\\\".\");\n+ throw new DMLRuntimeException(\"Cannot replace previously loaded blas \\\"\" + blasType + \"\\\" with \\\"\" +\n+ userSpecifiedBLAS + \"\\\".\");\n}\nelse if(isBLASLoaded() && userSpecifiedBLAS.equalsIgnoreCase(\"none\")) {\nCURRENT_NATIVE_BLAS_STATE = NativeBlasState.SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_NOT_IN_USE;\n@@ -141,7 +162,8 @@ public class NativeHelper {\n/**\n* Check if native BLAS libraries have been successfully loaded\n- * @return true if CURRENT_NATIVE_BLAS_STATE is SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE or SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_NOT_IN_USE\n+ * @return true if CURRENT_NATIVE_BLAS_STATE is SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE or\n+ * SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_NOT_IN_USE\n*/\nprivate static boolean isBLASLoaded() {\nreturn CURRENT_NATIVE_BLAS_STATE == NativeBlasState.SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE ||\n@@ -163,9 +185,8 @@ public class NativeHelper {\n// Performing loading in a method instead of a static block will throw a detailed stack trace in case of fatal errors\nprivate static void performLoading(String customLibPath, String userSpecifiedBLAS) {\n- // Only Linux supported for BLAS\n-// if(!SystemUtils.IS_OS_LINUX)\n-// return;\n+ if((customLibPath != null) && customLibPath.equalsIgnoreCase(\"none\"))\n+ customLibPath = null;\n// attemptedLoading variable ensures that we don't try to load SystemDS and other dependencies\n// again and again especially in the parfor (hence the double-checking with synchronized).\n@@ -180,20 +201,19 @@ public class NativeHelper {\nblas = new String[] { \"mkl\", \"openblas\" };\n}\n-\nif(SystemUtils.IS_OS_WINDOWS) {\n- if (checkAndLoadBLAS(customLibPath + \"\\\\lib\", blas) &&\n-// loadLibraryHelper(customLibPath + \"\\\\bin\\\\systemds_\" + blasType + \"-Windows-AMD64.dll\")) {\n-// loadLibraryHelper(\"systemds_\" + blasType + \"-Windows-AMD64.lib\")) {\n-// loadLibraryHelper(customLibPath + \"\\\\systemds_\" + blasType + \"-Windows-AMD64.dll\")) {\n- loadBLAS(customLibPath, \"systemds_\" + blasType + \"-Windows-AMD64\", \"\"))\n+ if (checkAndLoadBLAS(customLibPath, blas) &&\n+ (loadLibraryHelper(\"systemds_\" + blasType + \"-Windows-AMD64\") ||\n+ loadBLAS(customLibPath, \"systemds_\" + blasType + \"-Windows-AMD64\", null))\n+ )\n{\nLOG.info(\"Using native blas: \" + blasType + getNativeBLASPath());\nCURRENT_NATIVE_BLAS_STATE = NativeBlasState.SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE;\n}\n}\nelse {\n- if (checkAndLoadBLAS(customLibPath, blas) && loadLibraryHelper(\"libsystemds_\" + blasType + \"-Linux-x86_64.so\")) {\n+ if (checkAndLoadBLAS(customLibPath, blas) &&\n+ loadLibraryHelper(\"libsystemds_\" + blasType + \"-Linux-x86_64.so\")) {\nLOG.info(\"Using native blas: \" + blasType + getNativeBLASPath());\nCURRENT_NATIVE_BLAS_STATE = NativeBlasState.SUCCESSFULLY_LOADED_NATIVE_BLAS_AND_IN_USE;\n}\n@@ -205,7 +225,8 @@ public class NativeHelper {\nLOG.warn(\"Time to load native blas: \" + timeToLoadInMilliseconds + \" milliseconds.\");\n}\nelse if(LOG.isDebugEnabled() && !isSupportedBLAS(userSpecifiedBLAS)) {\n- LOG.debug(\"Using internal Java BLAS as native BLAS support the configuration 'sysds.native.blas'=\" + userSpecifiedBLAS + \".\");\n+ LOG.debug(\"Using internal Java BLAS as native BLAS support the configuration 'sysds.native.blas'=\" +\n+ userSpecifiedBLAS + \".\");\n}\n}\n@@ -214,18 +235,13 @@ public class NativeHelper {\ncustomLibPath = null;\nboolean isLoaded = false;\n- for(int i = 0; i < listBLAS.length; i++) {\n- String blas = listBLAS[i];\n+ for (String blas : listBLAS) {\nif (blas.equalsIgnoreCase(\"mkl\")) {\n- if(SystemUtils.IS_OS_WINDOWS)\n- isLoaded = true;\n-// isLoaded = loadBLAS(customLibPath, \"mkl_rt.dll\", null);\n- else\nisLoaded = loadBLAS(customLibPath, \"mkl_rt\", null);\n- }\n- else if(blas.equalsIgnoreCase(\"openblas\")) {\n- boolean isGompLoaded = loadBLAS(customLibPath, \"gomp\", \"gomp required for loading OpenBLAS-enabled SystemDS library\");\n- if(isGompLoaded) {\n+ } else if (blas.equalsIgnoreCase(\"openblas\")) {\n+ // no need for gomp on windows\n+ if (SystemUtils.IS_OS_WINDOWS || loadBLAS(customLibPath, \"gomp\",\n+ \"gomp required for loading OpenBLAS-enabled SystemDS library\")) {\nisLoaded = loadBLAS(customLibPath, \"openblas\", null);\n}\n}\n@@ -253,7 +269,7 @@ public class NativeHelper {\nVector<String> libraries = (Vector<String>) loadedLibraryNamesField.get(ClassLoader.getSystemClassLoader());\nLOG.debug(\"List of native libraries loaded:\" + libraries);\nfor(String library : libraries) {\n- if(library.contains(\"libmkl_rt\") || library.contains(\"libopenblas\")) {\n+ if(library.contains(\"mkl_rt\") || library.contains(\"libopenblas\")) {\nblasPathAndHint = \" from the path \" + library;\nbreak;\n}\n@@ -281,7 +297,7 @@ public class NativeHelper {\n*/\nprivate static boolean loadBLAS(String customLibPath, String blas, String optionalMsg) {\n// First attempt to load from custom library path\n- if(customLibPath != null) {\n+ if((customLibPath != null) && (!customLibPath.equalsIgnoreCase(\"none\"))) {\nString libPath = customLibPath + File.separator + System.mapLibraryName(blas);\ntry {\nSystem.load(libPath);\n@@ -301,6 +317,7 @@ public class NativeHelper {\nreturn true;\n}\ncatch (UnsatisfiedLinkError e) {\n+ System.out.println(System.getProperty(\"java.library.path\"));\nif(optionalMsg != null)\nLOG.debug(\"Unable to load \" + blas + \"(\" + optionalMsg + \"):\" + e.getMessage());\nelse\n@@ -312,11 +329,9 @@ public class NativeHelper {\nprivate static boolean loadLibraryHelper(String path) {\nOutputStream out = null;\n- try(InputStream in = NativeHelper.class.getResourceAsStream(\"/lib/\"+path))\n- {\n+ try(InputStream in = NativeHelper.class.getResourceAsStream(\"/lib/\"+path)) {\n// This logic is added because Java does not allow to load library from a resource file.\n- if(in != null)\n- {\n+ if(in != null) {\nFile temp = File.createTempFile(path, \"\");\ntemp.deleteOnExit();\nout = FileUtils.openOutputStream(temp);\n@@ -339,9 +354,11 @@ public class NativeHelper {\n// TODO: Add pmm, wsloss, mmchain, etc.\n//double-precision matrix multiply dense-dense\n- public static native boolean dmmdd(double [] m1, double [] m2, double [] ret, int m1rlen, int m1clen, int m2clen, int numThreads);\n+ public static native boolean dmmdd(double [] m1, double [] m2, double [] ret, int m1rlen, int m1clen, int m2clen,\n+ int numThreads);\n//single-precision matrix multiply dense-dense\n- public static native boolean smmdd(FloatBuffer m1, FloatBuffer m2, FloatBuffer ret, int m1rlen, int m1clen, int m2clen, int numThreads);\n+ public static native boolean smmdd(FloatBuffer m1, FloatBuffer m2, FloatBuffer ret, int m1rlen, int m1clen, int m2clen,\n+ int numThreads);\n//transpose-self matrix multiply\npublic static native boolean tsmm(double[] m1, double[] ret, int m1rlen, int m1clen, boolean leftTrans, int numThreads);\n@@ -349,35 +366,50 @@ public class NativeHelper {\n// LibMatrixDNN operations:\n// N = number of images, C = number of channels, H = image height, W = image width\n// K = number of filters, R = filter height, S = filter width\n- // TODO: case not handled: sparse filters (which will only be executed in Java). Since filters are relatively smaller, this is a low priority.\n+ // TODO: case not handled: sparse filters (which will only be executed in Java). Since filters are relatively smaller,\n+ // this is a low priority.\n// Returns -1 if failures or returns number of nonzeros\n// Called by DnnCPInstruction if both input and filter are dense\npublic static native int conv2dDense(double [] input, double [] filter, double [] ret, int N, int C, int H, int W,\nint K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q, int numThreads);\n+\npublic static native int dconv2dBiasAddDense(double [] input, double [] bias, double [] filter, double [] ret, int N,\n- int C, int H, int W, int K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q, int numThreads);\n+ int C, int H, int W, int K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q,\n+ int numThreads);\n+\npublic static native int sconv2dBiasAddDense(FloatBuffer input, FloatBuffer bias, FloatBuffer filter, FloatBuffer ret,\n- int N, int C, int H, int W, int K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q, int numThreads);\n+ int N, int C, int H, int W, int K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q,\n+ int numThreads);\n+\n// Called by DnnCPInstruction if both input and filter are dense\n- public static native int conv2dBackwardFilterDense(double [] input, double [] dout, double [] ret, int N, int C, int H, int W,\n- int K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q, int numThreads);\n+ public static native int conv2dBackwardFilterDense(double [] input, double [] dout, double [] ret, int N, int C,\n+ int H, int W, int K, int R, int S, int stride_h, int stride_w,\n+ int pad_h, int pad_w, int P, int Q, int numThreads);\n+\n// If both filter and dout are dense, then called by DnnCPInstruction\n// Else, called by LibMatrixDNN's thread if filter is dense. dout[n] is converted to dense if sparse.\n- public static native int conv2dBackwardDataDense(double [] filter, double [] dout, double [] ret, int N, int C, int H, int W,\n- int K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q, int numThreads);\n+ public static native int conv2dBackwardDataDense(double [] filter, double [] dout, double [] ret, int N, int C,\n+ int H, int W, int K, int R, int S, int stride_h, int stride_w,\n+ int pad_h, int pad_w, int P, int Q, int numThreads);\n// Currently only supported with numThreads = 1 and sparse input\n// Called by LibMatrixDNN's thread if input is sparse. dout[n] is converted to dense if sparse.\n- public static native boolean conv2dBackwardFilterSparseDense(int apos, int alen, int[] aix, double[] avals, double [] rotatedDoutPtr, double [] ret, int N, int C, int H, int W,\n- int K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q, int numThreads);\n+ public static native boolean conv2dBackwardFilterSparseDense(int apos, int alen, int[] aix, double[] avals,\n+ double [] rotatedDoutPtr, double [] ret, int N, int C,\n+ int H, int W, int K, int R, int S, int stride_h,\n+ int stride_w, int pad_h, int pad_w, int P, int Q,\n+ int numThreads);\n+\n// Called by LibMatrixDNN's thread if input is sparse and filter is dense\n- public static native boolean conv2dSparse(int apos, int alen, int[] aix, double[] avals, double [] filter, double [] ret, int N, int C, int H, int W,\n- int K, int R, int S, int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q, int numThreads);\n+ public static native boolean conv2dSparse(int apos, int alen, int[] aix, double[] avals, double [] filter,\n+ double [] ret, int N, int C, int H, int W, int K, int R, int S,\n+ int stride_h, int stride_w, int pad_h, int pad_w, int P, int Q,\n+ int numThreads);\n// ----------------------------------------------------------------------------------------------------------------\n- // This method helps us decide whether to use GetPrimitiveArrayCritical or GetDoubleArrayElements in JNI as each has different tradeoffs.\n- // In current implementation, we always use GetPrimitiveArrayCritical as it has proven to be fastest.\n- // We can revisit this decision later and hence I would not recommend removing this method.\n+ // This method helps us decide whether to use GetPrimitiveArrayCritical or GetDoubleArrayElements in JNI as each has\n+ // different tradeoffs. In current implementation, we always use GetPrimitiveArrayCritical as it has proven to be\n+ // fastest. We can revisit this decision later and hence I would not recommend removing this method.\nprivate static native void setMaxNumThreads(int numThreads);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/AutomatedTestBase.java",
"new_path": "src/test/java/org/tugraz/sysds/test/AutomatedTestBase.java",
"diff": "/*\n- * Modifications Copyright 2019 Graz University of Technology\n+ * Modifications Copyright 2020 Graz University of Technology\n*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n@@ -38,6 +38,7 @@ import java.util.HashMap;\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\n+import org.apache.commons.lang.SystemUtils;\nimport org.apache.spark.sql.SparkSession;\nimport org.apache.spark.sql.SparkSession.Builder;\nimport org.apache.wink.json4j.JSONObject;\n@@ -69,7 +70,6 @@ import org.tugraz.sysds.runtime.util.HDFSTool;\nimport org.tugraz.sysds.utils.ParameterBuilder;\nimport org.tugraz.sysds.utils.Statistics;\n-\n/**\n* <p>\n* Extend this class to easily\n@@ -103,27 +103,34 @@ public abstract class AutomatedTestBase {\n// is the root of this project.\nstatic {\n- String osname = System.getProperty(\"os.name\").toLowerCase();\n- if(osname.contains(\"win\")) {\n- System.err.printf(\"AutomatedTestBase has detected a Windows OS and is overriding\\n\"\n+ /* For testing MKL BLAS on Windows run \"mklvars.bat intel64\" or \"compilervars.bat intel64\" (this script\n+ * comes with the mkl software package and sets the env var MKLROOT). Then start SystemDS or\n+ * your IDE from that environment (e.g. from that command prompt).\n+ * Alternatively you can set MKLROOT and your PATH variables manually to make it permanent.\n+ * Same for Linux but with compilervars.sh intel64.\n+ * For OpenBLAS point your PATH to the shared library.\n+ */\n+\n+ // the JNI implementation will be in a SO/DLL in that directory\n+ // after a successful mvn package\n+ appendToJavaLibraryPath(\"target\" + File.separator + \"classes\" + File.separator + \"lib\");\n+\n+ if(SystemUtils.IS_OS_WINDOWS) {\n+ System.err.println(\"AutomatedTestBase has detected a Windows OS and is overriding\\n\"\n+ \"hadoop.home.dir and java.library.path.\\n\");\nString cwd = System.getProperty(\"user.dir\");\n+ System.setProperty(\"hadoop.home.dir\", cwd + File.separator + \"src\" + File.separator + \"test\" +\n+ File.separator + \"config\" +\n+ File.separator + \"hadoop_bin_windows\");\n- System.setProperty(\"hadoop.home.dir\", cwd + File.separator + \"\\\\src\\\\test\\\\config\\\\hadoop_bin_windows\");\n+ appendToJavaLibraryPath(cwd);\n+ appendToJavaLibraryPath(cwd + File.separator + \"src\" + File.separator + \"test\" + File.separator + \"config\" +\n+ File.separator + \"hadoop_bin_windows\" + File.separator + \"bin\");\n+ appendToJavaLibraryPath(\"lib\");\nif(TEST_GPU) {\nString CUDA_LIBRARY_PATH = System.getenv(\"CUDA_PATH\") + File.separator + \"bin\";\n- System.setProperty(\"java.library.path\",\n- cwd + File.separator + \"\\\\src\\\\test\\\\config\\\\hadoop_bin_windows\\\\bin\" + File.pathSeparator + \"/lib\"\n- + File.pathSeparator + CUDA_LIBRARY_PATH);\n- }\n- else {\n- System.setProperty(\"java.library.path\",\n- cwd + File.separator + \"\\\\src\\\\test\\\\config\\\\hadoop_bin_windows\\\\bin\"\n- // For testing BLAS on Windows\n- // + File.pathSeparator + \"C:\\\\Program Files\n- // (x86)\\\\IntelSWTools\\\\compilers_and_libraries_2017.0.109\\\\windows\\\\redist\\\\intel64_win\\\\mkl\"\n- );\n+ appendToJavaLibraryPath(CUDA_LIBRARY_PATH);\n}\n// Need to muck around with the classloader to get it to use the new\n@@ -1804,4 +1811,9 @@ public abstract class AutomatedTestBase {\nreturn \"N/A\";\n}\n}\n+\n+ public static void appendToJavaLibraryPath(String additional_path) {\n+ String current_path = System.getProperty(\"java.library.path\");\n+ System.setProperty(\"java.library.path\", current_path + File.pathSeparator + additional_path);\n+ }\n}\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-151] Follow-up to improve BLAS loading and building JNI helpers with CMake |
49,689 | 14.10.2019 11:57:23 | -7,200 | 729b293cd725dd2f08c8a61887a1c50cca92148f | Unmark loop dependent operations for lineage caching
Closes | [
{
"change_type": "MODIFY",
"old_path": "docs/Tasks.txt",
"new_path": "docs/Tasks.txt",
"diff": "@@ -190,6 +190,7 @@ SYSTEMDS-230 Lineage Integration\n* 234 Lineage tracing for spark instructions OK\n* 235 Lineage tracing for remote-spark parfor OK\n* 236 Extended multi-level lineage cache for statement blocks OK\n+ * 237 Unmark loop dependent operations OK\nSYSTEMDS-240 GPU Backend Improvements\n* 241 Dense GPU cumulative aggregates OK\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/AggBinaryOp.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/AggBinaryOp.java",
"diff": "/*\n- * Modifications Copyright 2019 Graz University of Technology\n+ * Modifications Copyright 2020 Graz University of Technology\n*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n@@ -58,7 +58,6 @@ import org.tugraz.sysds.runtime.util.UtilFunctions;\n*\n* Semantic: generate indices, align, cross-operate, generate indices, align, aggregate\n*/\n-\npublic class AggBinaryOp extends MultiThreadedHop\n{\npublic static final double MAPMULT_MEM_MULTIPLIER = 1.0;\n@@ -537,7 +536,7 @@ public class AggBinaryOp extends MultiThreadedHop\nint k = OptimizerUtils.getConstrainedNumThreads(_maxNumThreads);\nLop matmultCP = new MMTSJ(getInput().get(mmtsj.isLeft()?1:0).constructLops(),\ngetDataType(), getValueType(), et, mmtsj, false, k);\n- matmultCP.getOutputParameters().setDimensions(getDim1(), getDim2(), getBlocksize(), getNnz());\n+ matmultCP.getOutputParameters().setDimensions(getDim1(), getDim2(), getBlocksize(), getNnz(), requiresLineageCaching());\nsetLineNumbers( matmultCP );\nsetLops(matmultCP);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/Hop.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/Hop.java",
"diff": "/*\n- * Modifications Copyright 2019 Graz University of Technology\n+ * Modifications Copyright 2020 Graz University of Technology\n*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n@@ -114,6 +114,10 @@ public abstract class Hop implements ParseInfo\n// if those exists; otherwise only blocks w/ non-zero values are materialized\nprotected boolean _outputEmptyBlocks = true;\n+ // indicates if the output of this hop needs to be saved in lineage cache\n+ // this is a suggestion by compiler and can be ignored by runtime\n+ protected boolean _requiresLineageCaching = true;\n+\nprivate Lop _lops = null;\nprotected Hop(){\n@@ -264,6 +268,14 @@ public abstract class Hop implements ParseInfo\nreturn _requiresCompression;\n}\n+ public void setRequiresLineageCaching(boolean flag) {\n+ _requiresLineageCaching = flag;\n+ }\n+\n+ public boolean requiresLineageCaching() {\n+ return _requiresLineageCaching;\n+ }\n+\npublic void constructAndSetLopsDataFlowProperties() {\n//Step 1: construct reblock lop if required (output of hop)\nconstructAndSetReblockLopIfRequired();\n@@ -1653,6 +1665,7 @@ public abstract class Hop implements ParseInfo\n_requiresReblock = that._requiresReblock;\n_requiresCheckpoint = that._requiresCheckpoint;\n_requiresCompression = that._requiresCompression;\n+ _requiresLineageCaching = that._requiresLineageCaching;\n_outputEmptyBlocks = that._outputEmptyBlocks;\n_beginLine = that._beginLine;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/MarkForLineageReuse.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.hops.rewrite;\n+\n+import java.util.ArrayList;\n+import java.util.Arrays;\n+import java.util.HashSet;\n+import java.util.List;\n+import java.util.Set;\n+import java.util.stream.Collectors;\n+\n+import org.tugraz.sysds.common.Types.OpOpData;\n+import org.tugraz.sysds.hops.Hop;\n+import org.tugraz.sysds.parser.ForStatement;\n+import org.tugraz.sysds.parser.ForStatementBlock;\n+import org.tugraz.sysds.parser.FunctionStatement;\n+import org.tugraz.sysds.parser.FunctionStatementBlock;\n+import org.tugraz.sysds.parser.IfStatement;\n+import org.tugraz.sysds.parser.IfStatementBlock;\n+import org.tugraz.sysds.parser.StatementBlock;\n+import org.tugraz.sysds.parser.WhileStatement;\n+import org.tugraz.sysds.parser.WhileStatementBlock;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig;\n+\n+public class MarkForLineageReuse extends StatementBlockRewriteRule\n+{\n+ @Override\n+ public boolean createsSplitDag() {\n+ return false;\n+ }\n+\n+ @Override\n+ public List<StatementBlock> rewriteStatementBlock(StatementBlock sb, ProgramRewriteStatus status)\n+ {\n+ if (!HopRewriteUtils.isLoopStatementBlock(sb) || LineageCacheConfig.ReuseCacheType.isNone())\n+ return Arrays.asList(sb); //early abort\n+\n+ if (sb instanceof ForStatementBlock) {\n+ ForStatement fstmt = (ForStatement)sb.getStatement(0);\n+ Set<String> loopVar = new HashSet<>(Arrays.asList(fstmt.getIterablePredicate().getIterVar().getName()));\n+ HashSet<String> deproots = new HashSet<>();\n+ rUnmarkLoopDepVarsSB(fstmt.getBody(), deproots, loopVar);\n+ }\n+ if (sb instanceof WhileStatementBlock) {\n+ WhileStatement wstmt = (WhileStatement)sb.getStatement(0);\n+ // intersection of updated and conditional variables are the loop variables\n+ Set<String> loopVar = sb.variablesUpdated().getVariableNames().stream()\n+ .filter(v -> wstmt.getConditionalPredicate().variablesRead().containsVariable(v))\n+ .collect(Collectors.toSet());\n+ HashSet<String> deproots = new HashSet<>();\n+ rUnmarkLoopDepVarsSB(wstmt.getBody(), deproots, loopVar);\n+ }\n+ return Arrays.asList(sb);\n+ }\n+\n+ private void rUnmarkLoopDepVarsSB(ArrayList<StatementBlock> sbs, HashSet<String> deproots, Set<String> loopVar)\n+ {\n+ HashSet<String> newdepsbs = new HashSet<>();\n+ int lim = 0;\n+ do {\n+ newdepsbs.clear();\n+ newdepsbs.addAll(deproots);\n+ for (StatementBlock sb : sbs) {\n+ if (sb instanceof ForStatementBlock) {\n+ ForStatement fstmt = (ForStatement)sb.getStatement(0);\n+ rUnmarkLoopDepVarsSB(fstmt.getBody(), newdepsbs, loopVar);\n+ //TODO: nested loops.\n+ }\n+ else if (sb instanceof WhileStatementBlock) {\n+ WhileStatement wstmt = (WhileStatement)sb.getStatement(0);\n+ rUnmarkLoopDepVarsSB(wstmt.getBody(), newdepsbs, loopVar);\n+ }\n+ else if (sb instanceof IfStatementBlock) {\n+ IfStatement ifstmt = (IfStatement)sb.getStatement(0);\n+ rUnmarkLoopDepVarsSB(ifstmt.getIfBody(), newdepsbs, loopVar);\n+ if (ifstmt.getElseBody() != null)\n+ rUnmarkLoopDepVarsSB(ifstmt.getElseBody(), newdepsbs, loopVar);\n+ }\n+ else if (sb instanceof FunctionStatementBlock) {\n+ FunctionStatement fnstmt = (FunctionStatement)sb.getStatement(0);\n+ rUnmarkLoopDepVarsSB(fnstmt.getBody(), newdepsbs, loopVar);\n+ }\n+ else {\n+ if (sb.getHops() != null)\n+ for (int j=0; j<sb.variablesUpdated().getSize(); j++) {\n+ HashSet<String> newdeproots = new HashSet<>(deproots);\n+ for (Hop hop : sb.getHops()) {\n+ // find the loop dependent DAG roots\n+ Hop.resetVisitStatus(sb.getHops());\n+ HashSet<Long> dephops = new HashSet<>();\n+ rUnmarkLoopDepVars(hop, loopVar, newdeproots, dephops);\n+ }\n+ if (!deproots.isEmpty() && deproots.equals(newdeproots))\n+ // break if loop dependent DAGs are converged to a unvarying set\n+ break;\n+ else\n+ // iterate to propagate the loop dependents across all the DAGs in this SB\n+ deproots.addAll(newdeproots);\n+ }\n+ }\n+ }\n+ deproots.addAll(newdepsbs);\n+ lim++;\n+ }\n+ // iterate to propagate the loop dependents across all the SBs\n+ while (lim < sbs.size() && (deproots.isEmpty() || !deproots.equals(newdepsbs)));\n+ }\n+\n+ private void rUnmarkLoopDepVars(Hop hop, Set<String> loopVar, HashSet<String> deproots, HashSet<Long> dephops)\n+ {\n+ if (hop.isVisited())\n+ return;\n+\n+ for (Hop hi : hop.getInput())\n+ rUnmarkLoopDepVars(hi, loopVar, deproots, dephops);\n+\n+ // unmark operation if this itself or any of its inputs are loop dependent\n+ boolean loopdephop = loopVar.contains(hop.getName())\n+ || (HopRewriteUtils.isData(hop, OpOpData.TRANSIENTREAD)\n+ && deproots.contains(hop.getName()));\n+ for (Hop hi : hop.getInput())\n+ loopdephop |= dephops.contains(hi.getHopID());\n+\n+ if (loopdephop) {\n+ dephops.add(hop.getHopID());\n+ hop.setRequiresLineageCaching(false);\n+ //TODO: extend all the hops to propagate till variablecp output\n+ }\n+ // TODO: logic to separate out partially reusable cases (e.g cbind-tsmm)\n+\n+ if (HopRewriteUtils.isData(hop, OpOpData.TRANSIENTWRITE)\n+ && !dephops.isEmpty())\n+ // copy to propagate across\n+ deproots.add(hop.getName());\n+\n+ hop.setVisited();\n+ }\n+\n+ @Override\n+ public List<StatementBlock> rewriteStatementBlocks(List<StatementBlock> sbs, ProgramRewriteStatus status) {\n+ return sbs;\n+ }\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/rewrite/ProgramRewriter.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/rewrite/ProgramRewriter.java",
"diff": "/*\n+ * Modifications Copyright 2020 Graz University of Technology\n+ *\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n* distributed with this work for additional information\n@@ -40,6 +42,7 @@ import org.tugraz.sysds.parser.ParForStatementBlock;\nimport org.tugraz.sysds.parser.StatementBlock;\nimport org.tugraz.sysds.parser.WhileStatement;\nimport org.tugraz.sysds.parser.WhileStatementBlock;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig;\n/**\n* This program rewriter applies a variety of rule-based rewrites\n@@ -117,6 +120,8 @@ public class ProgramRewriter\n_sbRuleSet.add( new RewriteHoistLoopInvariantOperations() ); //dependency: vectorize, but before inplace\nif( OptimizerUtils.ALLOW_LOOP_UPDATE_IN_PLACE )\n_sbRuleSet.add( new RewriteMarkLoopVariablesUpdateInPlace() );\n+ if( LineageCacheConfig.getCompAssRW() )\n+ _sbRuleSet.add( new MarkForLineageReuse() );\n}\n// DYNAMIC REWRITES (which do require size information)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/lops/OutputParameters.java",
"new_path": "src/main/java/org/tugraz/sysds/lops/OutputParameters.java",
"diff": "/*\n+ * Modifications Copyright 2020 Graz University of Technology\n+ *\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n* distributed with this work for additional information\n@@ -39,6 +41,7 @@ public class OutputParameters\nprivate long _blocksize = -1;\nprivate String _file_name = null;\nprivate String _file_label = null;\n+ private boolean _linCacheCandidate = true;\nFileFormat matrix_format = FileFormat.BINARY;\n@@ -84,6 +87,11 @@ public class OutputParameters\nsetDimensions(rows, cols, blen, nnz);\n}\n+ public void setDimensions(long rows, long cols, long blen, long nnz, boolean linCacheCand) {\n+ _linCacheCandidate = linCacheCand;\n+ setDimensions(rows, cols, blen, nnz);\n+ }\n+\npublic void setDimensions(OutputParameters input) {\n_num_rows = input._num_rows;\n_num_cols = input._num_cols;\n@@ -138,6 +146,10 @@ public class OutputParameters\n_updateType = update;\n}\n+ public boolean getLinCacheMarking() {\n+ return _linCacheCandidate;\n+ }\n+\npublic long getBlocksize() {\nreturn _blocksize;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/lops/compile/Dag.java",
"new_path": "src/main/java/org/tugraz/sysds/lops/compile/Dag.java",
"diff": "/*\n- * Modifications Copyright 2019 Graz University of Technology\n+ * Modifications Copyright 2020 Graz University of Technology\n*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n@@ -805,7 +805,7 @@ public class Dag<N extends Lop>\noparams.getLabel(), oparams.getFile_name(), true, node.getDataType(),\nOutputInfo.outputInfoToString(getOutputInfo(node, false)),\nnew MatrixCharacteristics(oparams.getNumRows(), oparams.getNumCols(), blen, oparams.getNnz()),\n- oparams.getUpdateType());\n+ oparams.getUpdateType(), oparams.getLinCacheMarking());\ncreatevarInst.setLocation(node);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/parser/VariableSet.java",
"new_path": "src/main/java/org/tugraz/sysds/parser/VariableSet.java",
"diff": "/*\n+ * Modifications Copyright 2020 Graz University of Technology\n+ *\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n* distributed with this work for additional information\n@@ -69,6 +71,10 @@ public class VariableSet\nreturn _variables.keySet();\n}\n+ public int getSize(){\n+ return _variables.size();\n+ }\n+\npublic HashMap<String,DataIdentifier> getVariables(){\nreturn _variables;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/caching/MatrixObject.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/caching/MatrixObject.java",
"diff": "/*\n- * Modifications Copyright 2019 Graz University of Technology\n+ * Modifications Copyright 2020 Graz University of Technology\n*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n@@ -85,6 +85,7 @@ public class MatrixObject extends CacheableData<MatrixBlock>\n//additional matrix-specific flags\nprivate UpdateType _updateType = UpdateType.COPY;\nprivate boolean _diag = false;\n+ private boolean _markForLinCache = false;\n//information relevant to partitioned matrices.\nprivate boolean _partitioned = false; //indicates if obj partitioned\n@@ -140,6 +141,7 @@ public class MatrixObject extends CacheableData<MatrixBlock>\n_partitionFormat = mo._partitionFormat;\n_partitionSize = mo._partitionSize;\n_partitionCacheName = mo._partitionCacheName;\n+ _markForLinCache = mo._markForLinCache;\n}\npublic boolean isFederated() {\n@@ -218,6 +220,14 @@ public class MatrixObject extends CacheableData<MatrixBlock>\n_diag = diag;\n}\n+ public void setMarkForLinCache (boolean mark) {\n+ _markForLinCache = mark;\n+ }\n+\n+ public boolean isMarked() {\n+ return _markForLinCache;\n+ }\n+\n@Override\npublic void updateDataCharacteristics (DataCharacteristics dc) {\n_metaData.getDataCharacteristics().set(dc);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/VariableCPInstruction.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/instructions/cp/VariableCPInstruction.java",
"diff": "/*\n- * Modifications Copyright 2019 Graz University of Technology\n+ * Modifications Copyright 2020 Graz University of Technology\n*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n@@ -117,6 +117,7 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\nprivate final CPOperand output;\nprivate final MetaData metadata;\nprivate final UpdateType _updateType;\n+ private final boolean _markForLinCache;\n// Frame related members\nprivate final String _schema;\n@@ -125,7 +126,7 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\nprivate final FileFormatProperties _formatProperties;\nprivate VariableCPInstruction(VariableOperationCode op, CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out,\n- MetaData meta, FileFormatProperties fprops, String schema, UpdateType utype, String sopcode, String istr) {\n+ MetaData meta, FileFormatProperties fprops, String schema, UpdateType utype, String sopcode, String istr, boolean linCache) {\nsuper(CPType.Variable, sopcode, istr);\nopcode = op;\ninputs = new ArrayList<>();\n@@ -137,24 +138,25 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\n_formatProperties = fprops;\n_schema = schema;\n_updateType = utype;\n+ _markForLinCache = linCache;\n}\nprivate VariableCPInstruction(VariableOperationCode op, CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out,\nString sopcode, String istr) {\n- this(op, in1, in2, in3, out, null, null, null, null, sopcode, istr);\n+ this(op, in1, in2, in3, out, null, null, null, null, sopcode, istr, false);\n}\n// This version of the constructor is used only in case of CreateVariable\nprivate VariableCPInstruction(VariableOperationCode op, CPOperand in1, CPOperand in2, CPOperand in3, MetaData md,\n- UpdateType updateType, String schema, String sopcode, String istr) {\n- this(op, in1, in2, in3, null, md, null, schema, updateType, sopcode, istr);\n+ UpdateType updateType, String schema, String sopcode, String istr, boolean lineageCache) {\n+ this(op, in1, in2, in3, null, md, null, schema, updateType, sopcode, istr, lineageCache);\n}\n// This version of the constructor is used only in case of CreateVariable\nprivate VariableCPInstruction(VariableOperationCode op, CPOperand in1, CPOperand in2, CPOperand in3, MetaData md,\nUpdateType updateType, FileFormatProperties formatProperties, String schema, String sopcode,\nString istr) {\n- this(op, in1, in2, in3, null, md, formatProperties, schema, updateType, sopcode, istr);\n+ this(op, in1, in2, in3, null, md, formatProperties, schema, updateType, sopcode, istr, false);\n}\nprivate static VariableOperationCode getVariableOperationCode ( String str ) {\n@@ -354,7 +356,7 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\nthrow new DMLRuntimeException(\"Invalid number of operands in createvar instruction: \" + str);\n}\nelse {\n- if ( parts.length != 6 && parts.length != 11+extSchema )\n+ if ( parts.length != 6 && parts.length != 11+extSchema && parts.length != 12+extSchema )\nthrow new DMLRuntimeException(\"Invalid number of operands in createvar instruction: \" + str);\n}\nOutputInfo oi = OutputInfo.stringToOutputInfo(fmt);\n@@ -396,6 +398,9 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\nUpdateType updateType = UpdateType.COPY;\nif ( parts.length >= 11 )\nupdateType = UpdateType.valueOf(parts[10].toUpperCase());\n+ boolean lineageCache = false;\n+ if (parts.length >= 12)\n+ lineageCache = Boolean.parseBoolean(parts[11]);\n//handle frame schema\nString schema = (dt==DataType.FRAME && parts.length>=12) ? parts[parts.length-1] : null;\n@@ -425,7 +430,7 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\nreturn new VariableCPInstruction(VariableOperationCode.CreateVariable, in1, in2, in3, iimd, updateType, fmtProperties, schema, opcode, str);\n}\nelse {\n- return new VariableCPInstruction(VariableOperationCode.CreateVariable, in1, in2, in3, iimd, updateType, schema, opcode, str);\n+ return new VariableCPInstruction(VariableOperationCode.CreateVariable, in1, in2, in3, iimd, updateType, schema, opcode, str, lineageCache);\n}\ncase AssignVariable:\nin1 = new CPOperand(parts[1]);\n@@ -491,7 +496,7 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\nin4 = new CPOperand(parts[4]); // description\n}\nVariableCPInstruction inst = new VariableCPInstruction(\n- getVariableOperationCode(opcode), in1, in2, in3, out, null, fprops, null, null, opcode, str);\n+ getVariableOperationCode(opcode), in1, in2, in3, out, null, fprops, null, null, opcode, str, false);\ninst.addInput(in4);\nreturn inst;\n@@ -530,6 +535,7 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\n//is potential for hidden side effects between variables.\nobj.setMetaData((MetaData)metadata.clone());\nobj.setFileFormatProperties(_formatProperties);\n+ obj.setMarkForLinCache(_markForLinCache);\nobj.enableCleanup(!getInput1().getName()\n.startsWith(org.tugraz.sysds.lops.Data.PREAD_PREFIX));\nec.setVariable(getInput1().getName(), obj);\n@@ -1135,6 +1141,16 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\nreturn parseInstruction(str);\n}\n+ public static Instruction prepareCreateVariableInstruction(String varName, String fileName, boolean fNameOverride, DataType dt, String format, DataCharacteristics mc, UpdateType update, boolean linCacheCand) {\n+ StringBuilder sb = new StringBuilder();\n+ sb.append(prepareCreateVariableInstruction(varName,fileName, fNameOverride, dt, format, mc, update));\n+ sb.append(Lop.OPERAND_DELIMITOR);\n+ sb.append(linCacheCand);\n+\n+ String str = sb.toString();\n+ return parseInstruction(str);\n+ }\n+\npublic static Instruction prepareCreateVariableInstruction(String varName, String fileName, boolean fNameOverride, DataType dt, String format, DataCharacteristics mc, UpdateType update, boolean hasHeader, String delim, boolean sparse) {\nStringBuilder sb = new StringBuilder();\nsb.append(getBasicCreateVarString(varName, fileName, fNameOverride, dt, format));\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCache.java",
"diff": "/*\n- * Copyright 2019 Graz University of Technology\n+ * Copyright 2020 Graz University of Technology\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n@@ -89,7 +89,7 @@ public class LineageCache {\n//create a placeholder if no reuse to avoid redundancy\n//(e.g., concurrent threads that try to start the computation)\n- if( ! reuse )\n+ if(!reuse && isMarkedForCaching(inst, ec))\nputIntern(item, null, 0);\n}\n}\n@@ -172,6 +172,7 @@ public class LineageCache {\nif (ReuseCacheType.isNone())\nreturn;\nif (inst instanceof ComputationCPInstruction && isReusable(inst, ec) ) {\n+ if (!isMarkedForCaching(inst, ec)) return;\nLineageItem item = ((LineageTraceable) inst).getLineageItems(ec)[0];\nMatrixObject mo = ec.getMatrixObject(((ComputationCPInstruction) inst).output);\nMatrixBlock value = mo.acquireReadAndRelease();\n@@ -331,6 +332,16 @@ public class LineageCache {\nreturn(c1 == 1 || c2 == 1);\n}\n+ public static boolean isMarkedForCaching (Instruction inst, ExecutionContext ec) {\n+ if (!LineageCacheConfig.getCompAssRW())\n+ return true;\n+\n+ MatrixObject mo = ec.getMatrixObject(((ComputationCPInstruction)inst).output);\n+ //limit this to full reuse as partial reuse is applicable even for loop dependent operation\n+ boolean marked = (LineageCacheConfig.getCacheType() == ReuseCacheType.REUSE_FULL && !mo.isMarked()) ? false : true;\n+ return marked;\n+ }\n+\n//---------------- CACHE SPACE MANAGEMENT METHODS -----------------\nprivate static boolean isBelowThreshold(MatrixBlock value) {\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCacheConfig.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageCacheConfig.java",
"diff": "/*\n- * Copyright 2019 Graz University of Technology\n+ * Copyright 2020 Graz University of Technology\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n@@ -56,7 +56,7 @@ public class LineageCacheConfig {\nprivate static ReuseCacheType _cacheType = null;\nprivate static CachedItemHead _itemH = null;\nprivate static CachedItemTail _itemT = null;\n-\n+ private static boolean _compilerAssistedRW = true;\nstatic {\n//setup static configuration parameters\nsetSpill(false); //disable spilling of cache entries to disk\n@@ -78,6 +78,10 @@ public class LineageCacheConfig {\n_itemT = itt;\n}\n+ public static void setCompAssRW(boolean comp) {\n+ _compilerAssistedRW = comp;\n+ }\n+\npublic static void shutdownReuse() {\nDMLScript.LINEAGE = false;\nDMLScript.LINEAGE_REUSE = ReuseCacheType.NONE;\n@@ -107,4 +111,8 @@ public class LineageCacheConfig {\npublic static CachedItemTail getCachedItemTail() {\nreturn _itemT;\n}\n+\n+ public static boolean getCompAssRW() {\n+ return _compilerAssistedRW;\n+ }\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/java/org/tugraz/sysds/test/functions/lineage/UnmarkLoopDepVarsTest.java",
"diff": "+/*\n+ * Copyright 2020 Graz University of Technology\n+ *\n+ * Licensed under the Apache License, Version 2.0 (the \"License\");\n+ * you may not use this file except in compliance with the License.\n+ * You may obtain a copy of the License at\n+ *\n+ * http://www.apache.org/licenses/LICENSE-2.0\n+ *\n+ * Unless required by applicable law or agreed to in writing, software\n+ * distributed under the License is distributed on an \"AS IS\" BASIS,\n+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+ * See the License for the specific language governing permissions and\n+ * limitations under the License.\n+ */\n+\n+package org.tugraz.sysds.test.functions.lineage;\n+\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+import org.junit.Test;\n+import org.tugraz.sysds.hops.recompile.Recompiler;\n+import org.tugraz.sysds.runtime.lineage.Lineage;\n+import org.tugraz.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue;\n+import org.tugraz.sysds.test.AutomatedTestBase;\n+import org.tugraz.sysds.test.TestConfiguration;\n+import org.tugraz.sysds.test.TestUtils;\n+\n+public class UnmarkLoopDepVarsTest extends AutomatedTestBase {\n+ protected static final String TEST_DIR = \"functions/lineage/\";\n+ protected static final String TEST_NAME1 = \"unmarkLoopDepVars\";\n+\n+ protected String TEST_CLASS_DIR = TEST_DIR + UnmarkLoopDepVarsTest.class.getSimpleName() + \"/\";\n+\n+ protected static final int numRecords = 100;\n+ protected static final int numFeatures = 30;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1));\n+ }\n+\n+ @Test\n+ public void unmarkloopdepvars() {\n+ runtest();\n+ }\n+\n+ private void runtest() {\n+ try {\n+ getAndLoadTestConfiguration(UnmarkLoopDepVarsTest.TEST_NAME1);\n+ List<String> proArgs = new ArrayList<>();\n+\n+ proArgs.add(\"-explain\");\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(input(\"X\"));\n+ proArgs.add(output(\"Res\"));\n+ programArgs = proArgs.toArray(new String[0]);\n+ fullDMLScriptName = getScript();\n+ double[][] X = getRandomMatrix(numRecords, numFeatures, 0, 1, 0.8, -1);\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+ HashMap<MatrixValue.CellIndex, Double> R_orig = readDMLMatrixFromHDFS(\"Res\");\n+\n+ proArgs.clear();\n+ proArgs.add(\"-explain\");\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(ReuseCacheType.REUSE_FULL.name().toLowerCase());\n+ proArgs.add(\"-args\");\n+ proArgs.add(input(\"X\"));\n+ proArgs.add(output(\"Res\"));\n+ programArgs = proArgs.toArray(new String[0]);\n+ fullDMLScriptName = getScript();\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+ Lineage.resetInternalState();\n+ Lineage.setLinReusePartial();\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+ Lineage.setLinReuseNone();\n+ HashMap<MatrixValue.CellIndex, Double> R_reused = readDMLMatrixFromHDFS(\"Res\");\n+ TestUtils.compareMatrices(R_orig, R_reused, 1e-6, \"Origin\", \"Reused\");\n+ }\n+ finally {\n+ Recompiler.reinitRecompiler();\n+ }\n+ }\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "src/test/scripts/functions/lineage/unmarkLoopDepVars.dml",
"diff": "+#-------------------------------------------------------------\n+#\n+# Copyright 2020 Graz University of Technology\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+#\n+#-------------------------------------------------------------\n+\n+X = read($1);\n+\n+sum = 0;\n+tmp = X[,1];\n+R = matrix(0, 1, ncol(X));\n+\n+for (i in 2:ncol(X)) {\n+ Res1 = t(tmp) %*% tmp; #loop dependent\n+ Res2 = t(X) %*% X;\n+ tmp = cbind(tmp, X[,i]); #loop dependent\n+ while(FALSE) {}\n+ R[1,i] = sum(Res1); #loop dependent\n+ sum = sum + sum(Res1); #loop dependent\n+}\n+\n+R = R + sum(Res2);\n+write(R, $2, format=\"text\");\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-237] Unmark loop dependent operations for lineage caching
Closes #119 |
49,706 | 18.03.2020 17:47:59 | -3,600 | 01aca93d2bb2a7f63b27c0fc31ae1af1180f3a98 | [MINOR] Aggregate and binary tensor threadsafe | [
{
"change_type": "MODIFY",
"old_path": "pom.xml",
"new_path": "pom.xml",
"diff": "<threadCount>12</threadCount>\n<!-- 1C means the number of threads times 1 posible maximum forks for testing-->\n<forkCount>1C</forkCount>\n- <argLine>-Xms4g -Xmx6g</argLine>\n+ <argLine>-Xms4g -Xmx4g</argLine>\n<reuseForks>false</reuseForks>\n</configuration>\n</plugin>\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/aggregate/TensorSumTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/aggregate/TensorSumTest.java",
"diff": "@@ -30,6 +30,7 @@ import java.util.Arrays;\nimport java.util.Collection;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class TensorSumTest extends AutomatedTestBase\n{\nprivate final static String TEST_DIR = \"functions/aggregate/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/binary/tensor/ElementwiseAdditionTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/binary/tensor/ElementwiseAdditionTest.java",
"diff": "@@ -32,6 +32,7 @@ import java.util.Arrays;\nimport java.util.Collection;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class ElementwiseAdditionTest extends AutomatedTestBase {\nprivate final static String TEST_DIR = \"functions/binary/tensor/\";\nprivate final static String TEST_NAME = \"ElementwiseAdditionTest\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/binary/tensor/ElementwiseMultiplicationTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/binary/tensor/ElementwiseMultiplicationTest.java",
"diff": "@@ -32,6 +32,7 @@ import java.util.Arrays;\nimport java.util.Collection;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class ElementwiseMultiplicationTest extends AutomatedTestBase {\nprivate final static String TEST_DIR = \"functions/binary/tensor/\";\nprivate final static String TEST_NAME = \"ElementwiseMultiplicationTest\";\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Aggregate and binary tensor threadsafe |
49,720 | 18.03.2020 22:29:18 | -3,600 | 5d9698605b65572325933e206b367e721187b499 | Updating R version
To resolve failures in builtin package. | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/functionsTests.yml",
"new_path": ".github/workflows/functionsTests.yml",
"diff": "@@ -66,8 +66,10 @@ jobs:\n- name: install R\nrun: |\n- sudo apt-get update\n- sudo apt-get -y install r-base\n+ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9\n+ sudo add-apt-repository \"deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/\"\n+ sudo apt update\n+ sudo apt install r-base\n- name: set R environment\nrun: |\n"
}
] | Java | Apache License 2.0 | apache/systemds | Updating R version
To resolve failures in builtin package. |
49,706 | 19.03.2020 15:23:26 | -3,600 | 09848e9d76e96d0f6075f42b8d3940dc777ec1c1 | [MINOR] Parametized the number of threads for spark local test in config
Minor change enabling parametizing the number of threads
used in spark instructions while testing. Altho it did not solve
problems in some tests it does provide some extra setting for the
system. | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/conf/DMLConfig.java",
"new_path": "src/main/java/org/tugraz/sysds/conf/DMLConfig.java",
"diff": "@@ -81,6 +81,7 @@ public class DMLConfig\npublic static final String SYNCHRONIZE_GPU = \"sysds.gpu.sync.postProcess\"; // boolean: whether to synchronize GPUs after every instruction\npublic static final String EAGER_CUDA_FREE = \"sysds.gpu.eager.cudaFree\"; // boolean: whether to perform eager CUDA free on rmvar\npublic static final String GPU_EVICTION_POLICY = \"sysds.gpu.eviction.policy\"; // string: can be lru, lfu, min_evict\n+ public static final String LOCAL_SPARK_NUM_THREADS = \"sysds.local.spark.number.threads\";\n// Fraction of available memory to use. The available memory is computer when the GPUContext is created\n// to handle the tradeoff on calling cudaMemGetInfo too often.\n@@ -128,6 +129,7 @@ public class DMLConfig\n_defaultVals.put(GPU_MEMORY_ALLOCATOR, \"cuda\");\n_defaultVals.put(AVAILABLE_GPUS, \"-1\");\n_defaultVals.put(GPU_EVICTION_POLICY, \"min_evict\");\n+ _defaultVals.put(LOCAL_SPARK_NUM_THREADS, \"*\"); // * Means it allocates the number of available threads on the local host machine.\n_defaultVals.put(SYNCHRONIZE_GPU, \"false\" );\n_defaultVals.put(EAGER_CUDA_FREE, \"false\" );\n_defaultVals.put(FLOATING_POINT_PRECISION, \"double\" );\n@@ -378,7 +380,7 @@ public class DMLConfig\nCODEGEN, CODEGEN_COMPILER, CODEGEN_OPTIMIZER, CODEGEN_PLANCACHE, CODEGEN_LITERALS,\nSTATS_MAX_WRAP_LEN, PRINT_GPU_MEMORY_INFO,\nAVAILABLE_GPUS, SYNCHRONIZE_GPU, EAGER_CUDA_FREE, FLOATING_POINT_PRECISION, GPU_EVICTION_POLICY,\n- EVICTION_SHADOW_BUFFERSIZE, GPU_MEMORY_ALLOCATOR, GPU_MEMORY_UTILIZATION_FACTOR\n+ LOCAL_SPARK_NUM_THREADS, EVICTION_SHADOW_BUFFERSIZE, GPU_MEMORY_ALLOCATOR, GPU_MEMORY_UTILIZATION_FACTOR\n};\nStringBuilder sb = new StringBuilder();\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/SparkExecutionContext.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/controlprogram/context/SparkExecutionContext.java",
"diff": "@@ -39,6 +39,7 @@ import org.tugraz.sysds.api.mlcontext.MLContextUtil;\nimport org.tugraz.sysds.common.Types.ExecMode;\nimport org.tugraz.sysds.common.Types.ValueType;\nimport org.tugraz.sysds.conf.ConfigurationManager;\n+import org.tugraz.sysds.conf.DMLConfig;\nimport org.tugraz.sysds.hops.OptimizerUtils;\nimport org.tugraz.sysds.lops.Checkpoint;\nimport org.tugraz.sysds.runtime.DMLRuntimeException;\n@@ -214,7 +215,9 @@ public class SparkExecutionContext extends ExecutionContext\nif(DMLScript.USE_LOCAL_SPARK_CONFIG) {\n// For now set 4 cores for integration testing :)\nSparkConf conf = createSystemDSSparkConf()\n- .setMaster(\"local[*]\").setAppName(\"My local integration test app\");\n+ .setMaster(\"local[\" +\n+ ConfigurationManager.getDMLConfig().getTextValue(DMLConfig.LOCAL_SPARK_NUM_THREADS)+\n+ \"]\").setAppName(\"My local integration test app\");\n// This is discouraged in spark but have added only for those testcase that cannot stop the context properly\n// conf.set(\"spark.driver.allowMultipleContexts\", \"true\");\nconf.set(\"spark.ui.enabled\", \"false\");\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/config/SystemDS-config.xml",
"new_path": "src/test/config/SystemDS-config.xml",
"diff": "<!-- custom directory where BLAS libraries are available, experimental feature (options: absolute directory path or none). If set to none, we use standard LD_LIBRARY_PATH. -->\n<sysds.native.blas.directory>none</sysds.native.blas.directory>\n+ <!-- The number of theads for the spark instance artificially selected-->\n+ <sysds.local.spark.number.threads>16</sysds.local.spark.number.threads>\n</root>\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Parametized the number of threads for spark local test in config
Minor change enabling parametizing the number of threads
used in spark instructions while testing. Altho it did not solve
problems in some tests it does provide some extra setting for the
system. |
49,689 | 19.03.2020 19:00:24 | -3,600 | 9321996435d3a61b5b6f0b8c20c13ce2b8545d1c | [SYSTEMDS-232]Fix lineage-codegen support for msvm | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/codegen/SpoofCompiler.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/codegen/SpoofCompiler.java",
"diff": "@@ -585,15 +585,16 @@ public class SpoofCompiler\nHashMap<Long, Pair<Hop[],CNodeTpl>> cplans, HashMap<Long, Pair<Hop[],Class<?>>> cla)\n{\nHashSet<Long> memo = new HashSet<>();\n+ HashMap<Long, Hop> spoofmap = new HashMap<>();\nfor( int i=0; i<orig.size(); i++ ) {\nHop hop = orig.get(i); //w/o iterator because modified\n- rConstructModifiedHopDag(hop, cplans, cla, memo);\n+ rConstructModifiedHopDag(hop, cplans, cla, memo, spoofmap);\n}\nreturn orig;\n}\nprivate static void rConstructModifiedHopDag(Hop hop, HashMap<Long, Pair<Hop[],CNodeTpl>> cplans,\n- HashMap<Long, Pair<Hop[],Class<?>>> clas, HashSet<Long> memo)\n+ HashMap<Long, Pair<Hop[],Class<?>>> clas, HashSet<Long> memo, HashMap<Long, Hop> spoofmap)\n{\nif( memo.contains(hop.getHopID()) )\nreturn; //already processed\n@@ -609,11 +610,15 @@ public class SpoofCompiler\ntmpCla.getValue(), false, tmpCNode.getOutputDimType());\nHop[] inHops = tmpCla.getKey();\n+\nif (DMLScript.LINEAGE) {\n//construct and save lineage DAG from pre-modification HOP DAG\nHop[] roots = !(tmpCNode instanceof CNodeMultiAgg) ? new Hop[]{hop} :\n((CNodeMultiAgg)tmpCNode).getRootNodes().toArray(new Hop[0]);\n- LineageItemUtils.constructLineageFromHops(roots, tmpCla.getValue().getName(), inHops);\n+ LineageItemUtils.constructLineageFromHops(roots, tmpCla.getValue().getName(), inHops, spoofmap);\n+\n+ for (Hop root : roots)\n+ spoofmap.put(hnew.getHopID(), root);\n}\nfor(int i=0; i<inHops.length; i++) {\n@@ -661,7 +666,7 @@ public class SpoofCompiler\n//process hops recursively (parent-child links modified)\nfor( int i=0; i<hnew.getInput().size(); i++ ) {\nHop c = hnew.getInput().get(i);\n- rConstructModifiedHopDag(c, cplans, clas, memo);\n+ rConstructModifiedHopDag(c, cplans, clas, memo, spoofmap);\n}\nmemo.add(hnew.getHopID());\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/lineage/LineageItemUtils.java",
"diff": "@@ -363,7 +363,7 @@ public class LineageItemUtils {\nitem.setVisited();\n}\n- public static void constructLineageFromHops(Hop[] roots, String claName, Hop[] inputs) {\n+ public static void constructLineageFromHops(Hop[] roots, String claName, Hop[] inputs, HashMap<Long, Hop> spoofmap) {\n//probe existence and only generate lineage if non-existing\n//(a fused operator might be used in multiple places of a program)\nif( LineageCodegenItem.getCodegenLTrace(claName) == null ) {\n@@ -372,9 +372,10 @@ public class LineageItemUtils {\n//reset visit status once for entire sub DAG\nfor( Hop root : roots )\nroot.resetVisitStatus();\n+\n//construct lineage dags for roots (potentially overlapping)\nfor( Hop root : roots )\n- rConstructLineageFromHops(root, inputs, operands);\n+ rConstructLineageFromHops(root, inputs, operands, spoofmap);\n//create single lineage item (single root or multiagg)\nLineageItem out = operands.get(roots[0].getHopID());\n@@ -388,52 +389,58 @@ public class LineageItemUtils {\n//cache to avoid reconstruction\nLineageCodegenItem.setCodegenLTrace(claName, out);\n+\n+ for (Hop root : roots)\n+ root.resetVisitStatus();\n}\n}\n- public static void rConstructLineageFromHops(Hop root, Hop[] inputs, Map<Long, LineageItem> operands) {\n+ public static void rConstructLineageFromHops(Hop root, Hop[] inputs, Map<Long, LineageItem> operands, HashMap<Long, Hop> spoofmap) {\nif (root.isVisited())\nreturn;\n- for (int i = 0; i < root.getInput().size(); i++)\n- rConstructLineageFromHops(root.getInput().get(i), inputs, operands);\n-\n- if (HopRewriteUtils.isData(root, OpOpData.TRANSIENTREAD)\n- || ArrayUtils.contains(inputs, root))\n- {\n- LineageItem li = new LineageItem(root.getName(), \"InputPlaceholder\", \"Create\"+String.valueOf(root.getHopID()));\n- operands.put(root.getHopID(), li);\n+ boolean spoof = root instanceof SpoofFusedOp && ArrayUtils.contains(inputs, spoofmap.get(root.getHopID()));\n+ if (ArrayUtils.contains(inputs, root) || spoof) {\n+ Hop tmp = spoof ? spoofmap.get(root.getHopID()) : root;\n+ int pos = ArrayUtils.indexOf(inputs, tmp);\n+ LineageItem li = new LineageItem(String.valueOf(pos), \"InputPlaceholder\", \"Create\"+String.valueOf(root.getHopID()));\n+ operands.put(tmp.getHopID(), li);\nreturn;\n}\n+ for (int i = 0; i < root.getInput().size(); i++)\n+ rConstructLineageFromHops(root.getInput().get(i), inputs, operands, spoofmap);\n+\nLineageItem li = null;\n- ArrayList<LineageItem> LIinputs = new ArrayList<>();\n- root.getInput().forEach(input->LIinputs.add(operands.get(input.getHopID())));\n+ LineageItem[] LIinputs = root.getInput().stream()\n+ .map(h->ArrayUtils.contains(inputs, spoofmap.get(h.getHopID())) ? spoofmap.get(h.getHopID()) : h)\n+ .map(h->operands.get(h.getHopID()))\n+ .toArray(LineageItem[]::new);\n+\nString name = Dag.getNextUniqueVarname(root.getDataType());\nif (root instanceof ReorgOp)\n- li = new LineageItem(name, \"r'\", LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ li = new LineageItem(name, \"r'\", LIinputs);\nelse if (root instanceof UnaryOp) {\nString opcode = UnaryCP.getOpCode(Hop.HopsOpOp1LopsUS.get(((UnaryOp) root).getOp()));\n- li = new LineageItem(name, opcode, LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ li = new LineageItem(name, opcode, LIinputs);\n}\nelse if (root instanceof AggBinaryOp)\n- li = new LineageItem(name, \"ba+*\", LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ li = new LineageItem(name, \"ba+*\", LIinputs);\nelse if (root instanceof BinaryOp)\n- li = new LineageItem(name, Binary.getOpcode(Hop.HopsOpOp2LopsB.get(((BinaryOp)root).getOp())),\n- LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ li = new LineageItem(name, Binary.getOpcode(Hop.HopsOpOp2LopsB.get(((BinaryOp)root).getOp())), LIinputs);\nelse if (root instanceof TernaryOp) {\nString opcode = ((TernaryOp) root).getOp().toString();\n- li = new LineageItem(name, opcode, LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ li = new LineageItem(name, opcode, LIinputs);\n}\nelse if (root instanceof AggUnaryOp) {\nAggOp op = ((AggUnaryOp) root).getOp();\nDirection dir = ((AggUnaryOp) root).getDirection();\nString opcode = PartialAggregate.getOpcode(op, dir);\n- li = new LineageItem(name, opcode, LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ li = new LineageItem(name, opcode, LIinputs);\n}\nelse if (root instanceof IndexingOp)\n- li = new LineageItem(name, \"rightIndex\", LIinputs.toArray(new LineageItem[LIinputs.size()]));\n+ li = new LineageItem(name, \"rightIndex\", LIinputs);\nelse if (root instanceof SpoofFusedOp)\nli = LineageCodegenItem.getCodegenLTrace(((SpoofFusedOp) root).getClassName());\n@@ -449,9 +456,9 @@ public class LineageItemUtils {\n}\nelse\nthrow new DMLRuntimeException(\"Unsupported hop: \"+root.getOpString());\n+\n//TODO: include all the other hops\noperands.put(root.getHopID(), li);\n-\nroot.setVisited();\n}\n@@ -549,7 +556,7 @@ public class LineageItemUtils {\n//process children until old item found, then replace\nfor(int i=0; i<current.getInputs().length; i++) {\nLineageItem tmp = current.getInputs()[i];\n- if( tmp.equals(liOld) )\n+ if (liOld.equals(tmp))\ncurrent.getInputs()[i] = liNew;\nelse\nrReplace(tmp, liOld, liNew);\n@@ -558,19 +565,26 @@ public class LineageItemUtils {\n}\npublic static void replaceDagLeaves(ExecutionContext ec, LineageItem root, CPOperand[] newLeaves) {\n- LineageItem[] newLIleaves = LineageItemUtils.getLineage(ec, newLeaves);\n- HashMap<String, LineageItem> newLImap = new HashMap<>();\n- for (int i=0; i<newLIleaves.length; i++)\n- newLImap.put(newLeaves[i].getName(), newLIleaves[i]);\n-\n- //find and replace the old leaves\n- HashSet<LineageItem> oldLeaves = new HashSet<>();\n+ //find and replace the placeholder leaves\n+ root.resetVisitStatus();\n+ rReplaceDagLeaves(root, LineageItemUtils.getLineage(ec, newLeaves));\nroot.resetVisitStatus();\n- rGetDagLeaves(oldLeaves, root);\n- for (LineageItem leaf : oldLeaves) {\n- if (leaf.getType() != LineageItemType.Literal)\n- replace(root, leaf, newLImap.get(leaf.getName()));\n}\n+\n+ public static void rReplaceDagLeaves(LineageItem root, LineageItem[] newleaves) {\n+ if (root.isVisited() || root.isLeaf())\n+ return;\n+\n+ for (int i=0; i<root.getInputs().length; i++) {\n+ LineageItem li = root.getInputs()[i];\n+ if (li.isLeaf() && li.getType() != LineageItemType.Literal)\n+ //order-preserving replacement. Name represents relative position.\n+ root.getInputs()[i] = newleaves[Integer.parseInt(li.getName())];\n+ else\n+ rReplaceDagLeaves(li, newleaves);\n+ }\n+\n+ root.setVisited();\n}\npublic static void rGetDagLeaves(HashSet<LineageItem> leaves, LineageItem root) {\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-232]Fix lineage-codegen support for msvm |
49,738 | 19.03.2020 20:20:45 | -3,600 | 4cc95a6f2024fdef7267879fa8212d7ed43acd2a | [MINOR] Additional fixes functions tests (data-rand/tensor, codegen) | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/applications/ArimaTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/applications/ArimaTest.java",
"diff": "@@ -37,6 +37,7 @@ import org.tugraz.sysds.test.AutomatedTestBase;\nimport org.tugraz.sysds.test.TestUtils;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class ArimaTest extends AutomatedTestBase {\nprotected final static String TEST_DIR = \"applications/arima_box-jenkins/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmARIMA.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmARIMA.java",
"diff": "@@ -29,6 +29,7 @@ import org.tugraz.sysds.test.applications.ArimaTest;\nimport java.io.File;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class AlgorithmARIMA extends ArimaTest\n{\nprivate final static String LOCAL_TEST_DIR = \"functions/codegenalg/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmMDABivar.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmMDABivar.java",
"diff": "@@ -29,6 +29,7 @@ import org.tugraz.sysds.test.applications.MDABivariateStatsTest;\nimport java.io.File;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class AlgorithmMDABivar extends MDABivariateStatsTest\n{\nprivate final static String LOCAL_TEST_DIR = \"functions/codegenalg/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/data/rand/RandRuntimePlatformTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/data/rand/RandRuntimePlatformTest.java",
"diff": "@@ -44,9 +44,9 @@ import org.tugraz.sysds.test.TestUtils;\n*/\n@RunWith(value = Parameterized.class)\[email protected]\npublic class RandRuntimePlatformTest extends AutomatedTestBase\n{\n-\nprivate final static String TEST_DIR = \"functions/data/\";\nprivate final static String TEST_NAME = \"RandRuntimePlatformTest\";\nprivate final static String TEST_CLASS_DIR = TEST_DIR + RandRuntimePlatformTest.class.getSimpleName() + \"/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/data/rand/SampleTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/data/rand/SampleTest.java",
"diff": "@@ -37,6 +37,7 @@ import org.tugraz.sysds.test.TestConfiguration;\n*\n*/\n@RunWith(value = Parameterized.class)\[email protected]\npublic class SampleTest extends AutomatedTestBase\n{\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/data/rand/SequenceTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/data/rand/SequenceTest.java",
"diff": "@@ -40,6 +40,7 @@ import java.util.HashMap;\n* runtime platforms.\n*/\n@RunWith(value = Parameterized.class)\[email protected]\npublic class SequenceTest extends AutomatedTestBase\n{\nprivate final static String TEST_DIR = \"functions/data/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/data/tensor/SqlTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/data/tensor/SqlTest.java",
"diff": "@@ -34,6 +34,7 @@ import java.util.Arrays;\nimport java.util.Collection;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class SqlTest extends AutomatedTestBase {\nprivate final static String TEST_DIR = \"functions/data/\";\nprivate final static String TEST_NAME = \"SqlTest\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/data/tensor/TensorConstructionTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/data/tensor/TensorConstructionTest.java",
"diff": "@@ -30,6 +30,7 @@ import java.util.Arrays;\nimport java.util.Collection;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class TensorConstructionTest extends AutomatedTestBase {\nprivate final static String TEST_DIR = \"functions/data/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/data/tensor/TensorRandTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/data/tensor/TensorRandTest.java",
"diff": "@@ -31,6 +31,7 @@ import java.util.Arrays;\nimport java.util.Collection;\n@RunWith(value = Parameterized.class)\[email protected]\npublic class TensorRandTest extends AutomatedTestBase {\nprivate final static String TEST_DIR = \"functions/data/\";\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/scripts/functions/codegen/cellwisetmpl21.R",
"new_path": "src/test/scripts/functions/codegen/cellwisetmpl21.R",
"diff": "@@ -27,6 +27,7 @@ X = matrix(seq(7, 1006), 500, 2, byrow=TRUE);\nR1 = (X/3) %% 0.6;\nR2 = (X/3) %/% 0.6;\n+R1 = ifelse(R1<1e-7, 0, R1);\nR = (R1 > 0) * R2\nwriteMM(as(R,\"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Additional fixes functions tests (data-rand/tensor, codegen) |
49,738 | 21.03.2020 23:50:08 | -3,600 | 5b8298b6287f53e999b4465ddf6ff601be1775d1 | Cleanup intersect builtin and related tests
This patch removes unnecessary operations from the recently added
intersect builtin function and fixes the related tests which only
checked result correctness for a subset of test cases. | [
{
"change_type": "MODIFY",
"old_path": "scripts/builtin/intersect.dml",
"new_path": "scripts/builtin/intersect.dml",
"diff": "@@ -48,6 +48,5 @@ m_intersect = function(Matrix[Double] X, Matrix[Double] Y)\nI = X[1:n,] * Y[1:n,]\n# reconstruct integer values and create output\n- Iv = I * seq(1,n)\n- R = removeEmpty(target=Iv, margin=\"rows\", select=I)\n+ R = removeEmpty(target=seq(1,n), margin=\"rows\", select=I)\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/TestUtils.java",
"new_path": "src/test/java/org/tugraz/sysds/test/TestUtils.java",
"diff": "@@ -2340,6 +2340,14 @@ public class TestUtils\nreturn nnz;\n}\n+ public static double[][] seq(int from, int to, int incr) {\n+ int len = (int)UtilFunctions.getSeqLength(from, to, incr);\n+ double[][] ret = new double[len][1];\n+ for(int i=0, val=from; val<=to; i++, val+=incr)\n+ ret[i][0] = val;\n+ return ret;\n+ }\n+\npublic static void shutdownThreads(Thread... ts) {\nfor( Thread t : ts )\nshutdownThread(t);\n"
},
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinIntersectionTest.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/builtin/BuiltinIntersectionTest.java",
"diff": "package org.tugraz.sysds.test.functions.builtin;\n-import org.junit.Assert;\nimport org.junit.Test;\nimport org.tugraz.sysds.common.Types;\nimport org.tugraz.sysds.lops.LopProperties;\n-import org.tugraz.sysds.runtime.matrix.data.MatrixValue;\n+import org.tugraz.sysds.runtime.matrix.data.MatrixValue.CellIndex;\nimport org.tugraz.sysds.test.AutomatedTestBase;\nimport org.tugraz.sysds.test.TestConfiguration;\nimport org.tugraz.sysds.test.TestUtils;\n-import java.util.Arrays;\nimport java.util.HashMap;\n-public class BuiltinIntersectionTest extends AutomatedTestBase {\n+public class BuiltinIntersectionTest extends AutomatedTestBase\n+{\nprivate final static String TEST_NAME = \"intersection\";\nprivate final static String TEST_DIR = \"functions/builtin/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + BuiltinIntersectionTest.class.getSimpleName() + \"/\";\n@@ -43,61 +42,39 @@ public class BuiltinIntersectionTest extends AutomatedTestBase {\npublic void testIntersect1CP() {\ndouble[][] X = {{12},{22},{13},{4},{6},{7},{8},{9},{12},{12}};\ndouble[][] Y = {{1},{2},{11},{12},{13},{18},{20},{21},{12}};\n- X = TestUtils.round(X);\n- Y = TestUtils.round(Y);\n- runIntersectTest(X, Y, LopProperties.ExecType.CP);\n+ double[][] expected = {{12},{13}};\n+ runIntersectTest(X, Y, expected, LopProperties.ExecType.CP);\n}\n@Test\npublic void testIntersect1Spark() {\ndouble[][] X = {{12},{22},{13},{4},{6},{7},{8},{9},{12},{12}};\ndouble[][] Y = {{1},{2},{11},{12},{13},{18},{20},{21},{12}};\n- X = TestUtils.round(X);\n- Y = TestUtils.round(Y);\n- runIntersectTest(X, Y, LopProperties.ExecType.SPARK);\n+ double[][] expected = {{12},{13}};\n+ runIntersectTest(X, Y, expected, LopProperties.ExecType.SPARK);\n}\n@Test\npublic void testIntersect2CP() {\n- double[][] X = new double[50][1];\n- double[][] Y = new double[50][1];\n- for(int i =0, j=2; i<50; i++, j+=4)\n- X[i][0] = j;\n- for(int i =0, j=2; i<50; i++, j+=2)\n- Y[i][0] = j;\n- runIntersectTest(X, Y, LopProperties.ExecType.CP);\n- HashMap<MatrixValue.CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"C\");\n- Object[] out = dmlfile.values().toArray();\n- Arrays.sort(out);\n- for(int i = 0; i< out.length; i++)\n- Assert.assertEquals(out[i], Double.valueOf(X[i][0]));\n+ double[][] X = TestUtils.seq(2, 200, 4);\n+ double[][] Y = TestUtils.seq(2, 100, 2);\n+ double[][] expected = TestUtils.seq(2, 100, 4);\n+ runIntersectTest(X, Y, expected, LopProperties.ExecType.CP);\n}\n@Test\npublic void testIntersect2Spark() {\n- double[][] X = new double[50][1];\n- double[][] Y = new double[50][1];\n- for(int i =0, j=2; i<50; i++, j+=4)\n- X[i][0] = j;\n- for(int i =0, j=2; i<50; i++, j+=2)\n- Y[i][0] = j;\n- runIntersectTest(X, Y, LopProperties.ExecType.SPARK);\n- HashMap<MatrixValue.CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"C\");\n- Object[] out = dmlfile.values().toArray();\n- Arrays.sort(out);\n- for(int i = 0; i< out.length; i++)\n- Assert.assertEquals(out[i], Double.valueOf(X[i][0]));\n+ double[][] X = TestUtils.seq(2, 200, 4);\n+ double[][] Y = TestUtils.seq(2, 100, 2);\n+ double[][] expected = TestUtils.seq(2, 100, 4);\n+ runIntersectTest(X, Y, expected, LopProperties.ExecType.SPARK);\n}\n-\n-\n- private void runIntersectTest(double X[][], double Y[][], LopProperties.ExecType instType)\n+ private void runIntersectTest(double X[][], double Y[][], double[][] expected, LopProperties.ExecType instType)\n{\nTypes.ExecMode platformOld = setExecMode(instType);\n- //TODO compare with R instead of custom output comparison\n- try\n- {\n+ try {\nloadTestConfiguration(getTestConfiguration(TEST_NAME));\nString HOME = SCRIPT_DIR + TEST_DIR;\nfullDMLScriptName = HOME + TEST_NAME + \".dml\";\n@@ -107,7 +84,15 @@ public class BuiltinIntersectionTest extends AutomatedTestBase {\nwriteInputMatrixWithMTD(\"X\", X, true);\nwriteInputMatrixWithMTD(\"Y\", Y, true);\n+ //run test\nrunTest(true, false, null, -1);\n+\n+ //compare expected results\n+ HashMap<CellIndex, Double> R = new HashMap<>();\n+ for(int i=0; i<expected.length; i++)\n+ R.put(new CellIndex(i+1,1), expected[i][0]);\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"C\");\n+ TestUtils.compareMatrices(dmlfile, R, 1e-10, \"dml\", \"expected\");\n}\nfinally {\nrtplatform = platformOld;\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-196] Cleanup intersect builtin and related tests
This patch removes unnecessary operations from the recently added
intersect builtin function and fixes the related tests which only
checked result correctness for a subset of test cases. |
49,720 | 22.03.2020 13:44:17 | -3,600 | 023208d470fa37b53f7b74b445a553de6a15fe6f | [Minor] Fix null value handling | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/FrameBlock.java",
"new_path": "src/main/java/org/tugraz/sysds/runtime/matrix/data/FrameBlock.java",
"diff": "@@ -1791,7 +1791,7 @@ public class FrameBlock implements Writable, CacheBlock, Externalizable\n//read a not null sample value\nwhile (dataValue == null) {\nint randomIndex = ThreadLocalRandom.current().nextInt(0, rows - 1);\n- dataValue = obj.get(randomIndex).toString().trim().replace(\"\\\"\", \"\").toLowerCase();\n+ dataValue = ((obj.get(randomIndex) != null)?obj.get(randomIndex).toString().trim().replace(\"\\\"\", \"\").toLowerCase():null);\n}\nif (isType(dataValue) == ValueType.STRING) {\n"
}
] | Java | Apache License 2.0 | apache/systemds | [Minor] Fix null value handling |
49,746 | 22.03.2020 20:48:45 | -3,600 | 56798474386434e6a17739640d311fca58f5d72e | [MINOR] Switch to absolute import paths and update docs of python bindings
Closes | [
{
"change_type": "MODIFY",
"old_path": "src/main/python/docs/source/install.rst",
"new_path": "src/main/python/docs/source/install.rst",
"diff": "@@ -31,13 +31,13 @@ SystemDS is a java-project, the `pip` package contains all the necessary `jars`,\nbut you will need java version 8 installed. Do not use an older or newer\nversion of java, because SystemDS is non compatible with other java versions.\n-Check the output of ``java -version``. Output should look similiar to::\n+Check the output of ``java -version``. The output should look similar to::\nopenjdk version \"1.8.0_242\"\nOpenJDK Runtime Environment (build 1.8.0_242-b08)\nOpenJDK 64-Bit Server VM (build 25.242-b08, mixed mode)\n-The important part is in the first line ``opendjdk version \"1.8.0_xxx\"``,\n+The important part is in the first line ``openjdk version \"1.8.0_xxx\"``,\nplease make sure this is the case.\n@@ -54,16 +54,17 @@ Install Dependencies\nOnce installed you please verify your version numbers.\nAdditionally you have to install a few python packages.\n-Note depending on your installation you might need to use pip3 instead of pip.\n+Note depending on your installation you might need to use pip3 instead of pip::\n-- ``pip install numpy py4j wheel``\n+ pip install numpy py4j wheel\nThen to build the system you do the following\n-- Clone the Git Repository <https://github.com/tugraz-isds/systemds.git>.\n+- Clone the Git Repository: https://github.com/tugraz-isds/systemds.git\n- Open an terminal at the root of the repository.\n- Package the Java code using the ``mvn package`` command\n-- ``cd src/main/python`` to point at the root of the SystemDS python library.\n-- Execute ``python create_python_dist.py``\n+- ``cd src/main/python`` to point at the root of the SystemDS Python library.\n+- Copy `jars` with ``python pre_setup.py``\n+- Install with ``pip install .``\nAfter this you are ready to go.\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/docs/source/matrix.rst",
"new_path": "src/main/python/docs/source/matrix.rst",
"diff": ".. limitations under the License.\n.. ------------------------------------------------------------------------------\n+\nMatrix API\n==========\nOperationNode\n-------------\n+ .. todo\n+ The explanation for overloade methods seems weird and does not really describe which\n+ methods we mean (magic methods for operators like `+`, `*` etc.).\n+ Also I don't understand why that would mean that they return an ``OpeartionNode``.\n+\nAn ``OperationNode`` represents an operation that executes in SystemDS.\nMost methods are overloaded for ``OperationNode``.\nThis means that they return an ``OperationNode``.\n-To get the result from an `OperationNode` you simply call ``.compute()`` on it, thereby getting the numpy equivalent result.\n-Even comparisons like ``__eq__``, ``__lt__`` etc. gives `OperationNode`s.\n+To get the result from an ``OperationNode`` you simply call ``.compute()`` on it, thereby getting the numpy equivalent result.\n+Even comparisons like ``__eq__``, ``__lt__`` etc. return ``OperationNode``.\n.. note::\n@@ -37,14 +43,14 @@ Even comparisons like ``__eq__``, ``__lt__`` etc. gives `OperationNode`s.\nMatrix\n------\n-A `Matrix` is represented either by an `OperationNode`, or the derived class `Matrix`.\n+A ``Matrix`` is represented either by an ``OperationNode``, or the derived class ``Matrix``.\nAn Matrix can recognized it by checking the ``output_type`` of the object.\nMatrices are the most fundamental objects we operate on.\nIf one generate the matrix in SystemDS directly via a function call,\n-it can be used in an function which will generate an `OperationNode` e.g. `federated`, `full`, `seq`.\n+it can be used in an function which will generate an ``OperationNode`` e.g. ``federated``, ``full``, ``seq``.\n-If we want to work on an numpy array we need to use the class `Matrix`.\n+If we want to work on an numpy array we need to use the class ``Matrix``.\n.. autoclass:: systemds.matrix.Matrix\n:members:\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/docs/source/simple_examples.rst",
"new_path": "src/main/python/docs/source/simple_examples.rst",
"diff": "@@ -25,15 +25,15 @@ Matrix Operations\nMaking use of SystemDS, let us multiply an Matrix with an scalar::\n# Import full\n- >>> from systemds.matrix import full\n+ from systemds.matrix import full\n# Full generates a matrix completely filled with one number.\n# Generate a 5x10 matrix filled with 4.2\n- >>> m = full((5, 10), 4.20)\n+ m = full((5, 10), 4.20)\n# multiply with scala. Nothing is executed yet!\n- >>> m_res = m * 3.1\n+ m_res = m * 3.1\n# Do the calculation in SystemDS by calling compute().\n# The returned value is an numpy array that can be directly printed.\n- >>> print(m_res.compute())\n+ print(m_res.compute())\nAs output we get::\n@@ -47,21 +47,21 @@ The Python SystemDS package is compatible with numpy arrays.\nLet us do a quick element-wise matrix multiplication of numpy arrays with SystemDS.\nRemember to first start up a new terminal::\n- >>> import numpy as np # import numpy\n- >>> from systemds.matrix import Matrix # import Matrix class\n+ import numpy as np # import numpy\n+ from systemds.matrix import Matrix # import Matrix class\n# create a random array\n- >>> m1 = np.array(np.random.randint(100, size=5 * 5) + 1.01, dtype=np.double)\n- >>> m1.shape = (5, 5)\n+ m1 = np.array(np.random.randint(100, size=5 * 5) + 1.01, dtype=np.double)\n+ m1.shape = (5, 5)\n# create another random array\n- >>> m2 = np.array(np.random.randint(5, size=5 * 5) + 1, dtype=np.double)\n- >>> m2.shape = (5, 5)\n+ m2 = np.array(np.random.randint(5, size=5 * 5) + 1, dtype=np.double)\n+ m2.shape = (5, 5)\n# element-wise matrix multiplication, note that nothing is executed yet!\n- >>> m_res = Matrix(m1) * Matrix(m2)\n+ m_res = Matrix(m1) * Matrix(m2)\n# lets do the actual computation in SystemDS! We get an numpy array as a result\n- >>> m_res_np = m_res.compute()\n- >>> print(m_res_np)\n+ m_res_np = m_res.compute()\n+ print(m_res_np)\nMore complex operations\n-----------------------\n@@ -71,22 +71,22 @@ One example of this is l2SVM.\nhigh level functions for Data-Scientists, lets take a look at l2svm::\n# Import numpy and SystemDS matrix\n- >>> import numpy as np\n- >>> from systemds.matrix import Matrix\n+ import numpy as np\n+ from systemds.matrix import Matrix\n# Set a seed\n- >>> np.random.seed(0)\n+ np.random.seed(0)\n# Generate random features and labels in numpy\n# This can easily be exchanged with a data set.\n- >>> features = np.array(np.random.randint(100, size=10 * 10) + 1.01, dtype=np.double)\n- >>> features.shape = (10, 10)\n- >>> labels = np.zeros((10, 1))\n+ features = np.array(np.random.randint(100, size=10 * 10) + 1.01, dtype=np.double)\n+ features.shape = (10, 10)\n+ labels = np.zeros((10, 1))\n# l2svm labels can only be 0 or 1\n- >>> for i in range(10):\n- >>> if np.random.random() > 0.5:\n- >>> labels[i][0] = 1\n+ for i in range(10):\n+ if np.random.random() > 0.5:\n+ labels[i][0] = 1\n# compute our model\n- >>> model = Matrix(features).l2svm(Matrix(labels)).compute()\n- >>> print(model)\n+ model = Matrix(features).l2svm(Matrix(labels)).compute()\n+ print(model)\nThe output should be similar to::\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/systemds/matrix/matrix.py",
"new_path": "src/main/python/systemds/matrix/matrix.py",
"diff": "@@ -22,9 +22,9 @@ from typing import Union, Optional, Iterable, Dict, Tuple, Sequence\nimport numpy as np\nfrom py4j.java_gateway import JVMView, JavaObject\n-from ..utils.converters import numpy_to_matrix_block\n-from ..script_building.dag import VALID_INPUT_TYPES\n-from .operation_node import OperationNode\n+from systemds.utils.converters import numpy_to_matrix_block\n+from systemds.script_building.dag import VALID_INPUT_TYPES\n+from systemds.matrix.operation_node import OperationNode\n# TODO maybe instead of having a new class we could have a function `matrix` instead, adding behaviour to\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/systemds/matrix/operation_node.py",
"new_path": "src/main/python/systemds/matrix/operation_node.py",
"diff": "import numpy as np\nfrom py4j.java_gateway import JVMView, JavaObject\n-\n-from ..utils.helpers import get_gateway, create_params_string\n-from ..utils.converters import matrix_block_to_numpy\n-from ..script_building.script import DMLScript\n-from ..script_building.dag import OutputType, DAGNode, VALID_INPUT_TYPES\nfrom typing import Union, Optional, Iterable, Dict, Sequence\n+from systemds.utils.helpers import get_gateway, create_params_string\n+from systemds.utils.converters import matrix_block_to_numpy\n+from systemds.script_building.script import DMLScript\n+from systemds.script_building.dag import OutputType, DAGNode, VALID_INPUT_TYPES\n+\nBINARY_OPERATIONS = ['+', '-', '/', '//', '*', '<', '<=', '>', '>=', '==', '!=']\n# TODO add numpy array\nVALID_ARITHMETIC_TYPES = Union[DAGNode, int, float]\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/systemds/script_building/script.py",
"new_path": "src/main/python/systemds/script_building/script.py",
"diff": "# limitations under the License.\n# ------------------------------------------------------------------------------\n-from typing import Any, Dict, Optional, Collection, KeysView, Union\n+from typing import Any, Collection, KeysView\nfrom py4j.java_collections import JavaArray\nfrom py4j.java_gateway import JavaObject\n-from ..utils.helpers import get_gateway\n-from ..script_building.dag import DAGNode, VALID_INPUT_TYPES\n+from systemds.utils.helpers import get_gateway\n+from systemds.script_building.dag import DAGNode, VALID_INPUT_TYPES\n+from typing import Union, Optional, Dict\nclass DMLScript:\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/tests/test_l2svm.py",
"new_path": "src/main/python/tests/test_l2svm.py",
"diff": "@@ -27,7 +27,7 @@ sys.path.insert(0, path)\nfrom systemds.matrix import Matrix\n-class TestAPI(unittest.TestCase):\n+class TestL2svm(unittest.TestCase):\ndef test_10x10(self):\nfeatures, labels = generate_matrices_for_l2svm(10, seed=1304)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Switch to absolute import paths and update docs of python bindings
Closes #124 |
49,693 | 23.03.2020 00:33:50 | -3,600 | 732f287f0668c5c60564dd6f5412f27f72f6a57b | [MINOR] Make github workflow actions for python tests pass successfully
* Ignore unclosed socket warning
* Explicitly close py4j gateway
* Send return to stdin of the gateway process
* Wait three seconds between launching tests to give the gateway socket time to shutdown
Closes | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/python.yml",
"new_path": ".github/workflows/python.yml",
"diff": "@@ -73,7 +73,15 @@ jobs:\nls tests/\necho \"Beginning tests\"\npython tests/test_matrix_binary_op.py\n+ echo \"Exit Status: \" $?\n+ sleep 3\npython tests/test_matrix_aggregations.py\n+ echo \"Exit Status: \" $?\n+ sleep 3\npython tests/test_l2svm.py\n+ echo \"Exit Status: \" $?\npython tests/test_lineagetrace.py\n+ sleep 3\n+ echo \"Exit Status: \" $?\npython tests/test_l2svm_lineage.py\n+ echo \"Exit Status: \" $?\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/systemds/utils/helpers.py",
"new_path": "src/main/python/systemds/utils/helpers.py",
"diff": "@@ -25,6 +25,7 @@ from py4j.protocol import Py4JNetworkError\nJAVA_GATEWAY = None\nMODULE_NAME = 'systemds'\n+PROC = None\ndef get_gateway() -> JavaGateway:\n@@ -35,6 +36,7 @@ def get_gateway() -> JavaGateway:\n:return: the java gateway object\n\"\"\"\nglobal JAVA_GATEWAY\n+ global PROC\nif JAVA_GATEWAY is None:\ntry:\nJAVA_GATEWAY = JavaGateway(eager_load=True)\n@@ -47,13 +49,21 @@ def get_gateway() -> JavaGateway:\nsystemds_cp = os.path.join(systemds_java_path, '*')\nclasspath = cp_separator.join([lib_cp, systemds_cp])\nprocess = subprocess.Popen(['java', '-cp', classpath, 'org.tugraz.sysds.pythonapi.PythonDMLScript'],\n- stdout=subprocess.PIPE)\n+ stdout=subprocess.PIPE, stdin=subprocess.PIPE)\nprint(process.stdout.readline()) # wait for 'Gateway Server Started\\n' written by server\nassert process.poll() is None, \"Could not start JMLC server\"\nJAVA_GATEWAY = JavaGateway()\n+ PROC = process\nreturn JAVA_GATEWAY\n+def shutdown():\n+ global JAVA_GATEWAY\n+ global PROC\n+ JAVA_GATEWAY.shutdown()\n+ PROC.communicate(input=b'\\n')\n+\n+\ndef create_params_string(unnamed_parameters: Iterable[str], named_parameters: Dict[str, str]) -> str:\n\"\"\"\nCreates a string for providing parameters in dml. Basically converts both named and unnamed parameter\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/tests/test_l2svm.py",
"new_path": "src/main/python/tests/test_l2svm.py",
"diff": "# limitations under the License.\n# ------------------------------------------------------------------------------\n+import warnings\nimport unittest\nimport os\n@@ -25,10 +26,20 @@ import numpy as np\npath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"../\")\nsys.path.insert(0, path)\nfrom systemds.matrix import Matrix\n-\n+from systemds.utils import helpers\nclass TestL2svm(unittest.TestCase):\n+ def setUp(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\n+ def tearDown(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\ndef test_10x10(self):\nfeatures, labels = generate_matrices_for_l2svm(10, seed=1304)\n# TODO calculate reference\n@@ -57,4 +68,5 @@ def generate_matrices_for_l2svm(dims: int, seed: int = 1234) -> Tuple[Matrix, Ma\nif __name__ == \"__main__\":\n- unittest.main()\n+ unittest.main(exit=False)\n+ helpers.shutdown()\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/tests/test_l2svm_lineage.py",
"new_path": "src/main/python/tests/test_l2svm_lineage.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------------\n+\n+import warnings\nimport unittest\nimport re\n-\nimport os\nimport sys\nfrom typing import Tuple\n-\nimport numpy as np\npath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"../\")\nsys.path.insert(0, path)\nfrom systemds.matrix import Matrix\n-\n+from systemds.utils import helpers\nclass TestAPI(unittest.TestCase):\n+\n+ def setUp(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\n+ def tearDown(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\ndef test_getl2svm_lineage(self):\nfeatures, labels = generate_matrices_for_l2svm(10, seed=1304)\n#get the lineage trace\n@@ -64,5 +75,5 @@ def reVars(s: str) -> str:\nif __name__ == \"__main__\":\n- unittest.main()\n-\n+ unittest.main(exit=False)\n+ helpers.shutdown()\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/tests/test_lineagetrace.py",
"new_path": "src/main/python/tests/test_lineagetrace.py",
"diff": "# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------------\n-import unittest\n+import warnings\nimport unittest\nimport os\nimport sys\n-import numpy as np\nimport re\npath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"../\")\nsys.path.insert(0, path)\nfrom systemds.matrix import Matrix, full, seq\n+from systemds.utils import helpers\nclass TestLineageTrace(unittest.TestCase):\n+\n+ def setUp(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\n+ def tearDown(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\ndef test_compare_trace1(self): #test getLineageTrace() on an intermediate\nm = full((5, 10), 4.20)\nm_res = m * 3.1\n@@ -51,5 +62,5 @@ def reVars(s: str) -> str:\nreturn s\nif __name__ == \"__main__\":\n- unittest.main()\n-\n+ unittest.main(exit=False)\n+ helpers.shutdown()\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/tests/test_matrix_aggregations.py",
"new_path": "src/main/python/tests/test_matrix_aggregations.py",
"diff": "# Make the `systemds` package importable\nimport os\nimport sys\n+import warnings\n+import unittest\n+import numpy as np\npath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"../\")\nsys.path.insert(0, path)\n-import unittest\n-import numpy as np\n-\nfrom systemds.matrix import Matrix, full, seq\n+from systemds.utils import helpers\ndim = 5\nm1 = np.array(np.random.randint(100, size=dim * dim) + 1.01, dtype=np.double)\n@@ -43,6 +44,16 @@ m2.shape = (dim, dim)\nclass TestMatrixAggFn(unittest.TestCase):\n+ def setUp(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\n+ def tearDown(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\ndef test_sum1(self):\nself.assertTrue(np.allclose(Matrix(m1).sum().compute(), m1.sum()))\n@@ -78,4 +89,5 @@ class TestMatrixAggFn(unittest.TestCase):\nif __name__ == \"__main__\":\n- unittest.main()\n+ unittest.main(exit=False)\n+ helpers.shutdown()\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/python/tests/test_matrix_binary_op.py",
"new_path": "src/main/python/tests/test_matrix_binary_op.py",
"diff": "# Make the `systemds` package importable\nimport os\nimport sys\n+import warnings\n+import unittest\n+import numpy as np\npath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"../\")\nsys.path.insert(0, path)\n-import unittest\nfrom systemds.matrix import Matrix\n-import numpy as np\n+from systemds.utils import helpers\ndim = 5\nm1 = np.array(np.random.randint(100, size=dim * dim) + 1.01, dtype=np.double)\n@@ -42,6 +44,16 @@ s = 3.02\nclass TestBinaryOp(unittest.TestCase):\n+ def setUp(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\n+ def tearDown(self):\n+ warnings.filterwarnings(action=\"ignore\",\n+ message=\"unclosed\",\n+ category=ResourceWarning)\n+\ndef test_plus(self):\nself.assertTrue(np.allclose((Matrix(m1) + Matrix(m2)).compute(), m1 + m2))\n@@ -89,4 +101,5 @@ class TestBinaryOp(unittest.TestCase):\nif __name__ == \"__main__\":\n- unittest.main()\n+ unittest.main(exit=False)\n+ helpers.shutdown()\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Make github workflow actions for python tests pass successfully
* Ignore unclosed socket warning
* Explicitly close py4j gateway
* Send return to stdin of the gateway process
* Wait three seconds between launching tests to give the gateway socket time to shutdown
Closes #125 |
49,706 | 23.03.2020 15:48:40 | -3,600 | 74b78d3a681656ffeb058193c9d6ba684c90787e | [MINOR] Pipe stderror to out for tests in docker | [
{
"change_type": "MODIFY",
"old_path": "docker/entrypoint.sh",
"new_path": "docker/entrypoint.sh",
"diff": "@@ -40,7 +40,7 @@ log=\"/tmp/sysdstest.log\"\necho \"Starting Tests\"\n-grepvals=\"$(mvn surefire:test -DskipTests=false -Dtest=$1 | tee $log | grep $grep_args)\"\n+grepvals=\"$(mvn surefire:test -DskipTests=false -Dtest=$1 2>&1 | tee $log | grep $grep_args)\"\nif [[ $grepvals == *\"SUCCESS\"* ]]; then\necho \"--------------------- last 100 lines from test ------------------------\"\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Pipe stderror to out for tests in docker |
49,693 | 23.03.2020 18:05:01 | -3,600 | 4d085ad5c9df30c54d4de7f412f327df5cb7b84b | [MINOR] Omit producing code for a conditional with SpoofOuterProduct | [
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/codegen/template/TemplateOuterProduct.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/codegen/template/TemplateOuterProduct.java",
"diff": "@@ -129,13 +129,21 @@ public class TemplateOuterProduct extends TemplateBase {\nrConstructCplan(hop, memo, tmp, inHops, inHops2, compileLiterals);\nhop.resetVisitStatus();\n+ // Remove CNodes that would produce the following unnecessary\n+ // line of code: \"double tmpX = (a != 0) ? 1 : 0\"\n+ // This is unnecessary with SpoofOuterProduct, since code for tmpX==0\n+ // is not invoked anyway.\n+ long outputHopID = hop.getHopID();\n+ if(hop instanceof BinaryOp)\n+ outputHopID = TemplateUtils.skipConditionalInOuterProduct(hop, tmp, inHops);\n+\n//reorder inputs (ensure matrix is first input)\nHop X = inHops2.get(\"_X\");\nHop U = inHops2.get(\"_U\");\nHop V = inHops2.get(\"_V\");\nLinkedList<Hop> sinHops = new LinkedList<>(inHops);\n- // order of adds and removes is important here\n+ // order of adds and removes is important here (all removes before adds)\nsinHops.remove(V);\nsinHops.remove(U);\nsinHops.remove(X);\n@@ -149,7 +157,7 @@ public class TemplateOuterProduct extends TemplateBase {\nif( in != null )\ninputs.add(tmp.get(in.getHopID()));\n- CNode output = tmp.get(hop.getHopID());\n+ CNode output = tmp.get(outputHopID);\nCNodeOuterProduct tpl = new CNodeOuterProduct(inputs, output, mmtsj);\ntpl.setOutProdType(TemplateUtils.getOuterProductType(X, U, V, hop));\ntpl.setTransposeOutput(!HopRewriteUtils.isTransposeOperation(hop)\n"
},
{
"change_type": "MODIFY",
"old_path": "src/main/java/org/tugraz/sysds/hops/codegen/template/TemplateUtils.java",
"new_path": "src/main/java/org/tugraz/sysds/hops/codegen/template/TemplateUtils.java",
"diff": "package org.tugraz.sysds.hops.codegen.template;\n-import java.util.ArrayList;\n-import java.util.HashMap;\n-import java.util.HashSet;\n-import java.util.Map;\n-import java.util.Set;\n+import java.util.*;\nimport org.apache.commons.lang.ArrayUtils;\nimport org.apache.commons.lang3.mutable.MutableInt;\n@@ -328,6 +324,48 @@ public class TemplateUtils\n}\n}\n+ public static LinkedList<Long> findRemovableConditionalPatternInOuterProduct(Hop hop) {\n+ LinkedList<Long> removableHopIDs = new LinkedList<>();\n+ if(((BinaryOp) hop).getOp() == Hop.OpOp2.MULT) {\n+ if (hop.getInput().get(0) instanceof BinaryOp &&\n+ ((BinaryOp) hop.getInput().get(0)).getOp() == Hop.OpOp2.NOTEQUAL) {\n+ removableHopIDs.add(hop.getHopID());\n+ removableHopIDs.add(hop.getInput().get(0).getHopID());\n+ removableHopIDs.add(hop.getInput().get(0).getInput().get(0).getHopID());\n+ removableHopIDs.add(hop.getInput().get(0).getInput().get(1).getHopID());\n+ }\n+ else if (hop.getInput().get(1) instanceof BinaryOp &&\n+ ((BinaryOp) hop.getInput().get(1)).getOp() == Hop.OpOp2.NOTEQUAL) {\n+ removableHopIDs.add(hop.getHopID());\n+ removableHopIDs.add(hop.getInput().get(1).getHopID());\n+ removableHopIDs.add(hop.getInput().get(1).getInput().get(0).getHopID());\n+ removableHopIDs.add(hop.getInput().get(1).getInput().get(1).getHopID());\n+ }\n+ }\n+ return removableHopIDs;\n+ }\n+\n+ public static long skipConditionalInOuterProduct(Hop hop, HashMap<Long, CNode> tmp, HashSet<Hop> inHops) {\n+ LinkedList<Long> ll = findRemovableConditionalPatternInOuterProduct(hop);\n+ if(!ll.isEmpty()) {\n+ for (long hopid : ll) {\n+ boolean is_input = false;\n+ for (Hop in : inHops) {\n+ is_input = in.getHopID() == hopid;\n+ if (is_input)\n+ break;\n+ }\n+ if(!is_input)\n+ tmp.remove(hopid);\n+ }\n+ if(tmp.containsKey(hop.getInput().get(0).getHopID()))\n+ return hop.getInput().get(0).getHopID();\n+ else\n+ return hop.getInput().get(1).getHopID();\n+ }\n+ else return hop.getHopID();\n+ }\n+\npublic static boolean hasTransposeParentUnderOuterProduct(Hop hop) {\nfor( Hop p : hop.getParent() )\nif( HopRewriteUtils.isTransposeOperation(p) )\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Omit producing code for a conditional with SpoofOuterProduct |
49,706 | 23.03.2020 19:28:20 | -3,600 | 7b26f109b67d81cb8a4ab841a404fb18fc8a11cd | [MINOR] update R version in docker
This also change the the testing image to debian distribution instead of
the previous alpine distribution. | [
{
"change_type": "MODIFY",
"old_path": "docker/testsysds.Dockerfile",
"new_path": "docker/testsysds.Dockerfile",
"diff": "#\n#-------------------------------------------------------------\n-# Use Alpine OpenJDK 8 base\n-FROM openjdk:8-alpine\n+# Use OpenJDK 8 debian base\n+FROM openjdk:8\n+# Use R official debian release\n+FROM r-base\nWORKDIR /usr/src/\n@@ -39,21 +41,13 @@ RUN wget http://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/ap\nmv apache-maven-$MAVEN_VERSION /usr/lib/mvn\n# Install Extras\n-RUN apk update && \\\n- apk upgrade && \\\n- apk add git && \\\n- apk add bash\n+RUN apt-get update -qq && \\\n+ apt-get upgrade -y\nCOPY ./src/test/scripts/installDependencies.R installDependencies.R\n# Install R + Dependencies\n-RUN apk add libc-dev && \\\n- apk add R && \\\n- apk add R-dev && \\\n- Rscript installDependencies.R\n-\n- # echo \"R_LIBS=/Rpackages/\" > ~/.Renviron && \\\n- # mkdir /Rpackages && \\\n+RUN Rscript installDependencies.R\nCOPY ./docker/entrypoint.sh /entrypoint.sh\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] update R version in docker
This also change the the testing image to debian distribution instead of
the previous alpine distribution. |
49,706 | 23.03.2020 20:05:05 | -3,600 | a93ad0c4b45e14e6357e2df723bdcaeea3c961fc | [MINOR] fix docker image now containing java | [
{
"change_type": "MODIFY",
"old_path": "docker/README.md",
"new_path": "docker/README.md",
"diff": "@@ -78,3 +78,12 @@ docker push sebaba/testingsysds:0.2\n```\nFor each of the tests that require R, this image is simply used, because it skips the installation of the R packages, since they are installed in this image.\n+\n+Test your testing image locally by running the following command:\n+\n+```bash\n+docker run \\\n+ -v $(pwd):/github/workspace \\\n+ sebaba/testingsysds:0.2 \\\n+ org.tugraz.sysds.test.component.*.**\n+```\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/testsysds.Dockerfile",
"new_path": "docker/testsysds.Dockerfile",
"diff": "#\n#-------------------------------------------------------------\n-# Use OpenJDK 8 debian base\n-FROM openjdk:8\n# Use R official debian release\nFROM r-base\n@@ -42,7 +40,8 @@ RUN wget http://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/ap\n# Install Extras\nRUN apt-get update -qq && \\\n- apt-get upgrade -y\n+ apt-get upgrade -y && \\\n+ apt-get install openjdk-8-jdk-headless -y\nCOPY ./src/test/scripts/installDependencies.R installDependencies.R\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] fix docker image now containing java |
49,693 | 24.03.2020 00:52:34 | -3,600 | 4cfe866eb0cc86f7bdb0a6d79cbb3051e3533be2 | [MINOR] Readme updates and a lot of pointers to documentation | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -23,7 +23,7 @@ limitations under the License.\n**Overview:** SystemDS is a versatile system for the end-to-end data science lifecycle from data integration, cleaning, and feature engineering, over efficient, local and distributed ML model training, to deployment and serving. To this end, we aim to provide a stack of declarative languages with R-like syntax for (1) the different tasks of the data-science lifecycle, and (2) users with different expertise. These high-level scripts are compiled into hybrid execution plans of local, in-memory CPU and GPU operations, as well as distributed operations on Apache Spark. In contrast to existing systems - that either provide homogeneous tensors or 2D Datasets - and in order to serve the entire data science lifecycle, the underlying data model are DataTensors, i.e., tensors (multi-dimensional arrays) whose first dimension may have a heterogeneous and nested schema.\n-**Documentation:** [SystemDS Documentation](http://apache.github.io/systemml/dml-language-reference)\n+**Documentation:** [SystemDS Documentation](https://github.com/tugraz-isds/systemds/tree/master/docs)\n**Status and Build:** SystemDS is still in pre-alpha status. The original code base was forked from [**Apache SystemML**](http://systemml.apache.org/) 1.2 in September 2018. We will continue to support linear algebra programs over matrices, while replacing the underlying data model and compiler, as well as substantially extending the supported functionalities. Until the first release, you can build your own snapshot via Apache Maven: `mvn -DskipTests clean package`.\n"
},
{
"change_type": "MODIFY",
"old_path": "bin/README.md",
"new_path": "bin/README.md",
"diff": "+<!--\n+{% comment %}\n+Modifications Copyright 2020 Graz University of Technology\n+\n+Licensed to the Apache Software Foundation (ASF) under one or more\n+contributor license agreements. See the NOTICE file distributed with\n+this work for additional information regarding copyright ownership.\n+The ASF licenses this file to you under the Apache License, Version 2.0\n+(the \"License\"); you may not use this file except in compliance with\n+the License. You may obtain a copy of the License at\n+\n+http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+{% end comment %}\n+-->\n+\n## Scripts to run SystemDS\nThis directory contains scripts to launch systemds.\n@@ -37,3 +58,7 @@ $ bin/systemds.sh Univar-Stats.dml -nvargs X=data/haberman.data TYPES=data/types\nTo use the MKL acceleration download and install the latest MKL library from [1],\nset the environment variables with the MKL-provided script `$ compilervars.sh intel64` and set\nthe option `sysds.native.blas` in `SystemDS-config.xml`.\n+\n+## Further reading\n+\n+More documentation is available in the [docs directory of our github repository](https://github.com/tugraz-isds/systemds/tree/master/docs)\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docs/README.md",
"diff": "+<!--\n+{% comment %}\n+Modifications Copyright 2020 Graz University of Technology\n+\n+Licensed to the Apache Software Foundation (ASF) under one or more\n+contributor license agreements. See the NOTICE file distributed with\n+this work for additional information regarding copyright ownership.\n+The ASF licenses this file to you under the Apache License, Version 2.0\n+(the \"License\"); you may not use this file except in compliance with\n+the License. You may obtain a copy of the License at\n+\n+http://www.apache.org/licenses/LICENSE-2.0\n+\n+Unless required by applicable law or agreed to in writing, software\n+distributed under the License is distributed on an \"AS IS\" BASIS,\n+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+See the License for the specific language governing permissions and\n+limitations under the License.\n+{% end comment %}\n+-->\n+\n+# SystemDS Documentation\n+\n+Various forms of documentation for SystemDS are available.\n+In this directory you'll find\n+* a DML language reference\n+* a description of builtin functions (WIP)\n+* coding style settings for Eclipse (compatible with various other IDEs)\n+* an enumerated list of open and completed tasks\n+\n+### Pointers to more documentation\n+* A [hello world example](https://github.com/tugraz-isds/systemds/blob/master/src/assembly/bin/README.md) (shipped with the binary distribution) to get you started on how to run SystemDS\n+* An extended introductory [example](https://github.com/tugraz-isds/systemds/blob/master/bin/README.md)\n+* Instructions on how to build the [python bindings documentation](https://github.com/tugraz-isds/systemds/blob/master/src/main/python/docs/README.md)\n+* [Packaging](https://github.com/tugraz-isds/systemds/blob/master/src/main/python/BUILD_INSTRUCTIONS.md)\n+ the python bindings yourself\n+* The generated javadoc output will be available from the [releases page](https://github.com/tugraz-isds/systemds/releases)\n+\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "src/assembly/bin/README.md",
"new_path": "src/assembly/bin/README.md",
"diff": "@@ -21,13 +21,13 @@ limitations under the License.\n# SystemDS\n-### Overview\n+## Overview\nSystemDS is a versatile system for the end-to-end data science lifecycle from data integration, cleaning, and feature engineering, over efficient, local and distributed ML model training, to deployment and serving. To this end, we aim to provide a stack of declarative languages with R-like syntax for (1) the different tasks of the data-science lifecycle, and (2) users with different expertise. These high-level scripts are compiled into hybrid execution plans of local, in-memory CPU and GPU operations, as well as distributed operations on Apache Spark. In contrast to existing systems - that either provide homogeneous tensors or 2D Datasets - and in order to serve the entire data science lifecycle, the underlying data model are DataTensors, i.e., tensors (multi-dimensional arrays) whose first dimension may have a heterogeneous and nested schema.\n**Documentation:** [SystemDS Documentation](https://github.com/tugraz-isds/systemds/tree/master/docs)\n-#### Getting started\n+## Getting started\nRequirements for running SystemDS are a bash shell and OpenJDK 8 or a Spark 2 cluster installation (to run distributed jobs).\nThese requirements should be available via standard system packages in all major Linux distributions\n@@ -51,13 +51,13 @@ of sparsity. As you can see, DML can access these parameters by specifying $1, $\n**Execution:** Now run that first script you created by running one of the following commands depending on your operating system:\n-##### Running a script locally\n+#### Running a script locally\n```shell script\n$ ./systemds.sh hello.dml -args 10 10 1.0\n```\n-##### Running a script locally, providing your own SystemDS.jar file\n+#### Running a script locally, providing your own SystemDS.jar file\nIf you compiled SystemDS from source, you can of course use the created JAR file with the run script.\n@@ -65,14 +65,14 @@ If you compiled SystemDS from source, you can of course use the created JAR file\n$ ./systemds.sh path/to/the/SystemDS.jar hello.dml -args 10 10 1.0\n```\n-##### Running a script locally, in your SystemDS source environment\n+#### Running a script locally, in your SystemDS source environment\nIf you have cloned the SystemDS source repository and want to run your DML script with that, you can point the\nshell script to the source directory by setting the `SYSTEMDS_ROOT` environment variable.\n```shell script\n$ SYSTEMDS_ROOT=../../code/my-systemds/source ./systemds.sh hello.dml -args 10 10 1.0\n```\n-##### Running a script distributed on a Spark cluster\n+#### Running a script distributed on a Spark cluster\nFor running on a Spark cluster, the env variable SYSDS_DISTRIBUTED needs to be set (to something other than 0).\nPer default, SystemDS will run in hybrid mode, pushing some instructions to the cluster and running others locally.\nTo force cluster mode in this little test, we will increase the matrix size to give the woker nodes in the cluster\n@@ -104,3 +104,7 @@ Total execution time: 0,122 sec.\n20/03/09 16:40:30 INFO api.DMLScript: END DML run 03/09/2020 16:40:30\n```\n+\n+## Further reading\n+\n+More documentation is available in the [docs directory of our github repository](https://github.com/tugraz-isds/systemds/tree/master/docs)\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Readme updates and a lot of pointers to documentation |
49,693 | 24.03.2020 00:53:21 | -3,600 | b1c9c4817f37cc79173570acd66783009becf815 | [MINOR] GPG public key that will be used for signing the artifacts | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "dev/release/damslab-pubkey.asc",
"diff": "+-----BEGIN PGP PUBLIC KEY BLOCK-----\n+\n+mQINBF1pQWIBEACkUyhORiP/RjxYHiX1Mtkp8HTjzpS4T3E2Wg9Ey6V7rpKhPtKm\n+qwJW4rPU7IK/CRVbT7nsR7OQaDQaMY9ptATloWpUNSbmH+fKq9JsQll1kJOcLgUe\n+0QPZ5KJK3ZNMdlFva5k13nMjGIHd6ThTilfq1XuwD5+qQIXxUuDExflphSCR84V4\n+UrUUyqJTtMyeqWYNucCm8BOcU79hKNbGXCnLQTW7cEnRy5rg5wXc0ZI7QUM8bdWY\n+3AylaKP2rdlycjAPBZSy2cunKl/pUgPiRa8uuqOpnw9TIfCTjmqwXMrM3FJkM7Jg\n+Ul0oeIaUa/M3bsJECflwBMP8Z0nGHg/9H1geu6iSIi5xNIVX/H5A+DkZKDS9vvAF\n+DoK366N39MF6UkwHt0Sio98QCUOiOG9Lxf70DYI+rPFSf2HhKhTa3/VmJ2hpU5AV\n+/Lnt1VDSmUbMRvBiGn4IL38F8dWE6wythJgmCi+obBJaE1d9GsPkYxwrdBqNEJig\n+lOTUULYuYyBe2oNEmq6k99pNChlOQ0bLlXBAbzdz6fZ9pvAvjjgm+8DtkxnmDqJx\n+hHavYfameHgGBqJBEbato93JtmxhxJ3iigq+qPIyV7VcLt3C0Hm+hL2Gv/mYiA1X\n+uDCKwFMavM+oZHkyfVZb5Enqkq2KvFWNVJK9PyOwzStweAgSB+HJ8YoZzwARAQAB\n+tC9TeXN0ZW1EUyAocmVsZWFzZSBzaWduaW5nIGtleSkgPG1hcmtAZG9rdGVyLmNj\n+PokCVAQwAQoAPhYhBI7TggNO5z9SeN7qplE80Mx9Yvt3BQJeeTtnIB0AdHJhbnNm\n+ZXIgZnJvbSBjcmVhdG9yIHRvIGdyb3VwAAoJEFE80Mx9Yvt3OSMQAIS11onjwH0h\n+/sAfBJRg5j18xBqCflq79Cdb4amz3HXV8OqRVY01XxTNGzCS/QZwVRLPbh7LvO6o\n+Z3lr3sJ3WOS79Wy1ABoV0WVPnfnvgLNz+xF1Tb4/R1NyNODoN40T+gxM+CXHkGUJ\n+tSXiqQ48oexeQKgBleVof91WjCHlXgi5K6cMSWhexI/tIov5aFNEhZyk7xOA0tpu\n++hKbrXl/emWOzOiSxp3JZ9VP7KZ3KvnpdnJNqbJdajMlsNvcihHqABuRwxM8gLT0\n+z1ATYLF+bSuK7McCrmPU2axNIwfpolASheTK7qK7Yo7PgWNuLcKSmzE4ua5xm/P9\n+TyNoVlKGpvFHkM2XYBU41FJGAKz8ypQuQFByeFPTgg46YWCQ+5J7lN73iinZQGAe\n+C5CfcKSCkglwreihNQ2sjXSQSsm/IhgnR3Gg5ZlzHiKAM96LC9quManWGMktG8y0\n+vRqd5I1s08LrmAQjfqxVheEwYAiVqkLqS6JbzkmpqPiAfp/bx7NuyrCu+LY81kRt\n+lI3qQ9dKpHQuQAiEfLq+I6rHkkPJIGVaIgOAh7PZyNh9n4lNVqhMICo7asbDbtj8\n+MaH18B3ZKl+LuYxIlyFfBAOqfZjl8LVxkc3AielemdTif6v2uAWFkjZLqYeqWW8A\n+xihN1AjHJHqNsCOueuLOkF5TIwPo1N9PiQJUBBMBCgA+FiEEjtOCA07nP1J43uqm\n+UTzQzH1i+3cFAl4Aum0CGwMFCQWjmoAFCwkIBwIGFQoJCAsCBBYCAwECHgECF4AA\n+CgkQUTzQzH1i+3foqQ/8D742eSJOyBdrHPTLCSaNWZs5wcTjvFgzdKkCOPW7ZT7q\n+QINht/QHoiBSFL3w4X/0u5GRWabiBBcfx5Nqzpfaxm7XjTPEHnUkVCEEuwzg6zql\n+gajnWoebhieAdl9cUJxnnzPytWKFWglieGg6e40V1b/sUQUghe8bQgbUAohhHbtC\n+2Ro9exvZLprwzQj/48d055gmRIBo6xswGqKeiznaoa0LLSqBnoQkZFa4KUaYMUZh\n+BXZ+Har9bl/yWTS3MoiaRoyGzBJieEpEtCb+g8aLMunSDXOc0+x7ijHf1nHJoLmq\n+aNAYk4AcXNeyNHexmNmwBGwXnChwUyXV8XtaQ6x92dTevTGH18TrKb6F9c1pjjqM\n+WSXQPhy8ioLkNhhMqNAHq1duuPKCiNbIJqJxkBAMZmaSox1Ba77hIrx/wGeEBv0I\n+zW4X7HBkgkO7IkMBR/SsY+J59/PQMtQrpCSnQX9XluzFsdNeaFiKjLgO8hiEilVM\n+mUHPaqsHjAp3zSW+a+JBbKMG3bwGb1j8PITfnhA4Z+QQt5TR1ctdJQVsYIibpWyA\n+FxykyULv4lI3fKaXC2pX9jzK1HgL1ASZNg59jJTzqhdMTZuLhMhXNd89/cfS50hK\n+YTRy6VHGRPHeJEnInrkpF300I1H24r88vLP9oWqZqK84TPF0n3BLVyL9QzJGMQO0\n+QERBTVNMYWIgKFN5c3RlbURTIFJlbGVhc2UgU2lnbmluZyBLZXkpIDxkYW1zbGFi\n+QG1saXN0LnR1Z3Jhei5hdD6JAlQEEwEKAD4WIQSO04IDTuc/Unje6qZRPNDMfWL7\n+dwUCXnk6tgIbAwUJBaOagAULCQgHAgYVCgkICwIEFgIDAQIeAQIXgAAKCRBRPNDM\n+fWL7d5GyD/4q5jbX1UwtYr/troW0MntJnT6y66CdxJ7rXB1cQHx+kP/RzUWXx7G1\n+nnse/7flR2Ke9kIEaWq5ENvSSavH2ugWtcpKsvcSVtLn6FurkJ5VT3jLanp08Yvs\n+I0sE/hK5hQVvR/eS7LKKWYnrtbXGO1VxMOXDVz6ga3XvYatcBUgHjz7xPb6AEO5V\n+AphjDIelJRfgfznL+ufmtpspX1izJhS5ihk3qrcUjzxVj6sD2pvJElSbhsgfQKhz\n+29a5CYJLlo/52X+HGPw1YiSlra9enVzqLKbTNdowHhoEawpsLWTWg93sPbeRoAff\n+anrXOvUKU4s9JQawPcocQn5LGr+k2Jd4nOsYgnG3ezQmwkERdLXAaGZHS7ti4PRM\n+QE6MyzlKIfEEcydh+Ckfux82ObyRrIVajjspBVV36DxZNtnK+8bTIL8s6vWYuNzz\n+gxz7ovILNnCEuGftwb4Vd1mZuMzf98rOmmsweyMqmT1Tj7JhZ1dMfTNO3AIUqXZq\n+Jt2b9ap04fo67xsh144E/wrM9FRZcqUw4vJkTlGeuM3bkCsmIQQb/q6PkhINJRmq\n+U0/ZfSitBcvLJhUIfKe0mnwano2fCdHc8OfMctLMQps0ZVvBGSuaBhYZp+CNckVM\n+C24MCSFsrwuQo+0A0fxQU62DxRC3N7WKjbQSVYrMBsj6bIgZMqtOHrkCDQRdaUFi\n+ARAAm5IQ/S23tO02F2KR4iyCNZSg3XdDI/qW8EBlZpLI09S73RokvxiCUoAC+AA3\n+/A7jvJCa/OYtFohQ3g3XyoOlAy9r5iMs2JgxJvK4/92bBTCb05tE1mWe74fMJWXK\n+mbUys5XnKvdNnPkdpVhdaZCLfhGhyj4oYOlO/4h0lcwhpwo4kRxcX3AFkv2mLssh\n+UFoWqKmp5zrC4m5pD2SYDVuaxYDLAYQqGQmMXwsStBROVs64fol5ud4w9bJthQn2\n+lVir06KxinCYsFkBpB4zoT47ACT19vwzgQogA+DDqh6AydYo6+JCiybyTdPFNz/o\n+gBobH6sBXqGEK9mUSSXaBKPwJhb7KPaHStShRUhDXzrmKttOEVxfuvkGT82zx8Mm\n+wri4fVe1Vp8azrmZ23jstyxRRXeXxgjMAeBC0r/mi5hKuEhlqyjPoLF/kt47Jl8+\n+2DAc9nwHl7K7bsmbOygdEW9yKBrVeO3EvhB38RRpWEYfVXGqMNe3d5FhmWcPVM2o\n+QxtzIGr2UyNfSpfWn5OwIax0mK4lO3lsMRlqTzanVg3LC639VS3WiZ4Vsk+nTx3g\n+FULKin9nAESUJsosPH60wlC120nVr2NsLxbhn96Ze1alwDLjOHGagAiKmtYrOtZG\n+E5+90/Ubz265PtZ7f/X387YreDYfumDB3nIXob73HtAbdfMAEQEAAYkCPAQYAQoA\n+JhYhBI7TggNO5z9SeN7qplE80Mx9Yvt3BQJdaUFiAhsMBQkFo5qAAAoJEFE80Mx9\n+Yvt3D3QP/1EWHk8GWr6QLp6Gaizxlf3Jc0nUhxaGo60QyLmIbFiCVCsU/DzsMtOf\n+Q+iak7Prlz4C1IeBcH6jqS2MBtairGCmGpzj+wI3QG3DZSySuDqXaby/xWLExtHI\n+ZOiWcl47WqGz8kBc6+cecLbt23v/UpS81dUog3kM/TDjEMbgLmIJLZn3/C4p6mGH\n+YpOh2IZdNEuOpmN1FpMKgzSuDThltqocSV5uWAfP24OTBVnOMd1+fNyajvpAEgP4\n+9ZzNUY0d2VGTXfe3cVspjpHH0ED102nIO6ypnlvKpbjbQTrg7cbpXbBWpWIJsyzo\n+PLmfw5bUPxIc0RzaUIOLTzBkhLGBtzeWZCNVPel/+iPyUIFOZ8yEAN9Dwh3oTz6p\n+FYJjGD3k1wGhOG69mHpbB+BTqNYJWNaVZDXgEnq7BQp/OO+jFdlwXzKedMIYBpa1\n+IYcr1IaopJv8h3b7V2peNhIbl9OqlBFPz58MDfrf1tT9lNv4z+nno6DXp+ndv4Gb\n+ahSCEZZowEBaOR9FGQ1l2OLwpdVsdtVz8ahL8Sx4spcBaDwZMoQEgAGcmmurz578\n+O/iEpynhzh7dmCqUPV3LNq7bpm73MCHIgujvTU2fF2M/d6zE00PnT3pEvignBe5X\n+NgPjbMY8o+HCyerS3MXjNEfQBw4jRqV6kJdLWlgWLUo3l3qFz+GR\n+=qr4P\n+-----END PGP PUBLIC KEY BLOCK-----\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] GPG public key that will be used for signing the artifacts |
49,693 | 24.03.2020 01:05:22 | -3,600 | a58261ae817876a07b4330a23fac06d620218adc | [MINOR] Ignore pubkey in rat check; left a note on the working openjdk version (jdk8u232-b09) | [
{
"change_type": "MODIFY",
"old_path": "pom.xml",
"new_path": "pom.xml",
"diff": "<exclude>**/target/**</exclude>\n<exclude>**/README.md</exclude>\n<exclude>**/*.svg</exclude>\n+ <exclude>dev/release/damslab-pubkey.asc</exclude>\n<!-- Jupyter Notebooks -->\n<exclude>**/*.ipynb</exclude>\n<!-- Generated antlr files -->\n"
},
{
"change_type": "MODIFY",
"old_path": "src/assembly/bin/README.md",
"new_path": "src/assembly/bin/README.md",
"diff": "@@ -32,7 +32,8 @@ limitations under the License.\nRequirements for running SystemDS are a bash shell and OpenJDK 8 or a Spark 2 cluster installation (to run distributed jobs).\nThese requirements should be available via standard system packages in all major Linux distributions\n(make sure to have the right JDK version enabled, if you have multiple versions in your system).\n-For Windows, a bash comes with git (http://git-scm.com) and OpenJDK builds can be optained at http://adoptopenjdk.net.\n+For Windows, a bash comes with [git for windows](http://git-scm.com) and OpenJDK builds can be optained at http://adoptopenjdk.net\n+(tested version [jdk8u232-b09](https://adoptopenjdk.net/archive.html))\nTo start out with an example after having installed the requirements mentioned above, create a text file\n`hello.dml` in your unzipped SystemDS directory containing the following content:\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Ignore pubkey in rat check; left a note on the working openjdk version (jdk8u232-b09) |
49,706 | 24.03.2020 13:09:49 | -3,600 | 809ef0c0226aa1447661b477259ef8bda1309802 | [MINOR] Split codegenalg tests | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/functionsTests.yml",
"new_path": ".github/workflows/functionsTests.yml",
"diff": "@@ -49,7 +49,8 @@ jobs:\nbuiltin,\ncaching,\ncodegen,\n- codegenalg,\n+ codegenalg.partone,\n+ codegenalg.parttwo,\ndata.misc,\ndata.rand,\ndata.tensor,\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmAutoEncoder.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/partone/AlgorithmAutoEncoder.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.partone;\nimport java.io.File;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmKMeans.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/partone/AlgorithmKMeans.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.partone;\nimport java.io.File;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmL2SVM.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/partone/AlgorithmL2SVM.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.partone;\nimport java.io.File;\nimport java.util.HashMap;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmLinregCG.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/partone/AlgorithmLinregCG.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.partone;\nimport java.io.File;\nimport java.util.HashMap;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmMDABivar.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/partone/AlgorithmMDABivar.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.partone;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmMLogreg.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/partone/AlgorithmMLogreg.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.partone;\nimport java.io.File;\nimport java.util.HashMap;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmMSVM.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/partone/AlgorithmMSVM.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.partone;\nimport java.io.File;\nimport java.util.HashMap;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmARIMA.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/parttwo/AlgorithmARIMA.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.parttwo;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmDatagen.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/parttwo/AlgorithmDatagen.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.parttwo;\nimport java.io.File;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmGLM.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/parttwo/AlgorithmGLM.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.parttwo;\nimport java.io.File;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmPNMF.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/parttwo/AlgorithmPNMF.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.parttwo;\nimport java.io.File;\nimport java.util.HashMap;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmPageRank.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/parttwo/AlgorithmPageRank.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.parttwo;\nimport java.io.File;\nimport java.util.HashMap;\n"
},
{
"change_type": "RENAME",
"old_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/AlgorithmStepwiseRegression.java",
"new_path": "src/test/java/org/tugraz/sysds/test/functions/codegenalg/parttwo/AlgorithmStepwiseRegression.java",
"diff": "* under the License.\n*/\n-package org.tugraz.sysds.test.functions.codegenalg;\n+package org.tugraz.sysds.test.functions.codegenalg.parttwo;\nimport java.io.File;\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Split codegenalg tests |
49,720 | 24.03.2020 21:11:49 | -3,600 | a5a8d4e0040308993d7892be11dae63c81575efd | [MINOR] Fix jdk8u242 integration issue on Windows | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/tugraz/sysds/test/AutomatedTestBase.java",
"new_path": "src/test/java/org/tugraz/sysds/test/AutomatedTestBase.java",
"diff": "@@ -94,62 +94,57 @@ public abstract class AutomatedTestBase {\npublic static final int FED_WORKER_WAIT = 500; // in ms\n- // *** HACK ALERT *** HACK ALERT *** HACK ALERT ***\n- // Hadoop 2.4.1 doesn't work on Windows unless winutils.exe is available\n- // under $HADOOP_HOME/bin and hadoop.dll is available in the Java library\n- // path. The following static initializer sets up JVM variables so that\n- // Hadoop can find these native binaries, assuming that any Hadoop code\n- // loads after this class and that the JVM's current working directory\n- // is the root of this project.\n- static {\n-\n- /* For testing MKL BLAS on Windows run \"mklvars.bat intel64\" or \"compilervars.bat intel64\" (this script\n- * comes with the mkl software package and sets the env var MKLROOT). Then start SystemDS or\n- * your IDE from that environment (e.g. from that command prompt).\n- * Alternatively you can set MKLROOT and your PATH variables manually to make it permanent.\n- * Same for Linux but with compilervars.sh intel64.\n- * For OpenBLAS point your PATH to the shared library.\n- */\n-\n- // the JNI implementation will be in a SO/DLL in that directory\n- // after a successful mvn package\n- appendToJavaLibraryPath(\"target\" + File.separator + \"classes\" + File.separator + \"lib\");\n+ // With OpenJDK 8u242 on Windows, the new changes in JDK are not allowing to set the native library paths internally thus breaking the code.\n+ // That is why, these static assignments to java.library.path and hadoop.home.dir are commented out.\n- if(SystemUtils.IS_OS_WINDOWS) {\n- System.err.println(\"AutomatedTestBase has detected a Windows OS and is overriding\\n\"\n- + \"hadoop.home.dir and java.library.path.\\n\");\n- String cwd = System.getProperty(\"user.dir\");\n- System.setProperty(\"hadoop.home.dir\", cwd + File.separator + \"src\" + File.separator + \"test\" +\n- File.separator + \"config\" +\n- File.separator + \"hadoop_bin_windows\");\n-\n- appendToJavaLibraryPath(cwd);\n- appendToJavaLibraryPath(cwd + File.separator + \"src\" + File.separator + \"test\" + File.separator + \"config\" +\n- File.separator + \"hadoop_bin_windows\" + File.separator + \"bin\");\n- appendToJavaLibraryPath(\"lib\");\n-\n- if(TEST_GPU) {\n- String CUDA_LIBRARY_PATH = System.getenv(\"CUDA_PATH\") + File.separator + \"bin\";\n- appendToJavaLibraryPath(CUDA_LIBRARY_PATH);\n- }\n-\n- // Need to muck around with the classloader to get it to use the new\n- // value of java.library.path.\n- try {\n- final Field sysPathsField = ClassLoader.class.getDeclaredField(\"sys_paths\");\n- sysPathsField.setAccessible(true);\n-\n- sysPathsField.set(null, null);\n- }\n- catch(Exception e) {\n- // IBM Java throws an exception here, so don't print the stack trace.\n- // e.printStackTrace();\n- // System.err.printf(\"Caught exception while attempting to override library path. Attempting to\n- // continue.\");\n- }\n- }\n- }\n- // *** END HACK ***\n+// static {\n+//\n+// /* For testing MKL BLAS on Windows run \"mklvars.bat intel64\" or \"compilervars.bat intel64\" (this script\n+// * comes with the mkl software package and sets the env var MKLROOT). Then start SystemDS or\n+// * your IDE from that environment (e.g. from that command prompt).\n+// * Alternatively you can set MKLROOT and your PATH variables manually to make it permanent.\n+// * Same for Linux but with compilervars.sh intel64.\n+// * For OpenBLAS point your PATH to the shared library.\n+// */\n+//\n+// // the JNI implementation will be in a SO/DLL in that directory\n+// // after a successful mvn package\n+// appendToJavaLibraryPath(\"target\" + File.separator + \"classes\" + File.separator + \"lib\");\n+//\n+// if(SystemUtils.IS_OS_WINDOWS) {\n+// System.err.println(\"AutomatedTestBase has detected a Windows OS and is overriding\\n\"\n+// + \"hadoop.home.dir and java.library.path.\\n\");\n+// String cwd = System.getProperty(\"user.dir\");\n+// System.setProperty(\"hadoop.home.dir\", cwd + File.separator + \"src\" + File.separator + \"test\" +\n+// File.separator + \"config\" +\n+// File.separator + \"hadoop_bin_windows\");\n+//\n+// appendToJavaLibraryPath(cwd);\n+// appendToJavaLibraryPath(cwd + File.separator + \"src\" + File.separator + \"test\" + File.separator + \"config\" +\n+// File.separator + \"hadoop_bin_windows\" + File.separator + \"bin\");\n+// appendToJavaLibraryPath(\"lib\");\n+//\n+// if(TEST_GPU) {\n+// String CUDA_LIBRARY_PATH = System.getenv(\"CUDA_PATH\") + File.separator + \"bin\";\n+// appendToJavaLibraryPath(CUDA_LIBRARY_PATH);\n+// }\n+//\n+// // Need to muck around with the classloader to get it to use the new\n+// // value of java.library.path.\n+// try {\n+// final Field sysPathsField = ClassLoader.class.getDeclaredField(\"sys_paths\");\n+// sysPathsField.setAccessible(true);\n+//\n+// sysPathsField.set(null, null);\n+// }\n+// catch(Exception e) {\n+// // IBM Java throws an exception here, so don't print the stack trace.\n+// // e.printStackTrace();\n+// // System.err.printf(\"Caught exception while attempting to override library path. Attempting to\n+// // continue.\");\n+// }\n+// }\n+// }\n/**\n* Script source directory for .dml and .r files only (TEST_DATA_DIR for generated test data artifacts).\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix jdk8u242 integration issue on Windows |
49,738 | 28.03.2020 00:28:46 | -3,600 | 2cc922c856967d75afac09f80fd4df73a620584a | [MINOR] Fix mlcontext function tests (wrong url) | [
{
"change_type": "MODIFY",
"old_path": "src/test/java/org/apache/sysds/test/functions/mlcontext/MLContextTest.java",
"new_path": "src/test/java/org/apache/sysds/test/functions/mlcontext/MLContextTest.java",
"diff": "@@ -158,7 +158,7 @@ public class MLContextTest extends MLContextTestBase {\n@Test\npublic void testCreateDMLScriptBasedOnURL() throws MalformedURLException {\nSystem.out.println(\"MLContextTest - create DML script based on URL\");\n- String urlString = \"https://raw.githubusercontent.com/apache/systemml/systemds/master/src/test/scripts/applications/hits/HITS.dml\";\n+ String urlString = \"https://raw.githubusercontent.com/apache/systemml/master/src/test/scripts/applications/hits/HITS.dml\";\nURL url = new URL(urlString);\nScript script = dmlFromUrl(url);\nString expectedContent = \"Licensed to the Apache Software Foundation\";\n"
}
] | Java | Apache License 2.0 | apache/systemds | [MINOR] Fix mlcontext function tests (wrong url) |
49,706 | 28.03.2020 20:22:12 | -3,600 | dab09916436c9518afa3cf8da572db2bde32207a | Improved github workflows (cache dependencies)
Closes | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/applicationTests.yml",
"new_path": ".github/workflows/applicationTests.yml",
"diff": "@@ -39,7 +39,8 @@ jobs:\nos: [ubuntu-latest]\nname: Ap Test ${{ matrix.tests }}\nsteps:\n- - uses: actions/checkout@v2\n+ - name: Checkout Repository\n+ uses: actions/checkout@v2\n- name: Run all tests starting with \"${{ matrix.tests }}\"\nuses: ./.github/action/\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/workflows/build.yml",
"new_path": ".github/workflows/build.yml",
"diff": "@@ -30,14 +30,22 @@ jobs:\nfail-fast: false\nmatrix:\nos: [ubuntu-latest, macOS-latest, windows-latest]\n-\nsteps:\n- - uses: actions/checkout@v2\n+ - name: Checkout Repository\n+ uses: actions/checkout@v2\n- - name: Set up JDK 1.8\n+ - name: Setup Java 1.8\nuses: actions/setup-java@v1\nwith:\njava-version: 1.8\n- - name: Build with Maven\n+ - name: Cache Maven Dependencies\n+ uses: actions/cache@v1\n+ with:\n+ path: ~/.m2/repository\n+ key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}\n+ restore-keys: |\n+ ${{ runner.os }}-maven-\n+\n+ - name: Build\nrun: mvn package\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/workflows/componentTests.yml",
"new_path": ".github/workflows/componentTests.yml",
"diff": "@@ -30,15 +30,23 @@ jobs:\nfail-fast: false\nmatrix:\nos: [ubuntu-latest]\n- java: [ 1.8 ]\nname: Component Tests ${{ matrix.os }}\nsteps:\n- - uses: actions/checkout@v2\n+ - name: Checkout Repository\n+ uses: actions/checkout@v2\n- - name: Setup Java\n+ - name: Setup Java 1.8\nuses: actions/setup-java@v1\nwith:\n- java-version: ${{ matrix.java }}\n+ java-version: 1.8\n+\n+ - name: Cache Maven Dependencies\n+ uses: actions/cache@v1\n+ with:\n+ path: ~/.m2/repository\n+ key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}\n+ restore-keys: |\n+ ${{ runner.os }}-maven-\n- name: Maven clean compile & test-compile\nrun: mvn clean compile test-compile\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/workflows/documentation.yml",
"new_path": ".github/workflows/documentation.yml",
"diff": "@@ -31,13 +31,22 @@ jobs:\nruns-on: ubuntu-latest\nname: Documentation Java\nsteps:\n- - uses: actions/checkout@v2\n+ - name: Checkout Repository\n+ uses: actions/checkout@v2\n- - name: Setup Java\n+ - name: Setup Java 1.8\nuses: actions/setup-java@v1\nwith:\njava-version: 1.8\n+ - name: Cache Maven Dependencies\n+ uses: actions/cache@v1\n+ with:\n+ path: ~/.m2/repository\n+ key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}\n+ restore-keys: |\n+ ${{ runner.os }}-maven-\n+\n- name: Make Documentation SystemDS Java\nrun: mvn -P distribution package\n@@ -51,7 +60,8 @@ jobs:\nruns-on: ubuntu-latest\nname: Documentation Python\nsteps:\n- - uses: actions/checkout@v2\n+ - name: Checkout Repository\n+ uses: actions/checkout@v2\n- name: Setup Python\nuses: actions/setup-python@v1\n@@ -59,6 +69,14 @@ jobs:\npython-version: 3.7\narchitecture: 'x64'\n+ - name: Cache Pip Dependencies\n+ uses: actions/cache@v1\n+ with:\n+ path: ~/.cache/pip\n+ key: ${{ runner.os }}-pip-docs-${{ hashFiles('src/main/python/docs/requires-docs.txt') }}\n+ restore-keys: |\n+ ${{ runner.os }}-pip-docs-\n+\n- name: Install Dependencies\nrun: |\ncd src/main/python/docs\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/workflows/functionsTests.yml",
"new_path": ".github/workflows/functionsTests.yml",
"diff": "@@ -77,7 +77,8 @@ jobs:\nos: [ubuntu-latest]\nname: Func Test ${{ matrix.tests }}\nsteps:\n- - uses: actions/checkout@v2\n+ - name: Checkout Repository\n+ uses: actions/checkout@v2\n- name: Run all tests starting with \"${{ matrix.tests }}\"\nuses: ./.github/action/\n"
},
{
"change_type": "MODIFY",
"old_path": ".github/workflows/python.yml",
"new_path": ".github/workflows/python.yml",
"diff": "@@ -40,13 +40,22 @@ jobs:\njava: [ 1.8 ]\nname: Python Test\nsteps:\n- - uses: actions/checkout@v2\n+ - name: Checkout Repository\n+ uses: actions/checkout@v2\n- name: Setup Java\nuses: actions/setup-java@v1\nwith:\njava-version: ${{ matrix.java }}\n+ - name: Cache Maven Dependencies\n+ uses: actions/cache@v1\n+ with:\n+ path: ~/.m2/repository\n+ key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}\n+ restore-keys: |\n+ ${{ runner.os }}-maven-\n+\n- name: Maven clean & package\nrun: mvn clean package\n@@ -56,11 +65,18 @@ jobs:\npython-version: ${{ matrix.python-version }}\narchitecture: 'x64'\n+ - name: Cache Pip Dependencies\n+ uses: actions/cache@v1\n+ with:\n+ path: ~/.cache/pip\n+ key: ${{ runner.os }}-pip-${{ matrix.python-version }}-${{ hashFiles('src/main/python/setup.py') }}\n+ restore-keys: |\n+ ${{ runner.os }}-pip-${{ matrix.python-version }}-\n+\n- name: Install pip Dependencies\nrun: pip install numpy py4j wheel\n- name: Build Python Package\n- # TODO: Find out how to make if statement correctly: suggestion but not working: if: ${{ matrix.tests }} == P\nrun: |\ncd src/main/python\npython create_python_dist.py\n"
}
] | Java | Apache License 2.0 | apache/systemds | [SYSTEMDS-301] Improved github workflows (cache dependencies)
Closes #869. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.