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,693
24.02.2021 00:05:52
-3,600
510838a982b6d15e21aacd5328d6f140f1721513
[MINOR] fix jitify submodule config Closes
[ { "change_type": "MODIFY", "old_path": ".gitmodules", "new_path": ".gitmodules", "diff": "-[submodule \"jitify\"]\n+[submodule \"src/main/cuda/ext/jitify\"]\npath = src/main/cuda/ext/jitify\n- url = [email protected]:NVIDIA/jitify.git\n+ url = [email protected]:corepointer/jitify.git\n+ branch = win_compile_fix\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/cuda/ext/jitify", "diff": "+Subproject commit fdd570c55d59f28b6f7c20acd5f46cf359999585\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] fix jitify submodule config Closes #1180
49,743
27.11.2020 18:15:52
-3,600
44e42945541150d7e870c5b89e79c085d63b4e78
Add Builtin Decision Tree DIA project WS2020/21 Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/decisionTree.dml", "diff": "+#-------------------------------------------------------------\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+#\n+# THIS SCRIPT IMPLEMENTS CLASSIFICATION TREES WITH BOTH SCALE AND CATEGORICAL FEATURES\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Matrix[Double] --- Feature matrix X; note that X needs to be both recoded and dummy coded\n+# Y Matrix[Double] --- Label matrix Y; note that Y needs to be both recoded and dummy coded\n+# R Matrix[Double] \" \" Matrix R which for each feature in X contains the following information\n+# - R[1,]: Row Vector which indicates if feature vector is scalar or categorical. 1 indicates\n+# a scalar feature vector, other positive Integers indicate the number of categories\n+# If R is not provided by default all variables are assumed to be scale\n+# bins Integer 20 Number of equiheight bins per scale feature to choose thresholds\n+# depth Integer 25 Maximum depth of the learned tree\n+# verbose Boolean FALSE boolean specifying if the algorithm should print information while executing\n+# ---------------------------------------------------------------------------------------------\n+# OUTPUT:\n+# Matrix M where each column corresponds to a node in the learned tree and each row contains the following information:\n+# M[1,j]: id of node j (in a complete binary tree)\n+# M[2,j]: Offset (no. of columns) to left child of j if j is an internal node, otherwise 0\n+# M[3,j]: Feature index of the feature (scale feature id if the feature is scale or categorical feature id if the feature is categorical)\n+# that node j looks at if j is an internal node, otherwise 0\n+# M[4,j]: Type of the feature that node j looks at if j is an internal node: holds the same information as R input vector\n+# M[5,j]: If j is an internal node: 1 if the feature chosen for j is scale, otherwise the size of the subset of values\n+# stored in rows 6,7,... if j is categorical\n+# If j is a leaf node: number of misclassified samples reaching at node j\n+# M[6:,j]: If j is an internal node: Threshold the example's feature value is compared to is stored at M[6,j] if the feature chosen for j is scale,\n+# otherwise if the feature chosen for j is categorical rows 6,7,... depict the value subset chosen for j\n+# If j is a leaf node 1 if j is impure and the number of samples at j > threshold, otherwise 0\n+# -------------------------------------------------------------------------------------------\n+\n+m_decisionTree = function(\n+ Matrix[Double] X,\n+ Matrix[Double] Y,\n+ Matrix[Double] R,\n+ Integer bins = 10,\n+ Integer depth = 20,\n+ Boolean verbose = FALSE\n+) return (Matrix[Double] M) {\n+ if (verbose) {\n+ print(\"Executing Decision Tree:\")\n+ }\n+ node_queue = matrix(1, rows=1, cols=1) # Add first Node\n+ impurity_queue = matrix(1, rows=1, cols=1)\n+ use_cols_queue = matrix(1, rows=ncol(X), cols=1) # Add fist bool Vector with all cols <=> (use all cols)\n+ use_rows_queue = matrix(1, rows=nrow(X), cols=1) # Add fist bool Vector with all rows <=> (use all rows)\n+ queue_length = 1\n+ M = matrix(0, rows = 0, cols = 0)\n+ while (queue_length > 0) {\n+ [node_queue, node] = dataQueuePop(node_queue)\n+ [use_rows_queue, use_rows_vector] = dataQueuePop(use_rows_queue)\n+ [use_cols_queue, use_cols_vector] = dataQueuePop(use_cols_queue)\n+\n+ available_rows = calcAvailable(use_rows_vector)\n+ available_cols = calcAvailable(use_cols_vector)\n+ [impurity_queue, parent_impurity] = dataQueuePop(impurity_queue)\n+ create_child_nodes_flag = FALSE\n+ if (verbose) {\n+ print(\"Popped Node: \" + as.scalar(node))\n+ print(\"Rows: \" + toString(t(use_rows_vector)))\n+ print(\"Cols: \" + toString(t(use_cols_vector)))\n+ print(\"Available Rows: \" + available_rows)\n+ print(\"Available Cols: \" + available_cols)\n+ print(\"Parent impurity: \" + as.scalar(parent_impurity))\n+ }\n+\n+ node_depth = calculateNodeDepth(node)\n+ used_col = 0.0\n+ if (node_depth < depth & available_rows > 1 & available_cols > 0 & as.scalar(parent_impurity) > 0) {\n+ [impurity, used_col, threshold, type] = calcBestSplittingCriteria(X, Y, R, use_rows_vector, use_cols_vector, bins)\n+ create_child_nodes_flag = impurity < as.scalar(parent_impurity)\n+ if (verbose) {\n+ print(\"Current impurity: \" + impurity)\n+ print(\"Current threshold: \"+ toString(t(threshold)))\n+ }\n+ }\n+ if (verbose) {\n+\n+ print(\"Current column: \" + used_col)\n+ print(\"Current type: \" + type)\n+ }\n+ if (create_child_nodes_flag) {\n+ [left, right] = calculateChildNodes(node)\n+ node_queue = dataQueuePush(left, right, node_queue)\n+\n+ [new_use_cols_vector, left_use_rows_vector, right_use_rows_vector] = splitData(X, use_rows_vector, use_cols_vector, used_col, threshold, type)\n+ use_rows_queue = dataQueuePush(left_use_rows_vector, right_use_rows_vector, use_rows_queue)\n+ use_cols_queue = dataQueuePush(new_use_cols_vector, new_use_cols_vector, use_cols_queue)\n+\n+ impurity_queue = dataQueuePush(matrix(impurity, rows = 1, cols = 1), matrix(impurity, rows = 1, cols = 1), impurity_queue)\n+ offset = dataQueueLength(node_queue) - 1\n+ M = outputMatrixBind(M, node, offset, used_col, R, threshold)\n+ } else {\n+ M = outputMatrixBind(M, node, 0.0, used_col, R, matrix(0, rows = 1, cols = 1))\n+ }\n+ queue_length = dataQueueLength(node_queue)# -- user-defined function calls not supported in relational expressions\n+\n+ if (verbose) {\n+ print(\"New QueueLen: \" + queue_length)\n+ print(\"\")\n+ }\n+ }\n+}\n+\n+dataQueueLength = function(Matrix[Double] queue) return (Double len) {\n+ len = ncol(queue)\n+}\n+\n+dataQueuePop = function(Matrix[Double] queue) return (Matrix[Double] new_queue, Matrix[Double] node) {\n+ node = matrix(queue[,1], rows=1, cols=nrow(queue)) # reshape to force the creation of a new object\n+ node = matrix(node, rows=nrow(queue), cols=1) # reshape to force the creation of a new object\n+ len = dataQueueLength(queue)\n+ if (len < 2) {\n+ new_queue = matrix(0,0,0)\n+ } else {\n+ new_queue = matrix(queue[,2:ncol(queue)], rows=nrow(queue), cols=ncol(queue)-1)\n+ }\n+}\n+\n+dataQueuePush = function(Matrix[Double] left, Matrix[Double] right, Matrix[Double] queue) return (Matrix[Double] new_queue) {\n+ len = dataQueueLength(queue)\n+ if(len <= 0) {\n+ new_queue = cbind(left, right)\n+ } else {\n+ new_queue = cbind(queue, left, right)\n+ }\n+}\n+\n+dataVectorLength = function(Matrix[Double] vector) return (Double len) {\n+ len = nrow(vector)\n+}\n+\n+dataColVectorLength = function(Matrix[Double] vector) return (Double len) {\n+ len = ncol(vector)\n+}\n+\n+dataVectorGet = function(Matrix[Double] vector, Double index) return (Double value) {\n+ value = as.scalar(vector[index, 1])\n+}\n+\n+dataVectorSet = function(Matrix[Double] vector, Double index, Double data) return (Matrix[Double] new_vector) {\n+ vector[index, 1] = data\n+ new_vector = vector\n+}\n+\n+calcAvailable = function(Matrix[Double] vector) return(Double available_elements){\n+ len = dataVectorLength(vector)\n+ available_elements = 0.0\n+ for (index in 1:len) {\n+ element = dataVectorGet(vector, index)\n+ if(element > 0.0) {\n+ available_elements = available_elements + 1.0\n+ }\n+ }\n+}\n+\n+calculateNodeDepth = function(Matrix[Double] node) return(Double depth) {\n+ depth = log(as.scalar(node), 2) + 1\n+}\n+\n+calculateChildNodes = function(Matrix[Double] node) return(Matrix[Double] left, Matrix[Double] right) {\n+ left = node * 2.0\n+ right = node * 2.0 + 1.0\n+}\n+\n+getTypeOfCol = function(Matrix[Double] R, Double col) return(Double type) { # 1..scalar, 2..categorical\n+ type = as.scalar(R[1, col])\n+}\n+\n+extrapolateOrderedScalarFeatures = function(\n+ Matrix[Double] X,\n+ Matrix[Double] use_rows_vector,\n+ Double col) return (Matrix[Double] feature_vector) {\n+ feature_vector = matrix(1, rows = 1, cols = 1)\n+ len = nrow(X)\n+ first_time = TRUE\n+ for(row in 1:len) {\n+ use_feature = dataVectorGet(use_rows_vector, row)\n+ if (use_feature != 0) {\n+ if(first_time) {\n+ feature_vector[1,1] = X[row, col]\n+ first_time = FALSE\n+ } else {\n+ feature_vector = rbind(feature_vector, X[row, col])\n+ }\n+ }\n+ }\n+ feature_vector = order(target=feature_vector, by=1, decreasing=FALSE, index.return=FALSE)\n+}\n+\n+calcPossibleThresholdsScalar = function(\n+ Matrix[Double] X,\n+ Matrix[Double] use_rows_vector,\n+ Double col,\n+ int bins) return (Matrix[Double] thresholds) {\n+ ordered_features = extrapolateOrderedScalarFeatures(X, use_rows_vector, col)\n+ ordered_features_len = dataVectorLength(ordered_features)\n+ thresholds = matrix(1, rows = 1, cols = ordered_features_len - 1)\n+ virtual_length = min(ordered_features_len, 20)\n+ step_length = ordered_features_len / virtual_length\n+ if (ordered_features_len > 1) {\n+ for (index in 1:(virtual_length - 1)) {\n+ real_index = index * step_length\n+ mean = (dataVectorGet(ordered_features, real_index) + dataVectorGet(ordered_features, real_index + 1)) / 2\n+ thresholds[1, index] = mean\n+ }\n+ }\n+}\n+\n+calcPossibleThresholdsCategory = function(Double type) return (Matrix[Double] thresholds) {\n+ numberThresholds = 2 ^ type\n+ thresholds = matrix(-1, rows = type, cols = numberThresholds)\n+ toggleFactor = numberThresholds / 2\n+\n+ for (index in 1:type) {\n+ beginCols = 1\n+ endCols = toggleFactor\n+ iterations = numberThresholds / toggleFactor / 2\n+ for (it in 1:iterations) {\n+ category_val = type - index + 1\n+ thresholds[index, beginCols:endCols] = matrix(category_val, rows = 1, cols = toggleFactor)\n+ endCols = endCols + 2 * toggleFactor\n+ beginCols = beginCols + 2 * toggleFactor\n+ }\n+ toggleFactor = toggleFactor / 2\n+ iterations = numberThresholds / toggleFactor / 2\n+ }\n+ ncol = ncol(thresholds)\n+ if (ncol > 2.0) {\n+ thresholds = cbind(thresholds[,2:ncol-2], thresholds[,ncol-1])\n+ }\n+}\n+\n+calcGiniImpurity = function(Double num_true, Double num_false) return (Double impurity) {\n+ prop_true = num_true / (num_true + num_false)\n+ prop_false = num_false / (num_true + num_false)\n+ impurity = 1 - (prop_true ^ 2) - (prop_false ^ 2)\n+}\n+\n+calcImpurity = function(\n+ Matrix[Double] X,\n+ Matrix[Double] Y,\n+ Matrix[Double] use_rows_vector,\n+ Double col,\n+ Double type,\n+ int bins) return (Double impurity, Matrix[Double] threshold) {\n+\n+ is_scalar_type = typeIsScalar(type)\n+ if (is_scalar_type) {\n+ possible_thresholds = calcPossibleThresholdsScalar(X, use_rows_vector, col, bins)\n+ } else {\n+ possible_thresholds = calcPossibleThresholdsCategory(type)\n+ }\n+ len_thresholds = ncol(possible_thresholds)\n+ impurity = 1\n+ threshold = matrix(0, rows=1, cols=1)\n+ for (index in 1:len_thresholds) {\n+ [false_rows, true_rows] = splitRowsVector(X, use_rows_vector, col, possible_thresholds[, index], type)\n+ num_true_positive = 0; num_false_positive = 0; num_true_negative = 0; num_false_negative = 0\n+ len = dataVectorLength(use_rows_vector)\n+ for (c_row in 1:len) {\n+ true_row_data = dataVectorGet(true_rows, c_row)\n+ false_row_data = dataVectorGet(false_rows, c_row)\n+ if (true_row_data != 0 & false_row_data == 0) { # IT'S POSITIVE!\n+ if (as.scalar(Y[c_row, 1]) != 0) {\n+ num_true_positive = num_true_positive + 1\n+ } else {\n+ num_false_positive = num_false_positive + 1\n+ }\n+ } else if (true_row_data == 0 & false_row_data != 0) { # IT'S NEGATIVE\n+ if (as.scalar(Y[c_row, 1]) != 0.0) {\n+ num_false_negative = num_false_negative + 1\n+ } else {\n+ num_true_negative = num_true_negative + 1\n+ }\n+ }\n+ }\n+ impurity_positive_branch = calcGiniImpurity(num_true_positive, num_false_positive)\n+ impurity_negative_branch = calcGiniImpurity(num_true_negative, num_false_negative)\n+ num_samples = num_true_positive + num_false_positive + num_true_negative + num_false_negative\n+ num_negative = num_true_negative + num_false_negative\n+ num_positive = num_true_positive + num_false_positive\n+ c_impurity = num_positive / num_samples * impurity_positive_branch + num_negative / num_samples * impurity_negative_branch\n+ if (c_impurity <= impurity) {\n+ impurity = c_impurity\n+ threshold = possible_thresholds[, index]\n+ }\n+ }\n+}\n+\n+calcBestSplittingCriteria = function(\n+ Matrix[Double] X,\n+ Matrix[Double] Y,\n+ Matrix[Double] R,\n+ Matrix[Double] use_rows_vector,\n+ Matrix[Double] use_cols_vector,\n+ int bins) return (Double impurity, Double used_col, Matrix[Double] threshold, Double type) {\n+\n+ impurity = 1\n+ used_col = 1\n+ threshold = matrix(0, 1, 1)\n+ type = 1\n+ # -- user-defined function calls not supported for iterable predicates\n+ len = dataVectorLength(use_cols_vector)\n+ for (c_col in 1:len) {\n+ use_feature = dataVectorGet(use_cols_vector, c_col)\n+ if (use_feature != 0) {\n+ c_type = getTypeOfCol(R, c_col)\n+ [c_impurity, c_threshold] = calcImpurity(X, Y, use_rows_vector, c_col, c_type, bins)\n+ if(c_impurity <= impurity) {\n+ impurity = c_impurity\n+ used_col = c_col\n+ threshold = c_threshold\n+ type = c_type\n+ }\n+ }\n+ }\n+}\n+\n+typeIsScalar = function(Double type) return(Boolean b) {\n+ b = type == 1.0\n+}\n+\n+splitRowsVector = function(\n+ Matrix[Double] X,\n+ Matrix[Double] use_rows_vector,\n+ Double col,\n+ Matrix[Double] threshold,\n+ Double type\n+) return (Matrix[Double] false_use_rows_vector, Matrix[Double] true_use_rows_vector) {\n+ type_is_scalar = typeIsScalar(type)\n+ false_use_rows_vector = use_rows_vector\n+ true_use_rows_vector = use_rows_vector\n+\n+ if (type_is_scalar) {\n+ scalar_threshold = as.scalar(threshold[1,1])\n+ len = dataVectorLength(use_rows_vector)\n+ for (c_row in 1:len) {\n+ row_enabled = dataVectorGet(use_rows_vector, c_row)\n+ if (row_enabled != 0) {\n+ if (as.scalar(X[c_row, col]) > scalar_threshold) {\n+ false_use_rows_vector = dataVectorSet(false_use_rows_vector, c_row, 0.0)\n+ } else {\n+ true_use_rows_vector = dataVectorSet(true_use_rows_vector, c_row, 0.0)\n+ }\n+ }\n+ }\n+ } else {\n+ len = dataVectorLength(use_rows_vector)\n+ for (c_row in 1:len) {\n+ row_enabled = dataVectorGet(use_rows_vector, c_row)\n+ if (row_enabled != 0) {\n+ categories_len = dataColVectorLength(threshold)\n+ move_sample_to_true_set = FALSE\n+ for (category_col_index in 1:categories_len) {\n+ desired_category = as.scalar(X[c_row, col])\n+ if(desired_category != -1) {\n+ category_of_threshold = threshold[type - desired_category + 1, category_col_index]\n+ move_sample_to_true_set = as.scalar(X[c_row, col]) == as.scalar(category_of_threshold)\n+ } else {\n+ #Todo: has category -1 to be considered?\n+ move_sample_to_true_set = TRUE\n+ }\n+ }\n+ if (move_sample_to_true_set) {\n+ false_use_rows_vector = dataVectorSet(false_use_rows_vector, c_row, 0.0)\n+ } else {\n+ true_use_rows_vector = dataVectorSet(true_use_rows_vector, c_row, 0.0)\n+ }\n+ }\n+ }\n+ }\n+}\n+\n+splitData = function(\n+ Matrix[Double] X,\n+ Matrix[Double] use_rows_vector,\n+ Matrix[Double] use_cols_vector,\n+ Double col,\n+ Matrix[Double] threshold,\n+ Double type\n+) return (Matrix[Double] new_use_cols_vector, Matrix[Double] false_use_rows_vector, Matrix[Double] true_use_rows_vector) {\n+ new_use_cols_vector = dataVectorSet(use_cols_vector, col, 0.0)\n+ [false_use_rows_vector, true_use_rows_vector] = splitRowsVector(X, use_rows_vector, col, threshold, type)\n+}\n+\n+outputMatrixBind = function(\n+ Matrix[Double] M,\n+ Matrix[Double] node,\n+ Double offset,\n+ Double used_col,\n+ Matrix[Double] R,\n+ Matrix[Double] threshold\n+) return (Matrix[Double] new_M) {\n+ col = matrix(0, rows = 5, cols = 1)\n+ col[1, 1] = node[1, 1]\n+ col[2, 1] = offset\n+ col[3, 1] = used_col\n+ if (used_col >= 1.0) { col[4, 1] = R[1, used_col] }\n+ col[5, 1] = nrow(threshold)\n+ col = rbind(col, threshold)\n+\n+ if (ncol(M) == 0 & nrow(M) == 0) {\n+ new_M = col\n+ } else {\n+ row_difference = nrow(M) - nrow(col)\n+ if (row_difference < 0.0) {\n+ buffer = matrix(-1, rows = -row_difference, cols = ncol(M))\n+ M = rbind(M, buffer)\n+ } else if (row_difference > 0.0) {\n+ buffer = matrix(-1, rows = row_difference, cols = 1)\n+ col = rbind(col, buffer)\n+ }\n+ new_M = cbind(M, col)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -138,6 +138,7 @@ public enum Builtins {\nKMEANSPREDICT(\"kmeansPredict\", true),\nKNNBF(\"knnbf\", true),\nKNN(\"knn\", true),\n+ DECISIONTREE(\"decisionTree\", true),\nL2SVM(\"l2svm\", true),\nLASSO(\"lasso\", true),\nLENGTH(\"length\", false),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinDecisionTreeTest.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.apache.sysds.test.functions.builtin;\n+\n+import java.util.HashMap;\n+\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.lops.LopProperties;\n+import org.apache.sysds.runtime.matrix.data.MatrixValue;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Test;\n+\n+public class BuiltinDecisionTreeTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"decisionTree\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinDecisionTreeTest.class.getSimpleName() + \"/\";\n+\n+ private final static double eps = 1e-10;\n+\n+ @Override\n+ public void setUp() {\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {\"C\"}));\n+ }\n+\n+ @Test\n+ public void testDecisionTreeDefaultCP() {\n+ runDecisionTree(true, LopProperties.ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testDecisionTreeSP() {\n+ runDecisionTree(true, LopProperties.ExecType.SPARK);\n+ }\n+\n+ private void runDecisionTree(boolean defaultProb, LopProperties.ExecType instType) {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+ try {\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(\"X\"), input(\"Y\"), input(\"R\"), output(\"M\")};\n+\n+ double[][] Y = {{1.0}, {0.0}, {0.0}, {1.0}, {0.0}};\n+\n+ double[][] X = {{4.5, 4.0, 3.0, 2.8, 3.5}, {1.9, 2.4, 1.0, 3.4, 2.9}, {2.0, 1.1, 1.0, 4.9, 3.4},\n+ {2.3, 5.0, 2.0, 1.4, 1.8}, {2.1, 1.1, 3.0, 1.0, 1.9},};\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+ writeInputMatrixWithMTD(\"Y\", Y, true);\n+\n+ double[][] R = {{1.0, 1.0, 3.0, 1.0, 1.0},};\n+ writeInputMatrixWithMTD(\"R\", R, true);\n+\n+ runTest(true, false, null, -1);\n+\n+ HashMap<MatrixValue.CellIndex, Double> actual_M = readDMLMatrixFromOutputDir(\"M\");\n+ HashMap<MatrixValue.CellIndex, Double> expected_M = new HashMap<MatrixValue.CellIndex, Double>();\n+\n+ expected_M.put(new MatrixValue.CellIndex(1, 1), 1.0);\n+ expected_M.put(new MatrixValue.CellIndex(1, 3), 3.0);\n+ expected_M.put(new MatrixValue.CellIndex(3, 1), 2.0);\n+ expected_M.put(new MatrixValue.CellIndex(1, 2), 2.0);\n+ expected_M.put(new MatrixValue.CellIndex(2, 1), 1.0);\n+ expected_M.put(new MatrixValue.CellIndex(5, 1), 1.0);\n+ expected_M.put(new MatrixValue.CellIndex(4, 1), 1.0);\n+ expected_M.put(new MatrixValue.CellIndex(5, 3), 1.0);\n+ expected_M.put(new MatrixValue.CellIndex(5, 2), 1.0);\n+ expected_M.put(new MatrixValue.CellIndex(6, 1), 3.2);\n+\n+ TestUtils.compareMatrices(expected_M, actual_M, eps, \"Expected-DML\", \"Actual-DML\");\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/decisionTree.dml", "diff": "+#-------------------------------------------------------------\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+Y = read($2);\n+R = read($3)\n+M = decisionTree(X = X, Y = Y, R = R);\n+write(M, $4);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2870] Add Builtin Decision Tree DIA project WS2020/21 Closes #1145 Co-authored-by: David Egger <[email protected]> Co-authored-by: Adna Ribo <[email protected]>
49,693
25.02.2021 13:00:42
-3,600
3315eb62ab593f4526f307a6037a8d80109559db
[MINOR] Correcting a logic error while deciding to avoid execution on empty input in SpoofCUDACellwise
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/codegen/SpoofCUDACellwise.java", "new_path": "src/main/java/org/apache/sysds/runtime/codegen/SpoofCUDACellwise.java", "diff": "@@ -64,7 +64,6 @@ public class SpoofCUDACellwise extends SpoofCellwise implements SpoofCUDAOperato\nLOG.error(\"SpoofCUDA \" + getSpoofType() + \" operator failed to execute. Trying Java fallback.\\n\");\n// ToDo: java fallback\n}\n-\nLibMatrixCUDA.cudaSupportFunctions.deviceToHost(ec.getGPUContext(0), ptr, result, getName(), false);\nreturn new DoubleObject(result[0]);\n@@ -110,7 +109,7 @@ public class SpoofCUDACellwise extends SpoofCellwise implements SpoofCUDAOperato\n// ec.setMetaData(outputName, out_rows, out_cols);\nGPUObject g = a.getGPUObject(gctx);\n- boolean sparseOut = _type == CellType.NO_AGG && sparseSafe && g.isSparse();;\n+ boolean sparseOut = _type == CellType.NO_AGG && sparseSafe && g.isSparse();\nlong nnz = g.getNnz(\"spoofCUDA\" + getSpoofType(), false);\nif(sparseOut)\n@@ -121,7 +120,7 @@ public class SpoofCUDACellwise extends SpoofCellwise implements SpoofCUDAOperato\n(ec.getDenseMatrixOutputForGPUInstruction(outputName, out_rows, out_cols).getKey());\nint offset = 1;\n- if(!(inputIsEmpty(a.getGPUObject(gctx)) && sparseSafe )) {\n+ if(!inputIsEmpty(a.getGPUObject(gctx)) || !sparseSafe) {\nif(call.exec(ec, this, ID, prepareInputPointers(ec, inputs, offset), prepareSideInputPointers(ec, inputs, offset, false),\nprepareOutputPointers(ec, out_obj, sparseOut), scalarObjects, 0) != 0) {\nLOG.error(\"SpoofCUDA \" + getSpoofType() + \" operator failed to execute. Trying Java fallback.(ToDo)\\n\");\n@@ -132,9 +131,7 @@ public class SpoofCUDACellwise extends SpoofCellwise implements SpoofCUDAOperato\n}\nprivate boolean inputIsEmpty(GPUObject g) {\n- if(g.getDensePointer() != null || g.getSparseMatrixCudaPointer() != null)\n- return true;\n- return false;\n+ return g.getDensePointer() == null && g.getSparseMatrixCudaPointer() == null;\n}\n// used to determine sparse safety\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Correcting a logic error while deciding to avoid execution on empty input in SpoofCUDACellwise
49,685
26.02.2021 10:24:37
-3,600
67ae9551f7bd62846e0b084c743018d4a0713ba2
Bayesian Optimization Algorithm DIA project WS2020/21 Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/staging/bayesian_optimization/bayesianOptimization.dml", "diff": "+#-------------------------------------------------------------\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+\n+# INPUT PARAMETERS:\n+# -----------------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# -----------------------------------------------------------------------------------------------------\n+# xTrain Matrix[Double] --- Trainings data x used to score the hyperparameter sets.\n+# y Matrix[Double] --- Trainings targets used to score the hyperparameter sets.\n+# params Frame[String] --- Name of the hyper parameters to optimize.\n+# paramValues Matrix[Double] --- Values of the hyper parameters to optimize.\n+# objective String --- The objective function to train a model with a set of hyperparameters.\n+# predictive String --- The predictive function used to calculate the score.\n+# acquisition String --- Name of the acquisition function to maximize.\n+# acquParams List[Unknown] --- List of params to apply to the acquisition function.\n+# kernel String --- Kernel function to use.\n+# kernelParams List[Unknown] --- List of params to apply to the kernel.\n+# iterations Integer --- Number of training iterations.\n+# randomSamples Integer 0 Number of random samples used to initialize the GaussianP.\n+# minimize Boolean TRUE Returns HP set with min score if true.\n+# verbose Boolean TRUE Prints additional information if true.\n+#\n+\n+m_bayesianOptimization = function(Matrix[Double] xTrain, Matrix[Double] yTrain, List[String] params, List[Unknown] paramValues,\n+ String objective, String predictive, String acquisition, List[Unknown] acquParams, String kernel, List[Unknown] kernelParams,\n+ Integer iterations, Integer randomSamples = 0, Boolean minimize = TRUE, Boolean verbose = TRUE)\n+return (Frame[Unknown] opt)\n+{\n+ numOfParams = length(params);\n+ HP = getMatrixOfParamCombinations(params, paramValues, verbose);\n+ numOfHPCombinations = nrow(HP);\n+ indexes = getNormalizedIndexes(nrow(HP));\n+\n+ idxScoreMap = getInitScoreAndHyperParamIndexes(\n+ xTrain\n+ , yTrain\n+ , objective\n+ , predictive\n+ , HP\n+ , numOfParams\n+ , randomSamples\n+ , verbose\n+ );\n+\n+ [means, stdDevs] = getMeansAndStdDevs(idxScoreMap, kernel, kernelParams, numOfHPCombinations, verbose);\n+\n+ for (i in 1:iterations) {\n+\n+ if(verbose) {\n+ print(\"Start iteration \" + i);\n+ }\n+\n+ idxScoreEntry = matrix(0,1,2);\n+ # use acquisition function to get index of next hyperparameter set to try.\n+ aArgs = concatArgsList(list(means, stdDevs), acquParams);\n+ nextHPSetIdx = as.scalar(eval(acquisition, aArgs)); # Although double is returned print throw error not being able to print a matrix without toString.\n+ nextHPSet = HP[nextHPSetIdx];\n+\n+ # eval expensive objective function with hyperparametsers.\n+ oArgs = concatArgsMat(list(xTrain, yTrain), nextHPSet);\n+ oResult = eval(objective, oArgs);\n+\n+ # score result\n+ pArgs = list(xTrain, yTrain, oResult);\n+ pResult = as.scalar(eval(predictive, pArgs));\n+\n+ idxScoreEntry[1, 1] = nextHPSetIdx;\n+ idxScoreEntry[1, 2] = pResult;\n+ idxScoreMap = rbind(idxScoreMap, idxScoreEntry);\n+\n+\n+ # update model\n+ [means, stdDevs] = getMeansAndStdDevs(idxScoreMap, kernel, kernelParams, numOfHPCombinations, verbose);\n+\n+ if(verbose) {\n+ print(\"\\nEnd iteration: \" + i + \"\\n sampled HP set: \" + toString(nextHPSet) + \"\\nPredictive: \" + toString(pResult));\n+ }\n+ }\n+\n+ [opt, finalIndex, finalScore] = getFinalHPSetAndScore(HP, idxScoreMap, minimize);\n+\n+ if(verbose) {\n+ print(\"\\nFinal sampled HP-index/score:\\n\" + toString(idxScoreMap, rows=nrow(idxScoreMap), decimal=10) +\n+ \"\\nOptimal parameters after \" + iterations + \" iterations:\\n\" + toString(opt) + \"\\nIndex:\\n\" + finalIndex + \"\\nScore:\\n\" + finalScore);\n+ }\n+}\n+\n+getMatrixOfParamCombinations = function(List[String] params, list[Unknown] paramValues, Boolean verbose)\n+return (Matrix[Double] HP)\n+{\n+ numParams = length(params);\n+ paramLens = matrix(0, numParams, 1);\n+ for( j in 1:numParams ) {\n+ vect = as.matrix(paramValues[j,1]);\n+ paramLens[j,1] = nrow(vect);\n+ }\n+ paramVals = matrix(0, numParams, max(paramLens));\n+ for(j in 1:numParams) {\n+ vect = as.matrix(paramValues[j,1]);\n+ paramVals[j,1:nrow(vect)] = t(vect);\n+ }\n+ cumLens = rev(cumprod(rev(paramLens))/rev(paramLens));\n+ numConfigs = prod(paramLens);\n+\n+ HP = matrix(0, numConfigs, numParams);\n+\n+ parfor( i in 1:nrow(HP) ) {\n+ for( j in 1:numParams )\n+ HP[i,j] = paramVals[j,as.scalar(((i-1)/cumLens[j,1])%%paramLens[j,1]+1)];\n+ }\n+\n+ if( verbose ) {\n+ print(\"BayesianOptimization: Hyper-parameter combinations(\" + numConfigs + \"):\\n\"+toString(HP, rows=nrow(HP), decimal=10));\n+ }\n+}\n+\n+getInitScoreAndHyperParamIndexes = function(Matrix[Double] xTrain, Matrix[Double] yTrain, String objective,\n+ String predictive, Matrix[Double] HP, Integer numOfParams, Integer numOfRandomeSamples, Boolean verbose = TRUE)\n+return(Matrix[Double] idxScoreMap) {\n+ maxIndex = nrow(HP);\n+ samples = sample(maxIndex, numOfRandomeSamples);\n+ usedHPs = matrix(0, numOfRandomeSamples, numOfParams);\n+ idxScoreMap = matrix(0, numOfRandomeSamples, 2);\n+\n+ for (sampleIdx in 1:numOfRandomeSamples) {\n+ rndNum = as.scalar(samples[sampleIdx,1]);\n+ idxScoreMap[sampleIdx,1] = rndNum;\n+ HPSet = HP[rndNum,];\n+\n+ # calc objective\n+ oArgs = concatArgsMat(list(xTrain, yTrain), HPSet);\n+ usedHPs[sampleIdx,] = HPSet[1,];\n+ objResult = eval(objective, oArgs);\n+\n+ # calc predictive / score\n+ pArgs = list(xTrain, yTrain, objResult);\n+ predResult = as.scalar(eval(predictive, pArgs);)\n+ idxScoreMap[sampleIdx,2] = predResult;\n+ }\n+\n+ if (verbose) {\n+ print(\"\\nInit model with random samples:\\nNormalized Indexes/Scores:\\n\" +\n+ toString(idxScoreMap[,2], rows=nrow(idxScoreMap)) +\n+ \"\\nhyperparameters:\\n\" + toString(usedHPs, rows=nrow(usedHPs)));\n+ }\n+}\n+\n+getNormalizedIndexes = function(Integer numOfSamples)\n+return (Matrix[Double] indexes)\n+{\n+ indexes = matrix(0, numOfSamples, 1);\n+ for (i in 1:numOfSamples) {\n+ indexes[i,1] = i/numOfSamples;\n+ }\n+}\n+\n+getMeansAndStdDevs = function(Matrix[Double] idxScoreMap, String kernel, List[Unknown] kernelParams, Double numOfHPCombinations, Boolean verbose)\n+return (Matrix[Double] means, Matrix[Double] stdDevs)\n+{\n+\n+ sampledIndexes = idxScoreMap[,1];\n+ scores = idxScoreMap[,2];\n+\n+ KArgs = concatArgsList(list(sampledIndexes, sampledIndexes), kernelParams);\n+ K = getK(sampledIndexes, kernel, kernelParams)\n+ K_inv = inv(K);\n+\n+\n+ means = matrix(0, numOfHPCombinations, 1);\n+ stdDevs = matrix(0, numOfHPCombinations, 1);\n+\n+ for (i in 1:numOfHPCombinations) {\n+\n+ xNew = as.matrix(i);\n+ Ks = getKs(sampledIndexes, i, kernel, kernelParams);\n+ Kss = getKss(i, kernel, kernelParams);\n+\n+\n+ means[i,1] = as.scalar(t(Ks)%*%K_inv%*%scores);\n+ stdDevs[i,1] = sqrt(abs(as.scalar(Kss - t(Ks) %*% K_inv %*% Ks)));\n+ }\n+\n+ if (verbose) {\n+ print(\"\\nMeans:\\n\" + toString(means, rows=nrow(means)) + \"\\nStdDevs:\\n\" + toString(stdDevs, rows=nrow(stdDevs)));\n+ }\n+\n+}\n+\n+getK = function(Matrix[Double] indexes, String kernel, List[Unknown] kernelArgs)\n+return(Matrix[Double] K)\n+{\n+ numOfRows = nrow(indexes);\n+ K = matrix(0, numOfRows, numOfRows);\n+\n+ for (i in 1:numOfRows) {\n+ x1 = as.scalar(indexes[i,1]);\n+ for (j in 1:numOfRows) {\n+ x2 = as.scalar(indexes[j,1]);\n+ kArgs = concatArgsList(list(x1, x2), kernelArgs);\n+ K[i,j] = eval(kernel, kArgs);\n+ }\n+ }\n+}\n+\n+getKs = function(Matrix[Double] indexes, Double xNew, String kernel, List[Unknown] kernelArgs)\n+return(Matrix[Double] Ks)\n+{\n+ numOfRows = nrow(indexes);\n+ Ks = matrix(0, numOfRows, 1);\n+\n+ for (i in 1:numOfRows) {\n+ x1 = xNew;\n+ x2 = as.scalar(indexes[i,1]);\n+ kArgs = concatArgsList(list(x1, x2), kernelArgs);\n+ Ks[i,1] = eval(kernel, kArgs);\n+ }\n+}\n+\n+getKss = function(Double xNew, String kernel, List[Unknown] kernelArgs)\n+return(Matrix[Double] Kss)\n+{\n+ Kss = matrix(0, 1, 1);\n+ kArgs = concatArgsList(list(xNew, xNew), kernelArgs);\n+ Kss[1,1] = eval(kernel, kArgs);\n+}\n+\n+concatArgsList = function(List[Unknown] a, List[Unknown] b)\n+return (List[Unknown] result)\n+{\n+ result = a;\n+ if ( length(b) != 0 ) {\n+ for(i in 1:length(b)) {\n+ result = append(result, b[i]);\n+ }\n+ }\n+}\n+\n+concatArgsMat = function(List[Unknown] a, Matrix[Double] b)\n+return (List[Unknown] result)\n+{\n+ result = a;\n+ for(i in 1:ncol(b)) {\n+ result = append(result, as.scalar(b[1,i]));\n+ }\n+}\n+\n+getFinalHPSetAndScore = function(Matrix[Double] HP, Matrix[Double] HPIdxScoreMap, Boolean minimize)\n+return (Frame[Unknown] opt, Double index, Double score)\n+{\n+ if (minimize) {\n+ mapIdx = as.scalar(rowIndexMin(t(HPIdxScoreMap[,2])));\n+ } else {\n+ mapIdx = as.scalar(rowIndexMax(t(HPIdxScoreMap[,2])));\n+ }\n+\n+ index = as.scalar(HPIdxScoreMap[mapIdx,1]);\n+ opt = as.frame(HP[index]);\n+ score = as.scalar(HPIdxScoreMap[mapIdx,2]);\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/staging/bayesian_optimization/test/bayesianOptimizationMLTest.dml", "diff": "+#-------------------------------------------------------------\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+source(\"./scripts/staging/bayesian_optimization/bayesianOptimization.dml\") as bayOpt;\n+\n+gaussianKernel = function(Double x1, Double x2, Double width = 1)\n+return (Double result)\n+{\n+ result = exp((-1)*((x1-x2)^2)/(2 * width^2));\n+}\n+\n+l2norm = function(Matrix[Double] X, Matrix[Double] y, Matrix[Double] B)\n+return (Matrix[Double] loss) {\n+ loss = as.matrix(sum((y - X%*%B)^2));\n+}\n+\n+lowerConfidenceBound = function(Matrix[Double] means, Matrix[Double] variances, Double beta)\n+return (Double index)\n+{\n+ alphas = means - beta * variances;\n+ index = as.scalar(rowIndexMin(t(alphas)));\n+}\n+\n+params = list(\"icpt\", \"reg\", \"tol\", \"maxi\", \"verbose\");\n+paramValues = list(as.matrix(0), 10^seq(0,-3), 10^seq(-6,-10), 10^seq(3,6), as.matrix(1));\n+\n+N = 200;\n+X = read($1);\n+y = read($2);\n+isMinimize = as.logical($3);\n+iter = as.integer($4)\n+\n+xTrain = X[1:N,];\n+yTrain = y[1:N,];\n+\n+Xtest = X[(N+1):nrow(X),];\n+ytest = y[(N+1):nrow(X),];\n+\n+opt = bayOpt::m_bayesianOptimization(\n+ xTrain = xTrain\n+ , yTrain = yTrain\n+ , params = params\n+ , paramValues = paramValues\n+ , objective = \"lm\"\n+ , predictive = \"l2norm\"\n+ , acquisition = \"lowerConfidenceBound\"\n+ , acquParams = list(60) # beta\n+ , kernel = \"gaussianKernel\"\n+ , kernelParams = list(5) # stddev\n+ , iterations = iter\n+ , randomSamples = 10\n+ , minimize = isMinimize\n+ , verbose = FALSE);\n+\n+B1 = lm(\n+ X=xTrain,\n+ y=yTrain,\n+ icpt = as.scalar(opt[1,1]),\n+ reg = as.scalar(opt[1,2]),\n+ tol = as.scalar(opt[1,3]),\n+ maxi = as.scalar(opt[1,4]),\n+ verbose = FALSE\n+);\n+\n+B2 = lm(X=xTrain, y=yTrain, verbose=FALSE);\n+\n+l1 = l2norm(Xtest, ytest, B1);\n+l2 = l2norm(Xtest, ytest, B2);\n+\n+print(\"\\nDefault Params: \" + as.scalar(l2) + \"\\nBayes: \" + as.scalar(l1));\n+\n+R = as.scalar(l1 < l2);\n+write(R, $5);\n+\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinBayesianOptimisationTest.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.apache.sysds.test.functions.builtin;\n+\n+import org.junit.Ignore;\n+import org.junit.Test;\n+import org.junit.Assert;\n+\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.lops.LopProperties.ExecType;\n+\n+public class BuiltinBayesianOptimisationTest extends AutomatedTestBase {\n+\n+ private final static String TEST_NAME = \"bayesianOptimization\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + BuiltinBayesianOptimisationTest.class.getSimpleName() + \"/\";\n+\n+ private final static int rows = 300;\n+ private final static int cols = 200;\n+\n+ @Override\n+ public void setUp()\n+ {\n+ addTestConfiguration(TEST_DIR, TEST_NAME);\n+ }\n+\n+ @Test\n+ public void bayesianOptimisationMLMinimisationTest() {\n+ testBayesianOptimization(\"TRUE\", 10, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void bayesianOptimisationMLMaximizationTest() {\n+ testBayesianOptimization(\"FALSE\", 20, ExecType.CP);\n+ }\n+\n+ @Ignore\n+ public void bayesianOptimisationMLMaximizationTestSpark() {\n+ testBayesianOptimization(\"FALSE\", 20, ExecType.SPARK);\n+ }\n+\n+\n+ public void testBayesianOptimization(String minimize, int iter, ExecType exec) {\n+\n+ ExecMode modeOld = setExecMode(exec);\n+\n+ try\n+ {\n+ TestConfiguration config = getTestConfiguration(TEST_NAME);\n+ loadTestConfiguration(config);\n+ fullDMLScriptName = \"./scripts/staging/bayesian_optimization/test/bayesianOptimizationMLTest.dml\";\n+ programArgs = new String[] {\"-args\", input(\"X\"), input(\"y\"),\n+ String.valueOf(minimize), String.valueOf(iter), output(\"R\")};\n+ double[][] X = getRandomMatrix(rows, cols, 0, 1, 0.7, 1);\n+ double[][] y = getRandomMatrix(rows, 1, 0, 1, 1, 2);\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+ writeInputMatrixWithMTD(\"y\", y, true);\n+\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+ Assert.assertTrue(TestUtils.readDMLBoolean(output(\"R\")));\n+ }\n+ finally {\n+ resetExecMode(modeOld);\n+ }\n+ }\n+}\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2872] Bayesian Optimization Algorithm DIA project WS2020/21 Closes #1155.
49,735
26.02.2021 12:44:42
-3,600
a90022639d1d39bfd35abce2f0aeb0c53b1bbd00
Built-in CorrectTypos The function fixes the spelling errors by replacing them with similar frequent value in the column. DIA project WS2020/21 Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -86,6 +86,7 @@ public enum Builtins {\nCONV2D(\"conv2d\", false),\nCONV2D_BACKWARD_FILTER(\"conv2d_backward_filter\", false),\nCONV2D_BACKWARD_DATA(\"conv2d_backward_data\", false),\n+ CORRECTTYPOS(\"correctTypos\", true),\nCOS(\"cos\", false),\nCOV(\"cov\", false),\nCOSH(\"cosh\", false),\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/util/UtilFunctions.java", "new_path": "src/main/java/org/apache/sysds/runtime/util/UtilFunctions.java", "diff": "@@ -631,6 +631,16 @@ public class UtilFunctions {\nreturn \"\\\"\" + s + \"\\\"\";\n}\n+ public static int getAsciiAtIdx(String s, int idx) {\n+ int strlen = s.length();\n+ int c = 0;\n+ int javaIdx = idx - 1;\n+ if (javaIdx >= 0 && javaIdx < strlen) {\n+ c = (int)s.charAt(javaIdx);\n+ }\n+ return c;\n+ }\n+\n/**\n* Parses a memory size with optional g/m/k quantifiers into its\n* number representation.\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinCorrectTyposTest.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.apache.sysds.test.functions.builtin;\n+\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.common.Types.FileFormat;\n+import org.apache.sysds.lops.LopProperties.ExecType;\n+import org.apache.sysds.runtime.io.FrameWriter;\n+import org.apache.sysds.runtime.io.FrameWriterFactory;\n+import org.apache.sysds.runtime.matrix.data.FrameBlock;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.junit.Assert;\n+import org.junit.Ignore;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+import java.util.ArrayList;\n+import java.util.Collections;\n+import java.util.List;\n+import java.util.Random;\n+\n+public class BuiltinCorrectTyposTest extends AutomatedTestBase\n+{\n+ private final static String TEST_NAME = \"correct_typos\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinCorrectTyposTest.class.getSimpleName() + \"/\";\n+\n+ private final static Types.ValueType[] schema = {Types.ValueType.STRING};\n+\n+ private final static int numberDataPoints = 500;\n+ private final static int maxFrequencyErrors = 10;\n+ private final static boolean corruptData = true;\n+ // for every error number below between (1 and maxFrequencyErrors) identical errors are made\n+ // errors can still overlap though\n+ private final static int numberCharSwaps = 5;\n+ private final static int numberCharChanges = 5;\n+ private final static int numberCharAdds = 5;\n+ private final static int numberCharDeletions = 5;\n+ private final static int numberWrongCapitalizations = 10;\n+\n+ private static Random generator;\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 testCorrectTyposCPReport() throws IOException {\n+ runCorrectTyposTest(\"TRUE\", 0.1, 3,\n+ \"FALSE\", \"FALSE\", 41, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testCorrectTyposCPCorrect() throws IOException {\n+ runCorrectTyposTest(\"TRUE\", 0.05, 3,\n+ \"TRUE\", \"FALSE\", 42,true, ExecType.CP);\n+ }\n+\n+ // TODO: Computing incorrect results for Spark\n+ @Ignore\n+ public void testCorrectTyposSP() throws IOException {\n+ runCorrectTyposTest(\"TRUE\", 0.05, 3, \"TRUE\",\n+ \"FALSE\", 42, true, ExecType.SPARK);\n+ }\n+\n+\n+ private void runCorrectTyposTest(String decapitalize, double frequency_threshold, int distance_threshold,\n+ String correct, String is_verbose, Integer seed, boolean runVerify, ExecType instType) throws IOException\n+ {\n+ ExecMode platformOld = setExecMode(instType);\n+\n+ System.out.println(\"Begin CorrectTyposTest\");\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[]{\n+ \"-nvargs\", \"X=\" + input(\"X\"), \"Y=\" + output(\"Y\"),\n+ \"frequency_threshold=\" + frequency_threshold,\n+ \"distance_threshold=\" + distance_threshold,\n+ \"decapitalize=\" + decapitalize,\n+ \"correct=\" + correct,\n+ \"is_verbose=\" + is_verbose};\n+\n+ generator = (seed != null)? new Random(seed): new Random();\n+\n+ FrameBlock frame = new FrameBlock(schema);\n+ FrameBlock verificationFrame = new FrameBlock(schema);\n+ FrameWriter writer = FrameWriterFactory.createFrameWriter(FileFormat.CSV);\n+ initFrameData(frame, verificationFrame, decapitalize);\n+ verificationFrame = verificationFrame.slice(0, numberDataPoints-1, 0, 0, new FrameBlock());\n+ writer.writeFrameToHDFS(frame.slice(0, numberDataPoints-1, 0, 0, new FrameBlock()),\n+ input(\"X\"), frame.getNumRows(), 1);\n+\n+ System.out.println(\"Run test\");\n+ runTest(true, false, null, -1);\n+ System.out.println(\"DONE\");\n+ FrameBlock outputFrame = readDMLFrameFromHDFS(\"Y\", FileFormat.CSV);\n+ if(runVerify)\n+ verifyFrameData(verificationFrame, outputFrame);\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+\n+ private static void initFrameData(FrameBlock frame, FrameBlock verificationFrame, String decapitalize) {\n+ List<Integer> bins = new ArrayList<Integer>();\n+ String[] correctStrings = getCorrectData(numberDataPoints, bins);\n+ String[] corruptedStrings;\n+ if (corruptData) {\n+ corruptedStrings = getCorruptedData(correctStrings, bins, maxFrequencyErrors, numberCharSwaps,\n+ numberCharChanges, numberCharAdds, numberCharDeletions, numberWrongCapitalizations);\n+ } else {\n+ corruptedStrings = correctStrings;\n+ }\n+ if (decapitalize.equals(\"TRUE\")) {\n+ for (int i=0; i<correctStrings.length; ++i) {\n+ correctStrings[i] = correctStrings[i].toLowerCase();\n+ }\n+ }\n+ frame.appendColumn(corruptedStrings);\n+ verificationFrame.appendColumn(correctStrings);\n+ }\n+\n+\n+ private static String[] getCorrectData(int numberDataPoints, List<Integer> bins) {\n+\n+ String[] allCountries = new String[] {\"Austria\", \"Belarus\", \"Denmark\", \"Germany\", \"Italy\", \"Liechtenstein\"};\n+\n+ List<String> chosenCountries = new ArrayList<String>();\n+ int remainingDataPoints = numberDataPoints;\n+ bins.add(0);\n+ for (int i = 0; i < allCountries.length-1; i++) {\n+ int rand = generator.nextInt((int)(remainingDataPoints/Math.sqrt(allCountries.length)));\n+ for (int j = 0; j < rand; j++) {\n+ chosenCountries.add(allCountries[i]);\n+ }\n+ remainingDataPoints -= rand;\n+ bins.add(numberDataPoints - remainingDataPoints);\n+ }\n+ for (int i = 0; i < remainingDataPoints; i++) {\n+ chosenCountries.add(allCountries[allCountries.length - 1]);\n+ }\n+ bins.add(numberDataPoints);\n+ String[] string_array = new String[chosenCountries.size()];\n+ chosenCountries.toArray(string_array);\n+ return string_array;\n+ }\n+\n+ private static String[] getCorruptedData(String[] correctStrings, List<Integer> bins, int maxFrequencyErrors,\n+ int numberSwaps, int numberChanges, int numberAdds, int numberDeletions, int numberWrongCapitalizations) {\n+ String[] data = correctStrings.clone();\n+ for (int i = 0; i < numberSwaps; i++) {\n+ makeSwapErrors(data, bins, maxFrequencyErrors);\n+ }\n+ for (int i = 0; i < numberChanges; i++) {\n+ makeChangeErrors(data, bins, maxFrequencyErrors);\n+ }\n+ for (int i = 0; i < numberAdds; i++) {\n+ makeAddErrors(data, bins, maxFrequencyErrors);\n+ }\n+ for (int i = 0; i < numberDeletions; i++) {\n+ makeDeletionErrors(data, bins, maxFrequencyErrors);\n+ }\n+ for (int i = 0; i < numberWrongCapitalizations; i++) {\n+ makeCapitalizationErrors(data, bins, maxFrequencyErrors);\n+ }\n+ return data;\n+ }\n+\n+\n+\n+ private static void makeSwapErrors(String[] data, List<Integer> bins, int maxFrequencyErrors){\n+ int randIndex = generator.nextInt(data.length);\n+ int leftBinIndex = Integer.max(0, (-Collections.binarySearch(bins, randIndex) - 2));\n+ int rightBinIndex = Integer.max(1, (-Collections.binarySearch(bins, randIndex) - 1));\n+ int leftIndex = bins.get(leftBinIndex);\n+ int rightIndex = bins.get(rightBinIndex) - 1;\n+\n+ int charPos = generator.nextInt(data[randIndex].length() - 1) + 1;\n+ for (int j = 0; j < generator.nextInt(maxFrequencyErrors) + 1; j++) {\n+ int randErrorIndex = generator.nextInt(rightIndex + 1 - leftIndex) + leftIndex;\n+ String str = data[randErrorIndex];\n+ if (str.length() > 1 && charPos < str.length()) {\n+ data[randErrorIndex] = str.substring(0, charPos - 1) + str.charAt(charPos) + str.charAt(charPos - 1) +\n+ str.substring(charPos + 1);\n+ }\n+ }\n+ }\n+\n+ private static void makeChangeErrors(String[] data, List<Integer> bins, int maxFrequencyErrors){\n+ int randIndex = generator.nextInt(data.length);\n+ int leftBinIndex = Integer.max(0, (-Collections.binarySearch(bins, randIndex) - 2));\n+ int rightBinIndex = Integer.max(1, (-Collections.binarySearch(bins, randIndex) - 1));\n+ int leftIndex = bins.get(leftBinIndex);\n+ int rightIndex = bins.get(rightBinIndex) - 1;\n+\n+ int charPos = generator.nextInt(data[randIndex].length());\n+ String newChar = Character.toString((char)(generator.nextInt('z' + 1 - 'a') + 'a'));\n+ for (int j = 0; j < generator.nextInt(maxFrequencyErrors) + 1; j++) {\n+ int randErrorIndex = generator.nextInt(rightIndex + 1 - leftIndex) + leftIndex;\n+ String str = data[randErrorIndex];\n+ if (str.length() > 0 && charPos < str.length()) {\n+ data[randErrorIndex] = str.substring(0, charPos) + newChar + str.substring(charPos + 1);\n+ }\n+ }\n+ }\n+\n+ private static void makeAddErrors(String[] data, List<Integer> bins, int maxFrequencyErrors){\n+ int randIndex = generator.nextInt(data.length);\n+ int leftBinIndex = Integer.max(0, (-Collections.binarySearch(bins, randIndex) - 2));\n+ int rightBinIndex = Integer.max(1, (-Collections.binarySearch(bins, randIndex) - 1));\n+ int leftIndex = bins.get(leftBinIndex);\n+ int rightIndex = bins.get(rightBinIndex) - 1;\n+\n+ int charPos = generator.nextInt(data[randIndex].length() + 1);\n+ String newChar = Character.toString((char)(generator.nextInt('z' + 1 - 'a') + 'a'));\n+ for (int j = 0; j < generator.nextInt(maxFrequencyErrors) + 1; j++) {\n+ int randErrorIndex = generator.nextInt(rightIndex + 1 - leftIndex) + leftIndex;\n+ String str = data[randErrorIndex];\n+ if (str.length() > 0 && charPos < str.length() + 1) {\n+ data[randErrorIndex] = str.substring(0, charPos) + newChar + str.substring(charPos);\n+ }\n+ }\n+ }\n+\n+ private static void makeDeletionErrors(String[] data, List<Integer> bins, int maxFrequencyErrors){\n+ int randIndex = generator.nextInt(data.length);\n+ int leftBinIndex = Integer.max(0, (-Collections.binarySearch(bins, randIndex) - 2));\n+ int rightBinIndex = Integer.max(1, (-Collections.binarySearch(bins, randIndex) - 1));\n+ int leftIndex = bins.get(leftBinIndex);\n+ int rightIndex = bins.get(rightBinIndex) - 1;\n+\n+ int charPos = generator.nextInt(data[randIndex].length());\n+ for (int j = 0; j < generator.nextInt(maxFrequencyErrors) + 1; j++) {\n+ int randErrorIndex = generator.nextInt(rightIndex + 1 - leftIndex) + leftIndex;\n+ String str = data[randErrorIndex];\n+ if (str.length() > 1 && charPos < str.length()) {\n+ data[randErrorIndex] = str.substring(0, charPos) + str.substring(charPos + 1);\n+ }\n+ }\n+ }\n+\n+ private static void makeCapitalizationErrors(String[] data, List<Integer> bins, int maxFrequencyErrors){\n+ int randIndex = generator.nextInt(data.length);\n+ int leftBinIndex = Integer.max(0, (-Collections.binarySearch(bins, randIndex) - 2));\n+ int rightBinIndex = Integer.max(1, (-Collections.binarySearch(bins, randIndex) - 1));\n+ int leftIndex = bins.get(leftBinIndex);\n+ int rightIndex = bins.get(rightBinIndex) - 1;\n+\n+ for (int j = 0; j < generator.nextInt(maxFrequencyErrors) + 1; j++) {\n+ int randErrorIndex = generator.nextInt(rightIndex + 1 - leftIndex) + leftIndex;\n+ String str = data[randErrorIndex];\n+ if (str.length() > 0) {\n+ if (Character.isUpperCase(str.charAt(0))) {\n+ data[randErrorIndex] = str.substring(0, 1).toLowerCase() + str.substring(1);\n+ }\n+ else {\n+ data[randErrorIndex] = str.substring(0, 1).toUpperCase() + str.substring(1);\n+ }\n+ }\n+ }\n+ }\n+\n+ private static void verifyFrameData(FrameBlock verificationFrame, FrameBlock frame2) {\n+\n+ for (int i = 0; i < verificationFrame.getNumRows(); i++) {\n+ for (int j = 0; j < verificationFrame.getNumColumns(); j++) {\n+ String s1 = frame2.get(i, j).toString();\n+ String s2 = verificationFrame.get(i, j).toString();\n+ if (!s1.equals(s2)) {\n+ System.out.println(\"The DML data for cell (\" + i + \",\" + j + \") '\" + s1 + \"' i\" +\n+ \"s not equal to the expected value '\" + s2 + \"'\");\n+ Assert.fail(\"The DML data for cell (\" + i + \",\" + j + \") '\" + s1 + \"' is not equal \" +\n+ \"to the expected value '\" + s2 + \"'\");\n+ }\n+ }\n+ }\n+\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/correct_typos.dml", "diff": "+#-------------------------------------------------------------\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($X, data_type=\"frame\", format=\"csv\", header=FALSE);\n+Y = correctTypos(X, $frequency_threshold, $distance_threshold, $decapitalize, $correct, $is_verbose);\n+write(Y, $Y, format=\"csv\")\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2873] Built-in CorrectTypos The function fixes the spelling errors by replacing them with similar frequent value in the column. DIA project WS2020/21 Closes #1146. Co-authored-by: Tim Sagaster <[email protected]>
49,706
26.02.2021 14:28:44
-3,600
47cd04191f16e582811a5637afede020b4b15111
Python API Autogenerator This commit makes the generator work if called from the python folder, as well as before from the root folder of the project.
[ { "change_type": "MODIFY", "old_path": "src/main/python/generator/generator.py", "new_path": "src/main/python/generator/generator.py", "diff": "@@ -29,21 +29,23 @@ from parser import FunctionParser\nclass PythonAPIFileGenerator(object):\ntarget_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'systemds', 'operator', 'algorithm', 'builtin')\n- source_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))),'scripts', 'builtin')\nlicence_path = os.path.join('resources', 'template_python_script_license')\ntemplate_path = os.path.join('resources', 'template_python_script_imports')\n- licence = \"\"\n- imports = \"\"\n- generated_by = \"\"\n- generated_from = \"\"\n+ source_path :str\n+ licence : str\n+ imports: str\n+ generated_by : str\n+ generated_from : str\ninit_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'systemds', 'operator', 'algorithm', '__init__.py')\ninit_import = u\"from .builtin.{function} import {function} \\n\"\ninit_all = u\"__all__ = {functions} \\n\"\n- def __init__(self, extension: str='py'):\n+ def __init__(self, source_path:str, extension: str='py'):\nsuper(PythonAPIFileGenerator, self).__init__()\n+ self.source_path = source_path\n+\nself.extension = '.{extension}'.format(extension=extension)\nos.makedirs(self.__class__.target_path, exist_ok = True)\nself.function_names = list()\n@@ -54,7 +56,7 @@ class PythonAPIFileGenerator(object):\nwith open(os.path.join(path, self.__class__.licence_path), 'r') as f:\nself.licence = f.read()\n- self.generated_by = \"# Autogenerated By : \" + path + \".py\\n\"\n+ self.generated_by = \"# Autogenerated By : src/main/python/generator/generator.py\\n\"\nself.generated_from = \"# Autogenerated From : \"\ndef generate_file(self, filename: str, file_content: str, dml_file: str):\n@@ -68,7 +70,7 @@ class PythonAPIFileGenerator(object):\nwith open(target_file, \"w\") as new_script:\nnew_script.write(self.licence)\nnew_script.write(self.generated_by)\n- new_script.write(self.generated_from + dml_file + \"\\n\")\n+ new_script.write((self.generated_from + dml_file + \"\\n\").replace(\"../\",\"\").replace(\"src/main/python/generator/\",\"\"))\nnew_script.write(self.imports)\nnew_script.write(file_content)\n@@ -311,10 +313,14 @@ class PythonAPIDocumentationGenerator(object):\nif __name__ == \"__main__\":\n- f_parser = FunctionParser(PythonAPIFileGenerator.source_path)\n- doc_generator = PythonAPIDocumentationGenerator()\n+ if \"python\" in os.getcwd():\n+ source_path = os.path.join(\"../../../\",'scripts', 'builtin' )\n+ else:\n+ source_path = os.path.join(os.path.dirname(__file__),\"../../../../\",'scripts', 'builtin')\n+ file_generator = PythonAPIFileGenerator(source_path)\nfun_generator = PythonAPIFunctionGenerator()\n- file_generator = PythonAPIFileGenerator()\n+ f_parser = FunctionParser(source_path )\n+ doc_generator = PythonAPIDocumentationGenerator()\nfor dml_file in f_parser.files():\ntry:\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/generator/parser.py", "new_path": "src/main/python/generator/parser.py", "diff": "@@ -66,12 +66,14 @@ class FunctionParser(object):\nraise e\n# print(function_definition)\n- pattern = re.compile(self.__class__.parameter_pattern, flags=re.I|re.M)\n+ pattern = re.compile(\n+ self.__class__.parameter_pattern, flags=re.I | re.M)\nmatch = pattern.match(function_definition)\nparam_str, retval_str = match.group(1, 2)\nparameters = self.get_parameters(param_str)\nreturn_values = self.get_parameters(retval_str)\n- data = {'function_name': function_name, 'parameters': parameters, 'return_values':return_values}\n+ data = {'function_name': function_name,\n+ 'parameters': parameters, 'return_values': return_values}\nreturn data\ndef get_parameters(self, param_str: str):\n@@ -98,12 +100,14 @@ class FunctionParser(object):\ndef get_header_parameters(self, param_str: str):\nparameters = list()\n- pattern = re.compile(self.__class__.header_parameter_pattern, flags=re.I)\n+ pattern = re.compile(\n+ self.__class__.header_parameter_pattern, flags=re.I)\nfor param_line in [s for s in param_str.split(\"\\n\") if s]:\nmatch = pattern.match(param_line)\ntry:\n- parameters.append((match.group(1), match.group(2), match.group(3), match.group(4)))\n+ parameters.append((match.group(1), match.group(\n+ 2), match.group(3), match.group(4)))\nexcept Exception as e:\nif re.search(pattern=self.__class__.divider_pattern, string=param_line, flags=re.I | re.M) is not None:\ncontinue\n@@ -131,32 +135,39 @@ class FunctionParser(object):\noutput_parameters = self.get_header_parameters(h_output)\nexcept AttributeError as e:\nfile_name = os.path.basename(path)\n- print(\"[WARNING] Could not parse header in file \\'{file_name}\\'.\".format(file_name = file_name))\n+ print(\"[WARNING] Could not parse header in file \\'{file_name}\\'.\".format(\n+ file_name=file_name))\ninput_parameters = []\noutput_parameters = []\n- data = {'function_name': None, 'parameters': input_parameters, 'return_values':output_parameters}\n+ data = {'function_name': None, 'parameters': input_parameters,\n+ 'return_values': output_parameters}\nreturn data\ndef find_header_input_params(self, path: str):\nwith open(path, 'r') as f:\ncontent = f.read()\n- start = re.search(pattern=self.__class__.header_input_pattern, string=content, flags=re.I | re.M).end()\n- end = re.search(pattern=self.__class__.header_output_pattern, string=content, flags=re.I | re.M).start()\n+ start = re.search(pattern=self.__class__.header_input_pattern,\n+ string=content, flags=re.I | re.M).end()\n+ end = re.search(pattern=self.__class__.header_output_pattern,\n+ string=content, flags=re.I | re.M).start()\nheader = content[start:end]\nreturn header\ndef find_header_output_params(self, path: str):\nwith open(path, 'r') as f:\ncontent = f.read()\n- start = re.search(pattern=self.__class__.header_output_pattern, string=content, flags=re.I | re.M).end()\n- end = re.search(pattern=self.__class__.function_pattern, string=content, flags=re.I | re.M).start()\n+ start = re.search(pattern=self.__class__.header_output_pattern,\n+ string=content, flags=re.I | re.M).end()\n+ end = re.search(pattern=self.__class__.function_pattern,\n+ string=content, flags=re.I | re.M).start()\nheader = content[start:end]\nreturn header\ndef find_function_definition(self, path: str):\nwith open(path, 'r') as f:\ncontent = f.read()\n- match = re.search(pattern=self.__class__.function_pattern, string=content, flags=re.I | re.M)\n+ match = re.search(pattern=self.__class__.function_pattern,\n+ string=content, flags=re.I | re.M)\nstart = match.start()\nend = match.end()\nreturn content[start:end]\n@@ -174,7 +185,8 @@ class FunctionParser(object):\ntype_mapping_pattern = r\"^([^\\[\\s]+)\"\npath = os.path.dirname(__file__)\n- type_mapping_path = os.path.join(path, self.__class__.type_mapping_file)\n+ type_mapping_path = os.path.join(\n+ path, self.__class__.type_mapping_file)\n# print(type_mapping_path)\nwith open(type_mapping_path, 'r') as mapping:\ntype_mapping = json.load(mapping)\n@@ -184,10 +196,12 @@ class FunctionParser(object):\nif header_param_names != data_param_names:\nprint(\"[ERROR] The parameter names of the function does not match with the documentation \"\n\"for file \\'{file_name}\\'.\".format(file_name=data[\"function_name\"]))\n- raise ValueError(\"The parameter names of the function does not match with the documentation\")\n+ raise ValueError(\n+ \"The parameter names of the function does not match with the documentation\")\nheader_param_type = [p[1].lower() for p in header[\"parameters\"]]\n- header_param_type = [type_mapping[\"type\"].get(item, item) for item in header_param_type]\n+ header_param_type = [type_mapping[\"type\"].get(\n+ item, item) for item in header_param_type]\ndata_param_type = [p[1].lower() for p in data[\"parameters\"]]\ndata_param_type = [type_mapping[\"type\"].get(\n@@ -197,7 +211,8 @@ class FunctionParser(object):\nif header_param_type != data_param_type:\nprint(\"[ERROR] The parameter type of the function does not match with the documentation \"\n\"for file \\'{file_name}\\'.\".format(file_name=data[\"function_name\"]))\n- raise ValueError(\"The parameter type of the function does not match with the documentation\")\n+ raise ValueError(\n+ \"The parameter type of the function does not match with the documentation\")\n# header_param_default = [p[2].lower() for p in header[\"parameters\"]]\n# header_param_default = [type_mapping[\"default\"].get(item, item).lower() for item in header_param_default]\n@@ -207,4 +222,3 @@ class FunctionParser(object):\n# print(\"[ERROR] The parameter default of the function does not match with the documentation \"\n# \"for file \\'{file_name}\\'.\".format(file_name=data[\"function_name\"]))\n# raise ValueError(\"The parameter default of the function does not match with the documentation\")\n-\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/__init__.py", "new_path": "src/main/python/systemds/operator/algorithm/__init__.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\nfrom .builtin.l2svm import l2svm\nfrom .builtin.multiLogRegPredict import multiLogRegPredict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/alsTopkPredict.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/alsTopkPredict.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/alsTopkPredict.dml\nfrom typing import Dict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/kmeans.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/kmeans.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/kmeans.dml\nfrom typing import Dict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/kmeansPredict.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/kmeansPredict.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/kmeansPredict.dml\nfrom typing import Dict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/l2svm.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/l2svm.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/l2svm.dml\nfrom typing import Dict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/lm.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/lm.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/lm.dml\nfrom typing import Dict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/multiLogReg.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/multiLogReg.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/multiLogReg.dml\nfrom typing import Dict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/multiLogRegPredict.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/multiLogRegPredict.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/multiLogRegPredict.dml\nfrom typing import Dict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/pca.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/pca.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/pca.dml\nfrom typing import Dict\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/builtin/toOneHot.py", "new_path": "src/main/python/systemds/operator/algorithm/builtin/toOneHot.py", "diff": "#\n# -------------------------------------------------------------\n-# Autogenerated By : src/main/python/generator.py\n+# Autogenerated By : src/main/python/generator/generator.py\n# Autogenerated From : scripts/builtin/toOneHot.dml\nfrom typing import Dict\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2871] Python API Autogenerator This commit makes the generator work if called from the python folder, as well as before from the root folder of the project.
49,722
11.01.2021 01:11:47
-3,600
8565b1db948fc7222e3227a84622c6714fa6e425
Federated covariance Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/BinaryFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/BinaryFEDInstruction.java", "diff": "@@ -35,6 +35,11 @@ public abstract class BinaryFEDInstruction extends ComputationFEDInstruction {\nsuper(type, op, in1, in2, out, opcode, istr);\n}\n+ public BinaryFEDInstruction(FEDInstruction.FEDType type, Operator op,\n+ CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out, String opcode, String istr) {\n+ super(type, op, in1, in2, in3, out, opcode, istr);\n+ }\n+\npublic static BinaryFEDInstruction parseInstruction(String str) {\nif(str.startsWith(ExecType.SPARK.name())) {\n// rewrite the spark instruction to a cp instruction\n@@ -67,6 +72,29 @@ public abstract class BinaryFEDInstruction extends ComputationFEDInstruction {\nthrow new DMLRuntimeException(\"Federated binary operations not yet supported:\" + opcode);\n}\n+ protected static String parseBinaryInstruction(String instr, CPOperand in1, CPOperand in2, CPOperand out) {\n+ String[] parts = InstructionUtils.getInstructionPartsWithValueType(instr);\n+ InstructionUtils.checkNumFields ( parts, 3, 4 );\n+ String opcode = parts[0];\n+ in1.split(parts[1]);\n+ in2.split(parts[2]);\n+ out.split(parts[3]);\n+ return opcode;\n+ }\n+\n+ protected static String parseBinaryInstruction(String instr, CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out) {\n+ String[] parts = InstructionUtils.getInstructionPartsWithValueType(instr);\n+ InstructionUtils.checkNumFields ( parts, 4 );\n+\n+ String opcode = parts[0];\n+ in1.split(parts[1]);\n+ in2.split(parts[2]);\n+ in3.split(parts[3]);\n+ out.split(parts[4]);\n+\n+ return opcode;\n+ }\n+\nprotected static void checkOutputDataType(CPOperand in1, CPOperand in2, CPOperand out) {\n// check for valid data type of output\nif( (in1.getDataType() == DataType.MATRIX || in2.getDataType() == DataType.MATRIX) && out.getDataType() != DataType.MATRIX )\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "diff": "@@ -136,6 +136,9 @@ public class FEDInstructionUtils {\nfedinst = AppendFEDInstruction.parseInstruction(inst.getInstructionString());\nelse if(instruction.getOpcode().equals(\"qpick\"))\nfedinst = QuantilePickFEDInstruction.parseInstruction(inst.getInstructionString());\n+ else if(\"cov\".equals(instruction.getOpcode()) && (ec.getMatrixObject(instruction.input1).isFederated(FType.ROW) ||\n+ ec.getMatrixObject(instruction.input2).isFederated(FType.ROW)))\n+ fedinst = CovarianceFEDInstruction.parseInstruction(inst.getInstructionString());\nelse\nfedinst = BinaryFEDInstruction.parseInstruction(inst.getInstructionString());\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedCovarianceTest.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.apache.sysds.test.functions.federated.primitives;\n+\n+import java.util.Arrays;\n+import java.util.Collection;\n+\n+import org.apache.sysds.api.DMLScript;\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.runtime.meta.MatrixCharacteristics;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+\n+@RunWith(value = Parameterized.class)\[email protected]\n+public class FederatedCovarianceTest extends AutomatedTestBase {\n+\n+ private final static String TEST_NAME1 = \"FederatedCovarianceTest\";\n+ private final static String TEST_NAME2 = \"FederatedCovarianceAlignedTest\";\n+ private final static String TEST_DIR = \"functions/federated/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + FederatedCovarianceTest.class.getSimpleName() + \"/\";\n+\n+ private final static int blocksize = 1024;\n+ @Parameterized.Parameter\n+ public int rows;\n+ @Parameterized.Parameter(1)\n+ public int cols;\n+\n+ @Parameterized.Parameters\n+ public static Collection<Object[]> data() {\n+ return Arrays.asList(new Object[][] {\n+ {20, 1},\n+// {100, 1}, {1000, 1}\n+ });\n+ }\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] {\"S.scalar\"}));\n+ addTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] {\"S.scalar\"}));\n+ }\n+\n+ @Test\n+ public void testCovCP() { runCovTest(ExecMode.SINGLE_NODE, false); }\n+\n+ @Test\n+ public void testAlignedCovCP() { runCovTest(ExecMode.SINGLE_NODE, true); }\n+\n+ private void runCovTest(ExecMode execMode, boolean alignedFedInput) {\n+ boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\n+ ExecMode platformOld = rtplatform;\n+\n+ if(rtplatform == ExecMode.SPARK)\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+\n+ String TEST_NAME = alignedFedInput ? TEST_NAME2 : TEST_NAME1;\n+\n+ getAndLoadTestConfiguration(TEST_NAME);\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+\n+ // write input matrices\n+ int r = r = rows / 4;\n+ int c = cols;\n+\n+ // empty script name because we don't execute any script, just start the worker\n+ fullDMLScriptName = \"\";\n+\n+ double[][] X1 = getRandomMatrix(r, c, 1, 5, 1, 3);\n+ double[][] X2 = getRandomMatrix(r, c, 1, 5, 1, 7);\n+ double[][] X3 = getRandomMatrix(r, c, 1, 5, 1, 8);\n+ double[][] X4 = getRandomMatrix(r, c, 1, 5, 1, 9);\n+\n+ MatrixCharacteristics mc = new MatrixCharacteristics(r, c, blocksize, r * c);\n+ writeInputMatrixWithMTD(\"X1\", X1, false, mc);\n+ writeInputMatrixWithMTD(\"X2\", X2, false, mc);\n+ writeInputMatrixWithMTD(\"X3\", X3, false, mc);\n+ writeInputMatrixWithMTD(\"X4\", X4, false, mc);\n+\n+ // empty script name because we don't execute any script, just start the worker\n+ fullDMLScriptName = \"\";\n+ int port1 = getRandomAvailablePort();\n+ int port2 = getRandomAvailablePort();\n+ int port3 = getRandomAvailablePort();\n+ int port4 = getRandomAvailablePort();\n+ Thread t1 = startLocalFedWorkerThread(port1, FED_WORKER_WAIT_S);\n+ Thread t2 = startLocalFedWorkerThread(port2, FED_WORKER_WAIT_S);\n+ Thread t3 = startLocalFedWorkerThread(port3, FED_WORKER_WAIT_S);\n+ Thread t4 = startLocalFedWorkerThread(port4);\n+\n+ rtplatform = execMode;\n+ if(rtplatform == ExecMode.SPARK) {\n+ System.out.println(7);\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+ }\n+ TestConfiguration config = availableTestConfigurations.get(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ if(alignedFedInput) {\n+ double[][] Y1 = getRandomMatrix(r, c, 1, 5, 1, 3);\n+ double[][] Y2 = getRandomMatrix(r, c, 1, 5, 1, 7);\n+ double[][] Y3 = getRandomMatrix(r, c, 1, 5, 1, 8);\n+ double[][] Y4 = getRandomMatrix(r, c, 1, 5, 1, 9);\n+\n+ writeInputMatrixWithMTD(\"Y1\", Y1, false, mc);\n+ writeInputMatrixWithMTD(\"Y2\", Y2, false, mc);\n+ writeInputMatrixWithMTD(\"Y3\", Y3, false, mc);\n+ writeInputMatrixWithMTD(\"Y4\", Y4, false, mc);\n+\n+ // Run reference dml script with normal matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-args\", input(\"X1\"), input(\"X2\"), input(\"X3\"), input(\"X4\"),\n+ input(\"Y1\"), input(\"Y2\"), input(\"Y3\"), input(\"Y4\"), expected(\"S\")};\n+ runTest(null);\n+\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-nvargs\",\n+ \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"X1\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"X2\")),\n+ \"in_X3=\" + TestUtils.federatedAddress(port3, input(\"X3\")),\n+ \"in_X4=\" + TestUtils.federatedAddress(port4, input(\"X4\")),\n+ \"in_Y1=\" + TestUtils.federatedAddress(port1, input(\"Y1\")),\n+ \"in_Y2=\" + TestUtils.federatedAddress(port2, input(\"Y2\")),\n+ \"in_Y3=\" + TestUtils.federatedAddress(port3, input(\"Y3\")),\n+ \"in_Y4=\" + TestUtils.federatedAddress(port4, input(\"Y4\")),\n+ \"rows=\" + rows, \"cols=\" + cols, \"out_S=\" + output(\"S\")};\n+ runTest(null);\n+\n+ } else {\n+ double[][] Y = getRandomMatrix(rows, c, 1, 5, 1, 3);\n+ writeInputMatrixWithMTD(\"Y\", Y, false, new MatrixCharacteristics(rows, cols, blocksize, r*c));\n+\n+ // Run reference dml script with normal matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-args\", input(\"X1\"), input(\"X2\"), input(\"X3\"), input(\"X4\"),\n+ input(\"Y\"), expected(\"S\"),};\n+ runTest(null);\n+\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-nvargs\",\n+ \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"X1\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"X2\")),\n+ \"in_X3=\" + TestUtils.federatedAddress(port3, input(\"X3\")),\n+ \"in_X4=\" + TestUtils.federatedAddress(port4, input(\"X4\")),\n+ \"Y=\" + input(\"Y\"), \"rows=\" + rows, \"cols=\" + cols, \"out_S=\" + output(\"S\")};\n+ runTest(null);\n+ }\n+\n+ // compare via files\n+ compareResults(1e-2);\n+ Assert.assertTrue(heavyHittersContainsString(\"fed_cov\"));\n+\n+ TestUtils.shutdownThreads(t1, t2, t3, t4);\n+ rtplatform = platformOld;\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\n+ }\n+}\n+\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedRemoveEmptyTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedRemoveEmptyTest.java", "diff": "@@ -49,7 +49,6 @@ public class FederatedRemoveEmptyTest extends AutomatedTestBase {\npublic int rows;\[email protected](1)\npublic int cols;\n-\[email protected](2)\npublic boolean rowPartitioned;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedCovarianceAlignedTest.dml", "diff": "+#-------------------------------------------------------------\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 = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+\n+B = federated(addresses=list($in_Y1, $in_Y2, $in_Y3, $in_Y4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+\n+s = cov(A, B);\n+write(s, $out_S);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedCovarianceAlignedTestReference.dml", "diff": "+#-------------------------------------------------------------\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+\n+A = rbind(read($1), read($2), read($3), read($4));\n+B = rbind(read($5), read($6), read($7), read($8));\n+\n+s = cov(A, B);\n+write(s, $9);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedCovarianceTest.dml", "diff": "+#-------------------------------------------------------------\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 = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+B = read($Y);\n+\n+s = cov(A, B);\n+write(s, $out_S);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedCovarianceTestReference.dml", "diff": "+#-------------------------------------------------------------\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+\n+A = rbind(read($1), read($2), read($3), read($4));\n+B = read($5);\n+\n+s = cov(A, B);\n+write(s, $6);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2766] Federated covariance Closes #1150
49,722
25.02.2021 17:48:49
-7,200
96fc29434ff9877fbf170c09e58666d8040e6727
test encoder serialization Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/transform/EncoderSerializationTest.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.apache.sysds.test.functions.transform;\n+\n+import java.io.ByteArrayInputStream;\n+import java.io.ByteArrayOutputStream;\n+import java.io.IOException;\n+import java.io.ObjectInput;\n+import java.io.ObjectInputStream;\n+import java.io.ObjectOutputStream;\n+import java.util.List;\n+\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.runtime.matrix.data.FrameBlock;\n+import org.apache.sysds.runtime.transform.encode.Encoder;\n+import org.apache.sysds.runtime.transform.encode.EncoderComposite;\n+import org.apache.sysds.runtime.transform.encode.EncoderFactory;\n+import org.apache.sysds.runtime.util.UtilFunctions;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.Test;\n+\n+public class EncoderSerializationTest extends AutomatedTestBase\n+{\n+ private final static int rows = 2791;\n+ private final static int cols = 8;\n+\n+ private final static Types.ValueType[] schemaStrings = new Types.ValueType[]{\n+ Types.ValueType.STRING, Types.ValueType.STRING, Types.ValueType.STRING, Types.ValueType.STRING,\n+ Types.ValueType.STRING, Types.ValueType.STRING, Types.ValueType.STRING, Types.ValueType.STRING};\n+ private final static Types.ValueType[] schemaMixed = new Types.ValueType[]{\n+ Types.ValueType.STRING, Types.ValueType.FP64, Types.ValueType.INT64, Types.ValueType.BOOLEAN,\n+ Types.ValueType.STRING, Types.ValueType.FP64, Types.ValueType.INT64, Types.ValueType.BOOLEAN};\n+\n+\n+ public enum TransformType {\n+ RECODE,\n+ DUMMY\n+ }\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ }\n+\n+ @Test\n+ public void testComposite1() { runTransformSerTest(TransformType.DUMMY, schemaStrings); }\n+\n+ @Test\n+ public void testComposite2() { runTransformSerTest(TransformType.RECODE, schemaMixed); }\n+\n+ @Test\n+ public void testComposite3() { runTransformSerTest(TransformType.RECODE, schemaStrings); }\n+\n+ @Test\n+ public void testComposite4() { runTransformSerTest(TransformType.DUMMY, schemaMixed); }\n+\n+\n+ private void runTransformSerTest(TransformType type, Types.ValueType[] schema) {\n+ //data generation\n+ double[][] A = getRandomMatrix(rows, cols, -10, 10, 0.9, 8234);\n+\n+ //init data frame\n+ FrameBlock frame = new FrameBlock(schema);\n+\n+ //init data frame\n+ Object[] row = new Object[schema.length];\n+ for( int i=0; i < rows; i++) {\n+ for( int j=0; j<schema.length; j++ )\n+ A[i][j] = UtilFunctions.objectToDouble(schema[j],\n+ row[j] = UtilFunctions.doubleToObject(schema[j], A[i][j]));\n+ frame.appendRow(row);\n+ }\n+\n+ String spec = \"\";\n+ if(type == TransformType.DUMMY)\n+ spec = \"{\\n \\\"ids\\\": true\\n, \\\"dummycode\\\":[ 2, 7, 8, 1 ]\\n\\n}\";\n+ else if(type == TransformType.RECODE)\n+ spec = \"{\\n \\\"ids\\\": true\\n, \\\"recode\\\":[ 2, 7, 1, 8 ]\\n\\n}\";\n+\n+\n+ frame.setSchema(schema);\n+ String[] cnames = frame.getColumnNames();\n+\n+ Encoder encoderIn = EncoderFactory.createEncoder(spec, cnames, frame.getNumColumns(), null);\n+ EncoderComposite encoderOut;\n+\n+ // serialization and deserialization\n+ encoderOut = (EncoderComposite) serializeDeserialize(encoderIn);\n+ // compare\n+ Assert.assertArrayEquals(encoderIn.getColList(), encoderOut.getColList());\n+ Assert.assertEquals(encoderIn.getNumCols(), encoderOut.getNumCols());\n+\n+ List<Encoder> eListIn = ((EncoderComposite) encoderIn).getEncoders();\n+ List<Encoder> eListOut = encoderOut.getEncoders();\n+ for(int i = 0; i < eListIn.size(); i++) {\n+ Assert.assertArrayEquals(eListIn.get(i).getColList(), eListOut.get(i).getColList());\n+ Assert.assertEquals(eListIn.get(i).getNumCols(), eListOut.get(i).getNumCols());\n+ }\n+ }\n+\n+ private Encoder serializeDeserialize(Encoder encoderIn) {\n+ try {\n+ ByteArrayOutputStream bos = new ByteArrayOutputStream();\n+ ObjectOutputStream oos = new ObjectOutputStream(bos);\n+ oos.writeObject(encoderIn);\n+ oos.flush();\n+ byte[] encoderBytes = bos.toByteArray();\n+\n+ ByteArrayInputStream bis = new ByteArrayInputStream(encoderBytes);\n+ ObjectInput in = new ObjectInputStream(bis);\n+ Encoder encoderOut = (Encoder) in.readObject();\n+\n+ return encoderOut;\n+ }\n+ catch(IOException | ClassNotFoundException e) {\n+ e.printStackTrace();\n+ }\n+ return null;\n+ }\n+}\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2878] test encoder serialization Closes #1192
49,689
28.02.2021 14:48:53
-3,600
68e5e298c73d1013c528d76c789dba77fd106eb8
Add test for a mini-batch scenario with dedup This patch fixes a bug in placeholder handling in lineage deuplication. In addition, it adds a test to reuse preprocessing in a mini-batch like scenario with deduplication.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/parser/WhileStatementBlock.java", "new_path": "src/main/java/org/apache/sysds/parser/WhileStatementBlock.java", "diff": "@@ -21,6 +21,7 @@ package org.apache.sysds.parser;\nimport java.util.ArrayList;\nimport java.util.HashMap;\n+import java.util.HashSet;\nimport org.apache.sysds.conf.ConfigurationManager;\nimport org.apache.sysds.hops.Hop;\n@@ -259,11 +260,12 @@ public class WhileStatementBlock extends StatementBlock\n// By calling getInputstoSB on all the child statement blocks,\n// we remove the variables only read in the while predicate but\n// never used in the body from the input list.\n- ArrayList<String> inputs = new ArrayList<>();\n+ HashSet<String> inputs = new HashSet<>();\nWhileStatement fstmt = (WhileStatement)_statements.get(0);\nfor (StatementBlock sb : fstmt.getBody())\ninputs.addAll(sb.getInputstoSB());\n- return inputs;\n+ // Hashset ensures no duplicates in the variable list\n+ return new ArrayList<>(inputs);\n}\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCache.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCache.java", "diff": "@@ -329,6 +329,28 @@ public class LineageCache\nreturn p;\n}\n+ //This method is for hard removal of an entry, w/o maintaining eviction data structures\n+ public static void removeEntry(LineageItem key) {\n+ boolean p = _cache.containsKey(key);\n+ if (!p) return;\n+ synchronized(_cache) {\n+ LineageCacheEntry e = getEntry(key);\n+ long size = e.getSize();\n+ if (e._origItem == null)\n+ _cache.remove(e._key);\n+\n+ else {\n+ LineageCacheEntry h = _cache.get(e._origItem); //head\n+ while (h != null) {\n+ LineageCacheEntry tmp = h;\n+ h = h._nextEntry;\n+ _cache.remove(tmp._key);\n+ }\n+ }\n+ LineageCacheEviction.updateSize(size, false);\n+ }\n+ }\n+\npublic static MatrixBlock getMatrix(LineageItem key) {\nLineageCacheEntry e = null;\nsynchronized( _cache ) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCacheEviction.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCacheEviction.java", "diff": "@@ -33,7 +33,7 @@ import org.apache.sysds.runtime.util.LocalFileUtils;\npublic class LineageCacheEviction\n{\n- private static long _cachesize = 0;\n+ protected static long _cachesize = 0;\nprivate static long CACHE_LIMIT; //limit in bytes\nprivate static long _startTimestamp = 0;\nprotected static final Map<LineageItem, Integer> _removelist = new HashMap<>();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageDedupUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageDedupUtils.java", "diff": "@@ -108,10 +108,15 @@ public class LineageDedupUtils {\nLineageItem[] liinputs = LineageItemUtils.getLineageItemInputstoSB(inputnames, ec);\n// TODO: find the inputs from the ProgramBlock instead of StatementBlock\nString ph = LineageItemUtils.LPLACEHOLDER;\n- for (int i=0; i<liinputs.length; i++) {\n+ int i = 0;\n+ for (String input : inputnames) {\n+ // Skip empty variables to correctly map lineage items to live variables\n+ if (ec.getVariable(input) == null)\n+ continue;\n// Wrap the inputs with order-preserving placeholders.\nLineageItem phInput = new LineageItem(ph+String.valueOf(i), new LineageItem[] {liinputs[i]});\n- _tmpLineage.set(inputnames.get(i), phInput);\n+ _tmpLineage.set(input, phInput);\n+ i++;\n}\n// also copy the dedupblock to trace the taken path (bitset)\n_tmpLineage.setDedupBlock(ldb);\n@@ -194,6 +199,11 @@ public class LineageDedupUtils {\n}\nroot.resetVisitStatusNR();\ncutAtPlaceholder(root);\n+ if (!LineageCacheConfig.ReuseCacheType.isNone())\n+ // These chopped DAGs can lead to incorrect reuse.\n+ // FIXME: This logic removes only the live variables from lineage cache.\n+ // Need a way to remove all entries that are cached in this iteration.\n+ LineageCache.removeEntry(root);\n}\nlmap.getTraces().keySet().removeAll(emptyRoots);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/lineage/DedupReuseTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/lineage/DedupReuseTest.java", "diff": "@@ -44,6 +44,7 @@ public class DedupReuseTest extends AutomatedTestBase\nprotected static final String TEST_NAME3 = \"DedupReuse3\";\nprotected static final String TEST_NAME4 = \"DedupReuse4\";\nprotected static final String TEST_NAME5 = \"DedupReuse5\";\n+ protected static final String TEST_NAME6 = \"DedupReuse6\";\nprotected String TEST_CLASS_DIR = TEST_DIR + DedupReuseTest.class.getSimpleName() + \"/\";\n@@ -54,7 +55,7 @@ public class DedupReuseTest extends AutomatedTestBase\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n- for(int i=1; i<=5; i++)\n+ for(int i=1; i<=6; i++)\naddTestConfiguration(TEST_NAME+i, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME+i));\n}\n@@ -88,6 +89,12 @@ public class DedupReuseTest extends AutomatedTestBase\ntestLineageTrace(TEST_NAME4);\n}\n+ @Test\n+ public void testLineageTrace6() {\n+ // Reuse minibatch-wise preprocessing in a mini-batch like scenario\n+ testLineageTrace(TEST_NAME6);\n+ }\n+\npublic void testLineageTrace(String testname) {\nboolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\nboolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/lineage/DedupReuse6.dml", "diff": "+#-------------------------------------------------------------\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+D = rand(rows=1000, cols=784, min=0, max=20, seed=42)\n+bs = 128;\n+ep = 5;\n+iter_ep = ceil(nrow(D)/bs);\n+maxiter = ep * iter_ep;\n+beg = 1;\n+iter = 0;\n+i = 1;\n+\n+while (iter < maxiter) {\n+ end = beg + bs - 1;\n+ if (end>nrow(D))\n+ end = nrow(D);\n+ X = D[beg:end,]\n+\n+ #reusable OP across epochs\n+ X = scale(X, TRUE, TRUE);\n+\n+ #not reusable OPs\n+ X = ((X + X) * i - X) / (i+1)\n+ X = ((X + X) * i - X) / (i+1)\n+ X = ((X + X) * i - X) / (i+1)\n+ X = ((X + X) * i - X) / (i+1)\n+ X = ((X + X) * i - X) / (i+1)\n+\n+ iter = iter + 1;\n+ if (end == nrow(D))\n+ beg = 1;\n+ else\n+ beg = end + 1;\n+ i = i + 1;\n+\n+}\n+write(X, $1, format=\"text\");\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2583] Add test for a mini-batch scenario with dedup This patch fixes a bug in placeholder handling in lineage deuplication. In addition, it adds a test to reuse preprocessing in a mini-batch like scenario with deduplication.
49,706
01.03.2021 12:00:58
-3,600
4649eb1f0363f12cd8b7e11b328089b7e6dc956d
[MINOR] Scale apply use ifelse operation
[ { "change_type": "MODIFY", "old_path": "scripts/builtin/scaleApply.dml", "new_path": "scripts/builtin/scaleApply.dml", "diff": "# NAME TYPE DEFAULT MEANING\n# ---------------------------------------------------------------------------------------------\n# X Matrix --- Input feature matrix\n-# ColMean Matrix --- The column means to subtract from X (not done if empty)\n-# Centering Matrix --- The column scaling to multiply with X (not done if empty)\n+# Centering Matrix --- The column means to subtract from X (not done if empty)\n+# ScaleFactor Matrix --- The column scaling to multiply with X (not done if empty)\n# ---------------------------------------------------------------------------------------------\n# Y Matrix --- Output feature matrix with K columns\n# ---------------------------------------------------------------------------------------------\nm_scaleApply = function(Matrix[Double] X, Matrix[Double] Centering, Matrix[Double] ScaleFactor)\nreturn (Matrix[Double] Y)\n{\n- if(nrow(Centering) > 0 & ncol(Centering) > 0){\n- Y = X - Centering\n- }\n- if(nrow(ScaleFactor) > 0 & ncol(ScaleFactor) > 0){\n- Y = X / ScaleFactor\n- }\n-\n+ centered = ifelse(nrow(Centering) > 0 & ncol(Centering) > 0, X - Centering, X)\n+ Y = ifelse(nrow(ScaleFactor) > 0 & ncol(ScaleFactor) > 0, centered / ScaleFactor, centered)\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Scale apply use ifelse operation
49,696
01.03.2021 17:36:57
-3,600
b26c3d91ad7d3af791407f91a521bd344b3d0edb
TomekLink builtin function Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/tomeklink.dml", "diff": "+#-------------------------------------------------------------\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+# UNDERSAMPLING TECHNIQUE;\n+# COMPUTES TOMEK LINKS AND DROPS THEM FROM DATA MATRIX AND LABEL VECTOR\n+# DROPS ONLY THE MAJORITY LABEL AND CORRESPONDING POINT OF TOMEK LINKS\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X MATRIX --- Data Matrix (nxm)\n+# y MATRIX --- Label Matrix (nx1)\n+# ---------------------------------------------------------------------------------------------\n+# OUTPUT:\n+# X_under - Data Matrix without Tomek links\n+# y_under - Labels corresponding to undersampled data\n+# drop_idx - Indices of dropped rows/labels wrt input\n+\n+\n+###### MAIN PART ######\n+\n+m_tomeklink = function(Matrix[Double] X, Matrix[Double] y)\n+ return (Matrix[Double] X_under, Matrix[Double] y_under, Matrix[Double] drop_idx) {\n+ majority_label = 0\n+ n = nrow(X)\n+ m = ncol(X)\n+\n+ tomek_links = get_links(X, y, majority_label)\n+\n+ X_under = matrix(0, rows = 0, cols = m)\n+ y_under = matrix(0, rows = 0, cols = 1)\n+ drop_idx = matrix(0, rows = 0, cols = 1)\n+\n+ for (i in 1:nrow(X)) {\n+ is_link = as.scalar(tomek_links[i, 1])\n+ if (is_link == 1) {\n+ X_under = rbind(X_under, X[i,])\n+ y_under = rbind(y_under, y[i,])\n+ drop_idx = rbind(drop_idx, matrix(i, rows = 1, cols = 1))\n+ }\n+ }\n+}\n+\n+###### END MAIN PART ######\n+\n+###### UTILS ######\n+\n+# nearest nb function ----------------------------------------------------------\n+get_nn = function(Matrix[Double] X)\n+ return (Matrix[Double] nn) {\n+ nn = matrix(0, rows = nrow(X), cols = 1)\n+ for (i in 1:nrow(X)) {\n+ dists = rowSums((X - X[i,])^2)\n+ sort_dists = order(target = dists, by = 1, decreasing = FALSE, index.return = TRUE)\n+ nn[i, 1] = as.scalar(sort_dists[2, 1]) # nearest, not self\n+ }\n+}\n+\n+# find tomek link function ----------------------------------------------------\n+get_links = function(Matrix[Double] X, Matrix[Double] y, double majority_label)\n+ return (Matrix[Double] tomek_links) {\n+ tomek_links = matrix(0, rows = nrow(X), cols = 1)\n+ nn = get_nn(X)\n+\n+ for (index in 1:nrow(X)) {\n+ # this is a tomek link according to R: ubTomek https://rdrr.io/cran/unbalanced/src/R/ubTomek.R\n+ # other sources define it as a pair of mutual nearest neighbor\n+ # where exactly one endpoint has the majority label\n+\n+ nn_index = as.scalar(nn[index, 1])\n+ label = as.scalar(y[index, 1])\n+ nn_label = as.scalar(y[nn_index, 1])\n+\n+ if (label != majority_label) {\n+ if (nn_label == majority_label) {\n+ tomek_links[nn_index, 1] = 1\n+ }\n+ }\n+ }\n+}\n+\n+###### END UTILS ######\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -225,6 +225,7 @@ public enum Builtins {\nTANH(\"tanh\", false),\nTRACE(\"trace\", false),\nTO_ONE_HOT(\"toOneHot\", true),\n+ TOMEKLINK(\"tomeklink\", true),\nTYPEOF(\"typeof\", false),\nCOUNT_DISTINCT(\"countDistinct\",false),\nCOUNT_DISTINCT_APPROX(\"countDistinctApprox\",false),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinTomeklinkTest.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.apache.sysds.test.functions.builtin;\n+\n+import org.junit.Test;\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.lops.LopProperties.ExecType;\n+import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+\n+import java.util.HashMap;\n+\n+public class BuiltinTomeklinkTest extends AutomatedTestBase\n+{\n+ private final static String TEST_NAME = \"tomeklink\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinTomeklinkTest.class.getSimpleName() + \"/\";\n+\n+ private final static double eps = 1e-3;\n+ private final static int rows = 53;\n+ private final static int cols = 6;\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 testTomeklinkCP() {\n+ runTomeklinkTest(ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testTomeklinkSP() {\n+ runTomeklinkTest(ExecType.SPARK);\n+ }\n+\n+ private void runTomeklinkTest(ExecType instType)\n+ {\n+ 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\"), input(\"B\"), output(\"C\")};\n+\n+ fullRScriptName = HOME + TEST_NAME + \".R\";\n+ rCmd = \"Rscript\" + \" \" + fullRScriptName + \" \" + inputDir() + \" \" + expectedDir();\n+\n+ //generate actual dataset\n+ double[][] A = getRandomMatrix(rows, cols, -1, 1, 0.7, 1);\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+\n+ double[][] B = getRandomMatrix(rows, 1, 0, 1, 0.5, 1);\n+ B = TestUtils.round(B);\n+ writeInputMatrixWithMTD(\"B\", B, true);\n+\n+ runTest(true, false, null, -1);\n+ runRScript(true);\n+\n+ //compare matrices\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromOutputDir(\"C\");\n+ HashMap<CellIndex, Double> rfile = readRMatrixFromExpectedDir(\"C\");\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/tomeklink.R", "diff": "+#-------------------------------------------------------------\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+\n+args = commandArgs(TRUE)\n+\n+library(\"unbalanced\")\n+library(\"Matrix\")\n+\n+X = as.matrix(readMM(paste(args[1], \"A.mtx\", sep=\"\")))\n+y = as.matrix(readMM(paste(args[1], \"B.mtx\", sep=\"\")))\n+\n+C = sort(ubTomek(X, y, verbose=FALSE)$id.rm)\n+writeMM(as(C, \"CsparseMatrix\"), paste(args[2], \"C\", sep=\"\"))\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/tomeklink.dml", "diff": "+#-------------------------------------------------------------\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+\n+X = read($1)\n+y = read($2)\n+\n+[X_under, y_under, drop_idx] = tomeklink(X, y)\n+write(drop_idx, $3) # sorted by default\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2877] TomekLink builtin function Closes #1186
49,688
01.03.2021 18:46:28
-3,600
d4ba5028635ff2011b22828ad1e372d1811fab95
[MINOR] Fix null check in EncoderMVImpute for Global_Mean; Also: * Adapted test so NaN is checked * removed unnecessary import * adapted count for mean calculation Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/transform/encode/EncoderMVImpute.java", "new_path": "src/main/java/org/apache/sysds/runtime/transform/encode/EncoderMVImpute.java", "diff": "@@ -48,8 +48,7 @@ import org.apache.wink.json4j.JSONArray;\nimport org.apache.wink.json4j.JSONException;\nimport org.apache.wink.json4j.JSONObject;\n-public class EncoderMVImpute extends Encoder\n-{\n+public class EncoderMVImpute extends Encoder {\nprivate static final long serialVersionUID = 9057868620144662194L;\npublic enum MVMethod { INVALID, GLOBAL_MEAN, GLOBAL_MODE, CONSTANT }\n@@ -69,8 +68,7 @@ public class EncoderMVImpute extends Encoder\npublic KahanObject[] getMeans() { return _meanList; }\npublic EncoderMVImpute(JSONObject parsedSpec, String[] colnames, int clen, int minCol, int maxCol)\n- throws JSONException\n- {\n+ throws JSONException {\nsuper(null, clen);\n//handle column list\n@@ -166,9 +164,15 @@ public class EncoderMVImpute extends Encoder\nif( _mvMethodList[j] == MVMethod.GLOBAL_MEAN ) {\n//compute global column mean (scale)\nlong off = _countList[j];\n- for( int i=0; i<in.getNumRows(); i++ )\n+ for( int i=0; i<in.getNumRows(); i++ ){\n+ Object key = in.get(i, colID-1);\n+ if(key == null){\n+ off--;\n+ continue;\n+ }\n_meanFn.execute2(_meanList[j], UtilFunctions.objectToDouble(\n- in.getSchema()[colID-1], in.get(i, colID-1)), off+i+1);\n+ in.getSchema()[colID-1], key), off+i+1);\n+ }\n_replacementList[j] = String.valueOf(_meanList[j]._sum);\n_countList[j] += in.getNumRows();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/TestUtils.java", "new_path": "src/test/java/org/apache/sysds/test/TestUtils.java", "diff": "@@ -3056,4 +3056,11 @@ public class TestUtils\nreturn y;\n}\n+\n+ public static boolean containsNan(double[][] data, int col) {\n+ for (double[] datum : data)\n+ if (Double.isNaN(datum[col]))\n+ return true;\n+ return false;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/transform/TransformFrameEncodeApplyTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/transform/TransformFrameEncodeApplyTest.java", "diff": "@@ -31,8 +31,7 @@ import org.apache.sysds.test.TestConfiguration;\nimport org.apache.sysds.test.TestUtils;\nimport org.apache.sysds.utils.Statistics;\n-public class TransformFrameEncodeApplyTest extends AutomatedTestBase\n-{\n+public class TransformFrameEncodeApplyTest extends AutomatedTestBase {\nprivate final static String TEST_NAME1 = \"TransformFrameEncodeApply\";\nprivate final static String TEST_DIR = \"functions/transform/\";\nprivate final static String TEST_CLASS_DIR = TEST_DIR + TransformFrameEncodeApplyTest.class.getSimpleName() + \"/\";\n@@ -357,8 +356,7 @@ public class TransformFrameEncodeApplyTest extends AutomatedTestBase\nrunTransformTest(ExecMode.HYBRID, \"csv\", TransformType.HASH_RECODE, false);\n}\n- private void runTransformTest( ExecMode rt, String ofmt, TransformType type, boolean colnames )\n- {\n+ private void runTransformTest( ExecMode rt, String ofmt, TransformType type, boolean colnames ) {\nboolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\nif( rtplatform == ExecMode.SPARK || rtplatform == ExecMode.HYBRID)\nDMLScript.USE_LOCAL_SPARK_CONFIG = true;\n@@ -431,6 +429,10 @@ public class TransformFrameEncodeApplyTest extends AutomatedTestBase\n1:0, R1[i][10+j], 1e-8);\n}\n}\n+ } else if (type == TransformType.IMPUTE){\n+ // Column 8 had GLOBAL_MEAN applied\n+ Assert.assertFalse(TestUtils.containsNan(R1, 8));\n+ Assert.assertFalse(TestUtils.containsNan(R2, 8));\n}\n}\ncatch(Exception ex) {\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix null check in EncoderMVImpute for Global_Mean; Also: * Adapted test so NaN is checked * removed unnecessary import * adapted count for mean calculation Closes #1190
49,720
04.03.2021 15:22:11
-3,600
43ac8787b5693943c61b9afb116e37748df3def2
[MINOR] Removing print statement from commit
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/transform/TokenizeTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/transform/TokenizeTest.java", "diff": "package org.apache.sysds.test.functions.transform;\nimport org.apache.sysds.api.DMLScript;\n-import org.apache.sysds.runtime.io.*;\n-import org.junit.Test;\nimport org.apache.sysds.common.Types.ExecMode;\n-import org.apache.sysds.runtime.matrix.data.FrameBlock;\n-import org.apache.sysds.runtime.util.DataConverter;\nimport org.apache.sysds.test.AutomatedTestBase;\nimport org.apache.sysds.test.TestConfiguration;\nimport org.apache.sysds.test.TestUtils;\n+import org.junit.Test;\n-public class TokenizeTest extends AutomatedTestBase\n-{\n+public class TokenizeTest extends AutomatedTestBase {\nprivate static final String TEST_DIR = \"functions/transform/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + TokenizeTest.class.getSimpleName() + \"/\";\n@@ -94,11 +90,10 @@ public class TokenizeTest extends AutomatedTestBase\nrunTokenizeTest(ExecMode.SINGLE_NODE, TEST_NGRAM_POS_LONG,false);\n}\n- // Long format on spark execution fails with: Number of non-zeros mismatch on merge disjoint\n-// @Test\n-// public void testTokenizeSparkNgramPosLong() {\n-// runTokenizeTest(ExecMode.SPARK, TEST_NGRAM_POS_LONG, false);\n-// }\n+ @Test\n+ public void testTokenizeSparkNgramPosLong() {\n+ runTokenizeTest(ExecMode.SPARK, TEST_NGRAM_POS_LONG, false);\n+ }\n@Test\npublic void testTokenizeHybridNgramPosLong() {\n@@ -110,11 +105,10 @@ public class TokenizeTest extends AutomatedTestBase\nrunTokenizeTest(ExecMode.SINGLE_NODE, TEST_NGRAM_POS_LONG, true);\n}\n- // Long format on spark execution fails with: Number of non-zeros mismatch on merge disjoint\n-// @Test\n-// public void testTokenizeParReadSparkNgramPosLong() {\n-// runTokenizeTest(ExecMode.SPARK, TEST_NGRAM_POS_LONG, true);\n-// }\n+ @Test\n+ public void testTokenizeParReadSparkNgramPosLong() {\n+ runTokenizeTest(ExecMode.SPARK, TEST_NGRAM_POS_LONG, true);\n+ }\n@Test\npublic void testTokenizeParReadHybridNgramPosLong() {\n@@ -201,13 +195,13 @@ public class TokenizeTest extends AutomatedTestBase\nHOME + \"input/\" + DATASET, HOME + test_name + \".json\", output(\"R\") };\nrunTest(true, false, null, -1);\n-\n+// TODO add assertion tests\n//read input/output and compare\n- FrameReader reader2 = parRead ?\n- new FrameReaderTextCSVParallel( new FileFormatPropertiesCSV() ) :\n- new FrameReaderTextCSV( new FileFormatPropertiesCSV() );\n- FrameBlock fb2 = reader2.readFrameFromHDFS(output(\"R\"), -1L, -1L);\n- System.out.println(DataConverter.toString(fb2));\n+// FrameReader reader2 = parRead ?\n+// new FrameReaderTextCSVParallel( new FileFormatPropertiesCSV() ) :\n+// new FrameReaderTextCSV( new FileFormatPropertiesCSV() );\n+// FrameBlock fb2 = reader2.readFrameFromHDFS(output(\"R\"), -1L, -1L);\n+// System.out.println(DataConverter.toString(fb2));\n}\ncatch(Exception ex) {\nthrow new RuntimeException(ex);\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Removing print statement from commit 8ef0d5a
49,693
08.03.2021 12:09:36
-3,600
f13bf1bbd51d4a17202450c272e27798bf064ba4
[MINOR] Fix unused imports introduced in codegen
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/codegen/SpoofCompiler.java", "new_path": "src/main/java/org/apache/sysds/hops/codegen/SpoofCompiler.java", "diff": "package org.apache.sysds.hops.codegen;\n-import java.io.File;\n-import java.io.IOException;\n-import java.util.*;\n-import java.util.Map.Entry;\n-import java.util.jar.JarEntry;\n-import java.util.jar.JarFile;\n-\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.apache.commons.lang3.SystemUtils;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.sysds.api.DMLScript;\n+import org.apache.sysds.common.Types.DataType;\nimport org.apache.sysds.common.Types.ExecMode;\nimport org.apache.sysds.common.Types.OpOp1;\nimport org.apache.sysds.conf.ConfigurationManager;\n@@ -46,8 +40,8 @@ import org.apache.sysds.hops.codegen.cplan.CNodeMultiAgg;\nimport org.apache.sysds.hops.codegen.cplan.CNodeOuterProduct;\nimport org.apache.sysds.hops.codegen.cplan.CNodeRow;\nimport org.apache.sysds.hops.codegen.cplan.CNodeTernary;\n-import org.apache.sysds.hops.codegen.cplan.CNodeTpl;\nimport org.apache.sysds.hops.codegen.cplan.CNodeTernary.TernaryType;\n+import org.apache.sysds.hops.codegen.cplan.CNodeTpl;\nimport org.apache.sysds.hops.codegen.opt.PlanSelection;\nimport org.apache.sysds.hops.codegen.opt.PlanSelectionFuseAll;\nimport org.apache.sysds.hops.codegen.opt.PlanSelectionFuseCostBased;\n@@ -55,13 +49,13 @@ import org.apache.sysds.hops.codegen.opt.PlanSelectionFuseCostBasedV2;\nimport org.apache.sysds.hops.codegen.opt.PlanSelectionFuseNoRedundancy;\nimport org.apache.sysds.hops.codegen.template.CPlanCSERewriter;\nimport org.apache.sysds.hops.codegen.template.CPlanMemoTable;\n-import org.apache.sysds.hops.codegen.template.CPlanOpRewriter;\n-import org.apache.sysds.hops.codegen.template.TemplateBase;\n-import org.apache.sysds.hops.codegen.template.TemplateUtils;\nimport org.apache.sysds.hops.codegen.template.CPlanMemoTable.MemoTableEntry;\nimport org.apache.sysds.hops.codegen.template.CPlanMemoTable.MemoTableEntrySet;\n+import org.apache.sysds.hops.codegen.template.CPlanOpRewriter;\n+import org.apache.sysds.hops.codegen.template.TemplateBase;\nimport org.apache.sysds.hops.codegen.template.TemplateBase.CloseType;\nimport org.apache.sysds.hops.codegen.template.TemplateBase.TemplateType;\n+import org.apache.sysds.hops.codegen.template.TemplateUtils;\nimport org.apache.sysds.hops.recompile.RecompileStatus;\nimport org.apache.sysds.hops.recompile.Recompiler;\nimport org.apache.sysds.hops.rewrite.HopRewriteUtils;\n@@ -80,10 +74,8 @@ import org.apache.sysds.parser.IfStatementBlock;\nimport org.apache.sysds.parser.StatementBlock;\nimport org.apache.sysds.parser.WhileStatement;\nimport org.apache.sysds.parser.WhileStatementBlock;\n-import org.apache.sysds.common.Types.DataType;\nimport org.apache.sysds.runtime.DMLRuntimeException;\nimport org.apache.sysds.runtime.codegen.CodegenUtils;\n-import org.apache.sysds.runtime.codegen.SpoofCUDAOperator;\nimport org.apache.sysds.runtime.codegen.SpoofCellwise.CellType;\nimport org.apache.sysds.runtime.codegen.SpoofRowwise.RowType;\nimport org.apache.sysds.runtime.controlprogram.BasicProgramBlock;\n@@ -102,6 +94,20 @@ import org.apache.sysds.utils.Explain;\nimport org.apache.sysds.utils.NativeHelper;\nimport org.apache.sysds.utils.Statistics;\n+import java.io.File;\n+import java.io.IOException;\n+import java.util.ArrayList;\n+import java.util.Arrays;\n+import java.util.Collections;\n+import java.util.Enumeration;\n+import java.util.HashMap;\n+import java.util.HashSet;\n+import java.util.Iterator;\n+import java.util.LinkedHashMap;\n+import java.util.Map.Entry;\n+import java.util.jar.JarEntry;\n+import java.util.jar.JarFile;\n+\npublic class SpoofCompiler {\nprivate static final Log LOG = LogFactory.getLog(SpoofCompiler.class.getName());\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNode.java", "new_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNode.java", "diff": "package org.apache.sysds.hops.codegen.cplan;\n-import java.util.ArrayList;\n-\n-import org.apache.sysds.hops.codegen.SpoofCompiler;\n-import org.apache.sysds.hops.codegen.template.TemplateUtils;\nimport org.apache.sysds.common.Types.DataType;\n+import org.apache.sysds.hops.codegen.SpoofCompiler.GeneratorAPI;\n+import org.apache.sysds.hops.codegen.template.TemplateUtils;\nimport org.apache.sysds.runtime.controlprogram.parfor.util.IDSequence;\nimport org.apache.sysds.runtime.util.UtilFunctions;\n-import org.apache.sysds.hops.codegen.SpoofCompiler.GeneratorAPI;\n+\n+import java.util.ArrayList;\npublic abstract class CNode\n{\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNodeData.java", "new_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNodeData.java", "diff": "package org.apache.sysds.hops.codegen.cplan;\n-import org.apache.commons.lang.StringUtils;\n-import org.apache.sysds.hops.Hop;\nimport org.apache.sysds.common.Types.DataType;\n+import org.apache.sysds.hops.Hop;\nimport org.apache.sysds.hops.codegen.SpoofCompiler;\n+import org.apache.sysds.hops.codegen.SpoofCompiler.GeneratorAPI;\nimport org.apache.sysds.runtime.codegen.CodegenUtils;\nimport org.apache.sysds.runtime.util.UtilFunctions;\n-import org.apache.sysds.hops.codegen.SpoofCompiler.GeneratorAPI;\n+\nimport static org.apache.sysds.runtime.matrix.data.LibMatrixNative.isSinglePrecision;\npublic class CNodeData extends CNode\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNodeRow.java", "new_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNodeRow.java", "diff": "package org.apache.sysds.hops.codegen.cplan;\n-import java.util.ArrayList;\n-import java.util.Arrays;\n-import java.util.regex.Matcher;\n-import java.util.stream.Collectors;\n-\nimport org.apache.sysds.hops.codegen.SpoofCompiler;\n+import org.apache.sysds.hops.codegen.SpoofCompiler.GeneratorAPI;\nimport org.apache.sysds.hops.codegen.SpoofFusedOp.SpoofOutputDimsType;\nimport org.apache.sysds.hops.codegen.cplan.CNodeBinary.BinType;\nimport org.apache.sysds.hops.codegen.template.TemplateUtils;\nimport org.apache.sysds.runtime.codegen.SpoofRowwise.RowType;\nimport org.apache.sysds.runtime.util.UtilFunctions;\n-import org.apache.sysds.hops.codegen.SpoofCompiler.GeneratorAPI;\n-import static org.apache.sysds.runtime.matrix.data.LibMatrixNative.isSinglePrecision;\n+import java.util.ArrayList;\npublic class CNodeRow extends CNodeTpl\n{\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/codegen/CodegenUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/codegen/CodegenUtils.java", "diff": "package org.apache.sysds.runtime.codegen;\n-import java.io.File;\n-import java.io.IOException;\n-import java.io.InputStream;\n-import java.net.URL;\n-import java.net.URLClassLoader;\n-import java.util.Arrays;\n-import java.util.Iterator;\n-import java.util.List;\n-import java.util.Map.Entry;\n-import java.util.Scanner;\n-import java.util.concurrent.ConcurrentHashMap;\n-\n-import javax.tools.Diagnostic;\n-import javax.tools.Diagnostic.Kind;\n-import javax.tools.DiagnosticCollector;\n-import javax.tools.JavaCompiler;\n-import javax.tools.JavaCompiler.CompilationTask;\n-import javax.tools.JavaFileObject;\n-import javax.tools.StandardJavaFileManager;\n-import javax.tools.ToolProvider;\n-\nimport org.apache.commons.io.IOUtils;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n-import org.apache.sysds.runtime.matrix.data.Pair;\n-import org.codehaus.janino.SimpleCompiler;\nimport org.apache.sysds.api.DMLScript;\nimport org.apache.sysds.hops.codegen.SpoofCompiler;\nimport org.apache.sysds.hops.codegen.SpoofCompiler.CompilerType;\n@@ -55,6 +32,27 @@ import org.apache.sysds.runtime.io.IOUtilFunctions;\nimport org.apache.sysds.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysds.runtime.util.LocalFileUtils;\nimport org.apache.sysds.utils.Statistics;\n+import org.codehaus.janino.SimpleCompiler;\n+\n+import javax.tools.Diagnostic;\n+import javax.tools.Diagnostic.Kind;\n+import javax.tools.DiagnosticCollector;\n+import javax.tools.JavaCompiler;\n+import javax.tools.JavaCompiler.CompilationTask;\n+import javax.tools.JavaFileObject;\n+import javax.tools.StandardJavaFileManager;\n+import javax.tools.ToolProvider;\n+import java.io.File;\n+import java.io.IOException;\n+import java.io.InputStream;\n+import java.net.URL;\n+import java.net.URLClassLoader;\n+import java.util.Arrays;\n+import java.util.Iterator;\n+import java.util.List;\n+import java.util.Map.Entry;\n+import java.util.Scanner;\n+import java.util.concurrent.ConcurrentHashMap;\npublic class CodegenUtils\n{\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/codegen/SpoofCUDAOperator.java", "new_path": "src/main/java/org/apache/sysds/runtime/codegen/SpoofCUDAOperator.java", "diff": "package org.apache.sysds.runtime.codegen;\n-import java.util.ArrayList;\n-\nimport jcuda.Pointer;\nimport org.apache.sysds.hops.codegen.SpoofCompiler;\nimport org.apache.sysds.runtime.controlprogram.caching.MatrixObject;\n@@ -28,7 +26,8 @@ import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.apache.sysds.runtime.instructions.cp.ScalarObject;\nimport org.apache.sysds.runtime.instructions.gpu.context.GPUObject;\nimport org.apache.sysds.runtime.matrix.data.LibMatrixCUDA;\n-import org.json4s.ParserUtil;\n+\n+import java.util.ArrayList;\nimport static org.apache.sysds.runtime.matrix.data.LibMatrixCUDA.sizeOfDataType;\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix unused imports introduced in codegen
49,706
09.03.2021 10:38:55
-3,600
bc9880cc89e7424055303c4cbd4c70a65d3df0d0
[MINOR] l2svm predict builtin
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/l2svmPredict.dml", "diff": "+#-------------------------------------------------------------\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+\n+#\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Double --- matrix X of feature vectors to classify\n+# W Double --- matrix of the trained variables\n+# verbose Boolean FALSE Set to true if one wants print statements.\n+# ---------------------------------------------------------------------------------------------\n+# OUTPUT:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# Y^ Double --- Classification Labels Raw, meaning not modified to clean\n+# Labeles of 1's and -1's\n+# Y Double --- Classification Labels Maxed to ones and zeros.\n+\n+\n+m_l2svmPredict = function(Matrix[Double] X, Matrix[Double] W, Boolean verbose = FALSE)\n+ return(Matrix[Double] YRaw, Matrix[Double] Y)\n+{\n+ if(ncol(X) != nrow(W)){\n+ if(ncol(X) + 1 != nrow(W)){\n+ stop(\"l2svm Predict: Invalid shape of W [\"+ncol(W)+\",\"+nrow(W)+\"] or X [\"+ncol(X)+\",\"+nrow(X)+\"]\")\n+ }\n+ YRaw = X %*% W[1:ncol(X),] + W[ncol(X)+1,]\n+ Y = rowIndexMax(YRaw)\n+ }\n+ else{\n+ YRaw = X %*% W\n+ Y = rowIndexMax(YRaw)\n+ }\n+}\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] l2svm predict builtin
49,706
09.03.2021 16:26:39
-3,600
de6574a943eb1fa513f655901f6cd48674676705
[MINOR] Repeat test argument in pom
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<jcuda.version>10.2.0</jcuda.version>\n<!-->Testing settings<!-->\n<maven.test.skip>true</maven.test.skip>\n+ <rerun.failing.tests.count>2</rerun.failing.tests.count>\n<jacoco.skip>true</jacoco.skip>\n<automatedtestbase.outputbuffering>false</automatedtestbase.outputbuffering>\n<argLine>-Xms4g -Xmx4g -Xmn400m</argLine>\n<reuseForks>false</reuseForks>\n<reportFormat>brief</reportFormat>\n<trimStackTrace>true</trimStackTrace>\n- <rerunFailingTestsCount>2</rerunFailingTestsCount>\n+ <rerunFailingTestsCount>${rerun.failing.tests.count}</rerunFailingTestsCount>\n</configuration>\n</plugin>\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Repeat test argument in pom
49,706
10.03.2021 12:30:22
-3,600
a3693f54de1c791947b3e8f56555f3b0a36056d7
[MINOR] CLA Unary contains NaN
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/CompressedMatrixBlock.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/CompressedMatrixBlock.java", "diff": "@@ -854,11 +854,30 @@ public class CompressedMatrixBlock extends MatrixBlock {\n@Override\npublic MatrixBlock unaryOperations(UnaryOperator op, MatrixValue result) {\n+\n+ // early abort for comparisons w/ special values\n+ if(Builtin.isBuiltinCode(op.fn, BuiltinCode.ISNAN, BuiltinCode.ISNA) && !containsValue(op.getPattern()))\n+ return new MatrixBlock(getNumRows(), getNumColumns(), 0); // avoid unnecessary allocation\n+\nprintDecompressWarning(\"unaryOperations \" + op.fn.toString());\nMatrixBlock tmp = getUncompressed();\nreturn tmp.unaryOperations(op, result);\n}\n+ @Override\n+ public boolean containsValue(double pattern) {\n+ if(isOverlapping()) {\n+ throw new NotImplementedException(\"Not implemented contains value for overlapping matrix\");\n+ }\n+ else {\n+ for(AColGroup g : _colGroups) {\n+ if(g.containsValue(pattern))\n+ return true;\n+ }\n+ return false;\n+ }\n+ }\n+\n@Override\npublic double max() {\nAggregateUnaryOperator op = InstructionUtils.parseBasicAggregateUnaryOperator(\"uamax\", -1);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/AColGroup.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/AColGroup.java", "diff": "@@ -644,6 +644,8 @@ public abstract class AColGroup implements Serializable {\npublic abstract AColGroup copy();\n+ public abstract boolean containsValue(double pattern);\n+\n@Override\npublic String toString() {\nStringBuilder sb = new StringBuilder();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ADictionary.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ADictionary.java", "diff": "@@ -248,4 +248,6 @@ public abstract class ADictionary {\n* @return The re expanded Dictionary.\n*/\npublic abstract ADictionary reExpandColumns(int max);\n+\n+ public abstract boolean containsValue(double pattern);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupUncompressed.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupUncompressed.java", "diff": "@@ -532,11 +532,15 @@ public class ColGroupUncompressed extends AColGroup {\n@Override\npublic void leftMultBySelfDiagonalColGroup(double[] result, int numColumns) {\nthrow new NotImplementedException(\"Not implemented slice columns\");\n-\n}\n@Override\npublic AColGroup copy() {\nthrow new NotImplementedException(\"Not implemented copy of uncompressed colGroup yet.\");\n}\n+\n+ @Override\n+ public boolean containsValue(double pattern){\n+ return _data.containsValue(pattern);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupValue.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupValue.java", "diff": "@@ -1026,4 +1026,8 @@ public abstract class ColGroupValue extends AColGroup implements Cloneable {\n}\n}\n+ @Override\n+ public boolean containsValue(double pattern){\n+ return _dict.containsValue(pattern);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/Dictionary.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/Dictionary.java", "diff": "@@ -220,7 +220,7 @@ public class Dictionary extends ADictionary {\n// pre-aggregate value tuple\nfinal int numVals = getNumberOfValues(nrColumns);\n- double[] ret = ColGroupValue.allocDVector(numVals, false);\n+ double[] ret = new double[numVals];\nfor(int k = 0; k < numVals; k++) {\nret[k] = sumRow(k, square, nrColumns);\n}\n@@ -365,4 +365,26 @@ public class Dictionary extends ADictionary {\nreturn new Dictionary(newDictValues);\n}\n+\n+ @Override\n+ public boolean containsValue(double pattern) {\n+\n+ if(_values == null)\n+ return false;\n+\n+ boolean NaNpattern = Double.isNaN(pattern);\n+\n+ if(NaNpattern) {\n+ for(double v : _values)\n+ if(Double.isNaN(v))\n+ return true;\n+ }\n+ else {\n+ for(double v : _values)\n+ if(v == pattern)\n+ return true;\n+ }\n+\n+ return false;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/QDictionary.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/QDictionary.java", "diff": "@@ -445,4 +445,11 @@ public class QDictionary extends ADictionary {\nreturn new QDictionary(newDictValues, 1.0);\n}\n+\n+ @Override\n+ public boolean containsValue(double pattern){\n+ if(Double.isNaN(pattern) || Double.isInfinite(pattern))\n+ return false;\n+ throw new NotImplementedException(\"Not contains value on Q Dictionary\");\n+ }\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/component/compress/dictionary/DictionaryTest.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.apache.sysds.test.component.compress.dictionary;\n+\n+import static org.junit.Assert.assertTrue;\n+\n+import org.apache.sysds.runtime.compress.colgroup.Dictionary;\n+import org.junit.Test;\n+\n+public class DictionaryTest {\n+\n+ @Test\n+ public void testContainsValue() {\n+ Dictionary d = new Dictionary(new double[] {1, 2, 3});\n+ assertTrue(d.containsValue(1));\n+ assertTrue(!d.containsValue(-1));\n+ }\n+\n+ @Test\n+ public void testContainsValue_nan() {\n+ Dictionary d = new Dictionary(new double[] {Double.NaN, 2, 3});\n+ assertTrue(d.containsValue(Double.NaN));\n+ }\n+\n+ @Test\n+ public void testContainsValue_nan_not() {\n+ Dictionary d = new Dictionary(new double[] {1, 2, 3});\n+ assertTrue(!d.containsValue(Double.NaN));\n+ }\n+}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] CLA Unary contains NaN
49,752
11.03.2021 14:19:51
-3,600
c6c460d0a5000b14c698ff8ef9e013a6d78d162c
Builtin Gaussian Classifier - TODO: replace the looped implementation of covariance matrix into a vectorized builtin DIA project WS2020/21 Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/gaussianClassifier.dml", "diff": "+#-------------------------------------------------------------\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+# Computes the parameters needed for Gaussian Classification.\n+# Thus it computes the following per class: the prior probability,\n+# the inverse covariance matrix, the mean per feature and the determinant\n+# of the covariance matrix. Furthermore (if not explicitely defined), it\n+# adds some small smoothing value along the variances, to prevent\n+# numerical errors / instabilities.\n+#\n+#\n+# INPUT PARAMETERS:\n+# -------------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# -------------------------------------------------------------------------------------------------\n+# D Matrix[Double] --- Input matrix (training set)\n+# C Matrix[Double] --- Target vector\n+# varSmoothing Double 1e-9 Smoothing factor for variances\n+# verbose Boolean TRUE Print accuracy of the training set\n+# ---------------------------------------------------------------------------------------------\n+# OUTPUT:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# classPriors Matrix[Double] --- Vector storing the class prior probabilities\n+# classMeans Matrix[Double] --- Matrix storing the means of the classes\n+# classInvCovariances List[Unknown] --- List of inverse covariance matrices\n+# determinants Matrix[Double] --- Vector storing the determinants of the classes\n+# ---------------------------------------------------------------------------------------------\n+#\n+\n+\n+m_gaussianClassifier = function(Matrix[Double] D, Matrix[Double] C, Double varSmoothing=1e-9, Boolean verbose = TRUE)\n+ return (Matrix[Double] classPriors, Matrix[Double] classMeans,\n+ List[Unknown] classInvCovariances, Matrix[Double] determinants)\n+{\n+ #Retrieve number of samples, classes and features\n+ nSamples = nrow(D)\n+ nClasses = max(C)\n+ nFeats = ncol(D)\n+\n+ #Compute means, variances and priors\n+ classCounts = aggregate(target=C, groups=C, fn=\"count\", ngroups=as.integer(nClasses));\n+ classMeans = aggregate(target=D, groups=C, fn=\"mean\", ngroups=as.integer(nClasses));\n+ classVars = aggregate(target=D, groups=C, fn=\"variance\", ngroups=as.integer(nClasses));\n+ classPriors = classCounts / nSamples\n+\n+ smoothedVar = diag(matrix(1.0, rows=nFeats, cols=1)) * max(classVars) * varSmoothing\n+\n+ classInvCovariances = list()\n+ determinants = matrix(0, rows=nClasses, cols=1)\n+\n+ #Compute determinants and inverseCovariances\n+ for (class in 1:nClasses)\n+ {\n+ covMatrix = matrix(0, rows=nFeats, cols=nFeats)\n+ classMatrix = removeEmpty(target=D, margin=\"rows\", select=(C==class))\n+ # TODO replace with implementation of new built-in for var-cov matrix\n+ # possible vectorized implementation but results are varying in some digits\n+ # difference = classMatrix - classMeans[class,]\n+ # cov_S = 1/nrow(classMatrix) * (t(difference) %*% difference)\n+\n+ for (i in 1:nFeats)\n+ {\n+ for (j in 1:nFeats)\n+ {\n+ if (j == i)\n+ covMatrix[i,j] = classVars[class, j]\n+ else if (j < i)\n+ covMatrix[i,j] = covMatrix[j,i]\n+ else\n+ covMatrix[i,j] = cov(classMatrix[,i], classMatrix[,j])\n+ }\n+ }\n+\n+ #Apply smoothing of the variances, to avoid numerical errors\n+ covMatrix = covMatrix + smoothedVar\n+\n+ #Compute inverse\n+ [eVals, eVecs] = eigen(covMatrix)\n+ lam = diag(eVals^(-1))\n+ invCovMatrix = eVecs %*% lam %*% t(eVecs)\n+\n+ #Compute determinant\n+ det = prod(eVals)\n+\n+ determinants[class, 1] = det\n+ classInvCovariances = append(classInvCovariances, invCovMatrix)\n+ }\n+\n+ #Compute accuracy on the training set\n+ if (verbose)\n+ {\n+ results = matrix(0, rows=nSamples, cols=nClasses)\n+ parfor (class in 1:nClasses)\n+ {\n+ for (i in 1:nSamples)\n+ {\n+ intermediate = 0\n+ meanDiff = (D[i,] - classMeans[class,])\n+ intermediate = -1/2 * log((2*pi)^nFeats * determinants[class,])\n+ intermediate = intermediate - 1/2 * (meanDiff %*% as.matrix(classInvCovariances[class]) %*% t(meanDiff))\n+ intermediate = log(classPriors[class,]) + intermediate\n+ results[i, class] = intermediate\n+ }\n+ }\n+ acc = sum(rowIndexMax(results) == C) / nSamples * 100\n+ print(\"Training Accuracy (%): \" + acc)\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -118,6 +118,7 @@ public enum Builtins {\nEVAL(\"eval\", false),\nFLOOR(\"floor\", false),\nFRAME_SORT(\"frameSort\", true),\n+ GAUSSIAN_CLASSIFIER(\"gaussianClassifier\", true),\nGET_PERMUTATIONS(\"getPermutations\", true),\nGLM(\"glm\", true),\nGMM(\"gmm\", true),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinGaussianClassifierTest.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.apache.sysds.test.functions.builtin;\n+\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Test;\n+\n+public class BuiltinGaussianClassifierTest extends AutomatedTestBase\n+{\n+ private final static String TEST_NAME = \"GaussianClassifier\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + BuiltinGaussianClassifierTest.class.getSimpleName() + \"/\";\n+\n+ private final static String DATASET = SCRIPT_DIR + \"functions/transform/input/iris/iris.csv\";\n+\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 testSmallDenseFiveClasses() {\n+ testGaussianClassifier(80, 10, 0.9, 5);\n+ }\n+\n+ @Test\n+ public void testSmallDenseTenClasses() {\n+ testGaussianClassifier(80, 30, 0.9, 10);\n+ }\n+\n+ @Test\n+ public void testBiggerDenseFiveClasses() {\n+ testGaussianClassifier(200, 50, 0.9, 5);\n+ }\n+\n+ @Test\n+ public void testBiggerDenseTenClasses() {\n+ testGaussianClassifier(200, 50, 0.9, 10);\n+ }\n+\n+ @Test\n+ public void testBiggerSparseFiveClasses() {\n+ testGaussianClassifier(200, 50, 0.3, 5);\n+ }\n+\n+ @Test\n+ public void testBiggerSparseTenClasses() {\n+ testGaussianClassifier(200, 50, 0.3, 10);\n+ }\n+\n+ @Test\n+ public void testSmallSparseFiveClasses() {\n+ testGaussianClassifier(80, 30, 0.3, 5);\n+ }\n+\n+ @Test\n+ public void testSmallSparseTenClasses() {\n+ testGaussianClassifier(80, 30, 0.3, 10);\n+ }\n+\n+ public void testGaussianClassifier(int rows, int cols, double sparsity, int classes)\n+ {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+\n+ double varSmoothing = 1e-9;\n+\n+ List<String> proArgs = new ArrayList<>();\n+ proArgs.add(\"-args\");\n+ proArgs.add(input(\"X\"));\n+ proArgs.add(input(\"Y\"));\n+ proArgs.add(String.valueOf(varSmoothing));\n+ proArgs.add(output(\"priors\"));\n+ proArgs.add(output(\"means\"));\n+ proArgs.add(output(\"determinants\"));\n+ proArgs.add(output(\"invcovs\"));\n+\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ rCmd = getRCmd(inputDir(), Double.toString(varSmoothing), expectedDir());\n+\n+ double[][] X = getRandomMatrix(rows, cols, 0, 100, sparsity, -1);\n+ double[][] Y = getRandomMatrix(rows, 1, 0, 1, 1, -1);\n+ for(int i=0; i<rows; i++){\n+ Y[i][0] = (int)(Y[i][0]*classes) + 1;\n+ Y[i][0] = (Y[i][0] > classes) ? classes : Y[i][0];\n+ }\n+\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+ writeInputMatrixWithMTD(\"Y\", Y, true);\n+\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ runRScript(true);\n+\n+ HashMap<CellIndex, Double> priorR = readRMatrixFromExpectedDir(\"priors\");\n+ HashMap<CellIndex, Double> priorSYSTEMDS= readDMLMatrixFromOutputDir(\"priors\");\n+ HashMap<CellIndex, Double> meansRtemp = readRMatrixFromExpectedDir(\"means\");\n+ HashMap<CellIndex, Double> meansSYSTEMDStemp = readDMLMatrixFromOutputDir(\"means\");\n+ HashMap<CellIndex, Double> determinantsRtemp = readRMatrixFromExpectedDir(\"determinants\");\n+ HashMap<CellIndex, Double> determinantsSYSTEMDStemp = readDMLMatrixFromOutputDir(\"determinants\");\n+ HashMap<CellIndex, Double> invcovsRtemp = readRMatrixFromExpectedDir(\"invcovs\");\n+ HashMap<CellIndex, Double> invcovsSYSTEMDStemp = readDMLMatrixFromOutputDir(\"invcovs\");\n+\n+ double[][] meansR = TestUtils.convertHashMapToDoubleArray(meansRtemp);\n+ double[][] meansSYSTEMDS = TestUtils.convertHashMapToDoubleArray(meansSYSTEMDStemp);\n+ double[][] determinantsR = TestUtils.convertHashMapToDoubleArray(determinantsRtemp);\n+ double[][] determinantsSYSTEMDS = TestUtils.convertHashMapToDoubleArray(determinantsSYSTEMDStemp);\n+ double[][] invcovsR = TestUtils.convertHashMapToDoubleArray(invcovsRtemp);\n+ double[][] invcovsSYSTEMDS = TestUtils.convertHashMapToDoubleArray(invcovsSYSTEMDStemp);\n+\n+ TestUtils.compareMatrices(priorR, priorSYSTEMDS, Math.pow(10, -5.0), \"priorR\", \"priorSYSTEMDS\");\n+ TestUtils.compareMatricesBitAvgDistance(meansR, meansSYSTEMDS, 5L,5L, this.toString());\n+ TestUtils.compareMatricesBitAvgDistance(determinantsR, determinantsSYSTEMDS, (long)2E+12,(long)2E+12, this.toString());\n+ TestUtils.compareMatricesBitAvgDistance(invcovsR, invcovsSYSTEMDS, (long)2E+20,(long)2E+20, this.toString());\n+ }\n+\n+ @Test\n+ public void testIrisPrediction()\n+ {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \"Prediction.dml\";\n+\n+ double varSmoothing = 1e-9;\n+\n+ List<String> proArgs = new ArrayList<>();\n+ proArgs.add(\"-args\");\n+ proArgs.add(DATASET);\n+ proArgs.add(String.valueOf(varSmoothing));\n+ proArgs.add(output(\"trueLabels\"));\n+ proArgs.add(output(\"predLabels\"));\n+\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ HashMap<CellIndex, Double> trueLabels = readDMLMatrixFromOutputDir(\"trueLabels\");\n+ HashMap<CellIndex, Double> predLabels = readDMLMatrixFromOutputDir(\"predLabels\");\n+\n+ TestUtils.compareMatrices(trueLabels, predLabels, 0, \"trueLabels\", \"predLabels\");\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/GaussianClassifier.R", "diff": "+#-------------------------------------------------------------\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+args <- commandArgs(TRUE)\n+library(\"Matrix\")\n+\n+D <- as.matrix(readMM(paste(args[1], \"X.mtx\", sep=\"\")))\n+c <- as.matrix(readMM(paste(args[1], \"Y.mtx\", sep=\"\")))\n+\n+nClasses <- as.integer(max(c))\n+varSmoothing <- as.double(args[2])\n+\n+nSamples <- nrow(D)\n+nFeatures <- ncol(D)\n+\n+classInvCovariances <- list()\n+\n+classMeans <- aggregate(D, by=list(c), FUN= mean)\n+classMeans <- classMeans[1:nFeatures+1]\n+\n+classVars <- aggregate(D, by=list(c), FUN=var)\n+classVars[is.na(classVars)] <- 0\n+smoothedVar <- varSmoothing * max(classVars) * diag(nFeatures)\n+\n+classCounts <- aggregate(c, by=list(c), FUN=length)\n+classCounts <- classCounts[2]\n+classPriors <- classCounts / nSamples\n+\n+determinants <- matrix(0, nrow=nClasses, ncol=1)\n+\n+for (i in 1:nClasses)\n+{\n+ classMatrix <- subset(D, c==i)\n+ covMatrix <- cov(x=classMatrix, use=\"all.obs\")\n+ covMatrix[is.na(covMatrix)] <- 0\n+ covMatrix <- covMatrix + smoothedVar\n+ #determinant <- det(covMatrix)\n+ #determinants[i] <- det(covMatrix)\n+\n+ ev <- eigen(covMatrix)\n+ vecs <- ev$vectors\n+ vals <- ev$values\n+ lam <- diag(vals^(-1))\n+ determinants[i] <- prod(vals)\n+\n+ invCovMatrix <- vecs %*% lam %*% t(vecs)\n+ invCovMatrix[is.na(invCovMatrix)] <- 0\n+ classInvCovariances[[i]] <- invCovMatrix\n+}\n+\n+\n+#Calc accuracy\n+results <- matrix(0, nrow=nSamples, ncol=nClasses)\n+for (class in 1:nClasses)\n+{\n+ for (i in 1:nSamples)\n+ {\n+ intermediate <- 0\n+ meanDiff <- (D[i,] - classMeans[class,])\n+ intermediate <- -1/2 * log((2*pi)^nFeatures * determinants[class,])\n+ intermediate <- intermediate - 1/2 * (as.matrix(meanDiff) %*% as.matrix(classInvCovariances[[class]])\n+ %*% t(as.matrix(meanDiff)))\n+ intermediate <- log(classPriors[class,]) + intermediate\n+ results[i, class] <- intermediate\n+ }\n+}\n+\n+pred <- max.col(results)\n+acc <- sum(pred == c) / nSamples * 100\n+print(paste(\"Training Accuracy (%): \", acc, sep=\"\"))\n+\n+classPriors <- data.matrix(classPriors)\n+classMeans <- data.matrix(classMeans)\n+\n+#Cbind the inverse covariance matrices, to make them comparable in the unit tests\n+stackedInvCovs <- classInvCovariances[[1]]\n+for (i in 2:nClasses)\n+{\n+ stackedInvCovs <- cbind(stackedInvCovs, classInvCovariances[[i]])\n+}\n+\n+writeMM(as(classPriors, \"CsparseMatrix\"), paste(args[3], \"priors\", sep=\"\"));\n+writeMM(as(classMeans, \"CsparseMatrix\"), paste(args[3], \"means\", sep=\"\"));\n+writeMM(as(determinants, \"CsparseMatrix\"), paste(args[3], \"determinants\", sep=\"\"));\n+writeMM(as(stackedInvCovs, \"CsparseMatrix\"), paste(args[3], \"invcovs\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/GaussianClassifier.dml", "diff": "+#-------------------------------------------------------------\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+y = read($2);\n+\n+[prior, means, covs, det] = gaussianClassifier(D=X, C=y, varSmoothing=$3);\n+\n+#Cbind the inverse covariance matrices, to make them comparable in the unit tests\n+invcovs = as.matrix(covs[1])\n+for (i in 2:max(y))\n+{\n+ invcovs = cbind(invcovs, as.matrix(covs[i]))\n+}\n+\n+write(prior, $4);\n+write(means, $5);\n+write(det, $6);\n+write(invcovs, $7);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/GaussianClassifierPrediction.dml", "diff": "+#-------------------------------------------------------------\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+O = read($1, data_type = \"frame\", format = \"csv\")\n+\n+#Create feature matrix to learn parameters (45 samples per class)\n+X = as.matrix(O[1:45, 2:ncol(O)-1]) #setosa\n+X = rbind(X, as.matrix(O[51:95, 2:ncol(O)-1])) #versicolor\n+X = rbind(X, as.matrix(O[101:145, 2:ncol(O)-1])) #virginica\n+\n+y = matrix (1, rows=45, cols=1)\n+y = rbind(y, matrix(2, rows=45, cols=1))\n+y = rbind(y, matrix(3, rows=45, cols=1))\n+\n+[prior, means, covs, det] = gaussianClassifier(D=X, C=y, varSmoothing=$2);\n+\n+#Create feature matrix for prediction (5 samples per class)\n+Xp = as.matrix(O[46:50, 2:ncol(O)-1]) #setosa\n+Xp = rbind(Xp, as.matrix(O[96:100, 2:ncol(O)-1])) #versicolor\n+Xp = rbind(Xp, as.matrix(O[146:150, 2:ncol(O)-1])) #virginica\n+\n+#Set the target labels\n+yp = matrix(1, rows=5, cols=1)\n+yp = rbind(yp, matrix(2, rows=5, cols=1))\n+yp = rbind(yp, matrix(3, rows=5, cols=1))\n+\n+#Compute the prediction with the learned parameters\n+nSamples = nrow(Xp)\n+nClasses = max(yp)\n+nFeats = ncol(Xp)\n+results = matrix(0, rows=nSamples, cols=nClasses)\n+\n+for (class in 1:nClasses)\n+{\n+ for (i in 1:nSamples)\n+ {\n+ intermediate = 0\n+ meanDiff = (Xp[i,] - means[class,])\n+ intermediate = -1/2 * log((2*pi)^nFeats * det[class,])\n+ intermediate = intermediate - 1/2 * (meanDiff %*% as.matrix(covs[class]) %*% t(meanDiff))\n+ intermediate = log(prior[class,]) + intermediate\n+ results[i, class] = intermediate\n+ }\n+}\n+\n+#Get the predicted labels from the result matrix\n+predicted = rowIndexMax(results)\n+\n+write(yp, $3);\n+write(predicted, $4);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2891] Builtin Gaussian Classifier - TODO: replace the looped implementation of covariance matrix into a vectorized builtin DIA project WS2020/21 Closes #1153.
49,689
11.03.2021 19:12:33
-3,600
444df94ed8e990322e2a3a7a6fc7e3a0545b46da
Lineage tracing GPU instructions This patch extends lineage tracing for GPU instructions. This is the initial version and only a few operations are supported at this moment. Furthermore, this patch adds a test which tunes hyper-parameters for LM in GPU, recomputes the result from lineage in CPU and finally matches the results.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/AggregateBinaryGPUInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/AggregateBinaryGPUInstruction.java", "diff": "*/\npackage org.apache.sysds.runtime.instructions.gpu;\n+import org.apache.commons.lang3.tuple.Pair;\nimport org.apache.sysds.runtime.DMLRuntimeException;\nimport org.apache.sysds.runtime.controlprogram.caching.MatrixObject;\nimport org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\n@@ -26,6 +27,9 @@ import org.apache.sysds.runtime.functionobjects.Plus;\nimport org.apache.sysds.runtime.functionobjects.SwapIndex;\nimport org.apache.sysds.runtime.instructions.InstructionUtils;\nimport org.apache.sysds.runtime.instructions.cp.CPOperand;\n+import org.apache.sysds.runtime.lineage.LineageItem;\n+import org.apache.sysds.runtime.lineage.LineageItemUtils;\n+import org.apache.sysds.runtime.lineage.LineageTraceable;\nimport org.apache.sysds.runtime.matrix.data.LibMatrixCUDA;\nimport org.apache.sysds.runtime.matrix.data.LibMatrixCuMatMult;\nimport org.apache.sysds.runtime.matrix.data.MatrixBlock;\n@@ -34,7 +38,7 @@ import org.apache.sysds.runtime.matrix.operators.Operator;\nimport org.apache.sysds.runtime.matrix.operators.ReorgOperator;\nimport org.apache.sysds.utils.GPUStatistics;\n-public class AggregateBinaryGPUInstruction extends GPUInstruction {\n+public class AggregateBinaryGPUInstruction extends GPUInstruction implements LineageTraceable {\nprivate CPOperand _input1 = null;\nprivate CPOperand _input2 = null;\nprivate CPOperand _output = null;\n@@ -97,4 +101,10 @@ public class AggregateBinaryGPUInstruction extends GPUInstruction {\nMatrixObject mo = ec.getMatrixObject(var);\nreturn LibMatrixCUDA.isInSparseFormat(ec.getGPUContext(0), mo);\n}\n+\n+ @Override\n+ public Pair<String, LineageItem> getLineageItem(ExecutionContext ec) {\n+ return Pair.of(_output.getName(), new LineageItem(getOpcode(),\n+ LineageItemUtils.getLineage(ec, _input1, _input2)));\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/ArithmeticBinaryGPUInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/ArithmeticBinaryGPUInstruction.java", "diff": "package org.apache.sysds.runtime.instructions.gpu;\n+import org.apache.commons.lang3.tuple.Pair;\nimport org.apache.sysds.common.Types.DataType;\nimport org.apache.sysds.runtime.DMLRuntimeException;\n+import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.apache.sysds.runtime.instructions.InstructionUtils;\nimport org.apache.sysds.runtime.instructions.cp.CPOperand;\n+import org.apache.sysds.runtime.lineage.LineageItem;\n+import org.apache.sysds.runtime.lineage.LineageItemUtils;\n+import org.apache.sysds.runtime.lineage.LineageTraceable;\nimport org.apache.sysds.runtime.matrix.operators.Operator;\n-public abstract class ArithmeticBinaryGPUInstruction extends GPUInstruction {\n+public abstract class ArithmeticBinaryGPUInstruction extends GPUInstruction implements LineageTraceable {\nprotected CPOperand _input1;\nprotected CPOperand _input2;\nprotected CPOperand _output;\n@@ -65,4 +70,10 @@ public abstract class ArithmeticBinaryGPUInstruction extends GPUInstruction {\nelse\nthrow new DMLRuntimeException(\"Unsupported GPU ArithmeticInstruction.\");\n}\n+\n+ @Override\n+ public Pair<String, LineageItem> getLineageItem(ExecutionContext ec) {\n+ return Pair.of(_output.getName(), new LineageItem(getOpcode(),\n+ LineageItemUtils.getLineage(ec, _input1, _input2)));\n+ }\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/BuiltinBinaryGPUInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/BuiltinBinaryGPUInstruction.java", "diff": "package org.apache.sysds.runtime.instructions.gpu;\n+import org.apache.commons.lang3.tuple.Pair;\nimport org.apache.sysds.common.Types.DataType;\nimport org.apache.sysds.common.Types.ValueType;\nimport org.apache.sysds.runtime.DMLRuntimeException;\n+import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.apache.sysds.runtime.functionobjects.Builtin;\nimport org.apache.sysds.runtime.functionobjects.ValueFunction;\nimport org.apache.sysds.runtime.instructions.InstructionUtils;\nimport org.apache.sysds.runtime.instructions.cp.CPOperand;\n+import org.apache.sysds.runtime.lineage.LineageItem;\n+import org.apache.sysds.runtime.lineage.LineageItemUtils;\n+import org.apache.sysds.runtime.lineage.LineageTraceable;\nimport org.apache.sysds.runtime.matrix.operators.BinaryOperator;\nimport org.apache.sysds.runtime.matrix.operators.Operator;\n-public abstract class BuiltinBinaryGPUInstruction extends GPUInstruction {\n+public abstract class BuiltinBinaryGPUInstruction extends GPUInstruction implements LineageTraceable {\n@SuppressWarnings(\"unused\")\nprivate int _arity;\n@@ -59,9 +64,10 @@ public abstract class BuiltinBinaryGPUInstruction extends GPUInstruction {\nout.split(parts[3]);\n// check for valid data type of output\n- if((in1.getDataType() == DataType.MATRIX || in2.getDataType() == DataType.MATRIX) && out.getDataType() != DataType.MATRIX)\n- throw new DMLRuntimeException(\"Element-wise matrix operations between variables \" + in1.getName() +\n- \" and \" + in2.getName() + \" must produce a matrix, which \" + out.getName() + \" is not\");\n+ if ((in1.getDataType() == DataType.MATRIX || in2.getDataType() == DataType.MATRIX) &&\n+ out.getDataType() != DataType.MATRIX)\n+ throw new DMLRuntimeException(\"Element-wise matrix operations between variables \" + in1.getName() + \" and \"\n+ + in2.getName() + \" must produce a matrix, which \" + out.getName() + \" is not\");\n// Determine appropriate Function Object based on opcode\nValueFunction func = Builtin.getBuiltinFnObject(opcode);\n@@ -78,9 +84,14 @@ public abstract class BuiltinBinaryGPUInstruction extends GPUInstruction {\nreturn new ScalarMatrixBuiltinGPUInstruction(new BinaryOperator(func), in1, in2, out, opcode, str, 2);\nelse\n- throw new DMLRuntimeException(\"GPU : Unsupported GPU builtin operations on a matrix and a scalar:\" + opcode);\n-\n+ throw new DMLRuntimeException(\n+ \"GPU : Unsupported GPU builtin operations on a matrix and a scalar:\" + opcode);\n+ }\n+ @Override\n+ public Pair<String, LineageItem> getLineageItem(ExecutionContext ec) {\n+ return Pair.of(output.getName(), new LineageItem(getOpcode(),\n+ LineageItemUtils.getLineage(ec, input1, input2)));\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/MatrixMatrixBuiltinGPUInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/MatrixMatrixBuiltinGPUInstruction.java", "diff": "@@ -47,7 +47,8 @@ public class MatrixMatrixBuiltinGPUInstruction extends BuiltinBinaryGPUInstructi\nec.setMetaData(output.getName(), mat1.getNumColumns(), 1);\nLibMatrixCUDA.solve(ec, ec.getGPUContext(0), getExtendedOpcode(), mat1, mat2, output.getName());\n- } else {\n+ }\n+ else {\nthrow new DMLRuntimeException(\"Unsupported GPU operator:\" + opcode);\n}\nec.releaseMatrixInputForGPUInstruction(input1.getName());\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/ReorgGPUInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/ReorgGPUInstruction.java", "diff": "package org.apache.sysds.runtime.instructions.gpu;\n+import org.apache.commons.lang3.tuple.Pair;\nimport org.apache.sysds.runtime.DMLRuntimeException;\nimport org.apache.sysds.runtime.controlprogram.caching.MatrixObject;\nimport org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\nimport org.apache.sysds.runtime.functionobjects.SwapIndex;\nimport org.apache.sysds.runtime.instructions.InstructionUtils;\nimport org.apache.sysds.runtime.instructions.cp.CPOperand;\n+import org.apache.sysds.runtime.lineage.LineageItem;\n+import org.apache.sysds.runtime.lineage.LineageItemUtils;\n+import org.apache.sysds.runtime.lineage.LineageTraceable;\nimport org.apache.sysds.runtime.matrix.data.LibMatrixCUDA;\nimport org.apache.sysds.runtime.matrix.operators.Operator;\nimport org.apache.sysds.runtime.matrix.operators.ReorgOperator;\nimport org.apache.sysds.utils.GPUStatistics;\n-public class ReorgGPUInstruction extends GPUInstruction {\n+public class ReorgGPUInstruction extends GPUInstruction implements LineageTraceable {\nprivate CPOperand _input;\nprivate CPOperand _output;\n@@ -80,4 +84,10 @@ public class ReorgGPUInstruction extends GPUInstruction {\nec.releaseMatrixInputForGPUInstruction(_input.getName());\nec.releaseMatrixOutputForGPUInstruction(_output.getName());\n}\n+\n+ @Override\n+ public Pair<String, LineageItem> getLineageItem(ExecutionContext ec) {\n+ return Pair.of(_output.getName(), new LineageItem(getOpcode(),\n+ LineageItemUtils.getLineage(ec, _input)));\n+ }\n}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageRecomputeUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageRecomputeUtils.java", "diff": "@@ -89,7 +89,21 @@ public class LineageRecomputeUtils {\nLineageItem root = LineageParser.parseLineageTrace(mainTrace);\nif (dedupPatches != null)\nLineageParser.parseLineageTraceDedup(dedupPatches);\n+\n+ // Disable GPU execution. TODO: Support GPU\n+ boolean GPUenabled = false;\n+ if (DMLScript.USE_ACCELERATOR) {\n+ GPUenabled = true;\n+ DMLScript.USE_ACCELERATOR = false;\n+ }\n+ // Reset statistics\n+ if (DMLScript.STATISTICS)\n+ Statistics.reset();\n+\nData ret = computeByLineage(root);\n+\n+ if (GPUenabled)\n+ DMLScript.USE_ACCELERATOR = true;\n// Cleanup the statics\nloopPatchMap.clear();\nreturn ret;\n@@ -115,9 +129,9 @@ public class LineageRecomputeUtils {\npartDagRoots.put(varname, out);\nconstructBasicBlock(partDagRoots, varname, prog);\n- // Reset cache due to cleaned data objects\n+ // Reset cache to avoid erroneous reuse\nLineageCache.resetCache();\n- //execute instructions and get result\n+ // Execute instructions and get result\nif (DEBUG) {\nDMLScript.STATISTICS = true;\nExplainCounts counts = Explain.countDistributedOperations(prog);\n@@ -125,10 +139,11 @@ public class LineageRecomputeUtils {\n}\nec.setProgram(prog);\nprog.execute(ec);\n- if (DEBUG) {\n+ if (DEBUG || DMLScript.STATISTICS) {\nStatistics.stopRunTimer();\nSystem.out.println(Statistics.display(DMLScript.STATISTICS_COUNT));\n}\n+\nreturn ec.getVariable(varname);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/TestUtils.java", "new_path": "src/test/java/org/apache/sysds/test/TestUtils.java", "diff": "@@ -78,6 +78,8 @@ import org.apache.sysds.runtime.util.DataConverter;\nimport org.apache.sysds.runtime.util.UtilFunctions;\nimport org.junit.Assert;\n+import jcuda.runtime.JCuda;\n+\n/**\n* <p>\n@@ -3063,4 +3065,10 @@ public class TestUtils\nreturn true;\nreturn false;\n}\n+\n+ public static int isGPUAvailable() {\n+ // returns cudaSuccess if at least one gpu is available\n+ final int[] deviceCount = new int[1];\n+ return JCuda.cudaGetDeviceCount(deviceCount);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinCsplineTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinCsplineTest.java", "diff": "* under the License.\n*/\n-package org.apache.sysds.test.applications;\n+package org.apache.sysds.test.functions.builtin;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/lineage/LineageTraceGPUTest.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.apache.sysds.test.functions.lineage;\n+\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+import org.apache.sysds.runtime.controlprogram.caching.MatrixObject;\n+import org.apache.sysds.runtime.instructions.cp.Data;\n+import org.apache.sysds.runtime.lineage.Lineage;\n+import org.apache.sysds.runtime.lineage.LineageRecomputeUtils;\n+import org.apache.sysds.runtime.matrix.data.MatrixBlock;\n+import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Test;\n+\n+import jcuda.runtime.cudaError;\n+\n+public class LineageTraceGPUTest extends AutomatedTestBase{\n+\n+ protected static final String TEST_DIR = \"functions/lineage/\";\n+ protected static final String TEST_NAME1 = \"LineageTraceGPU1\";\n+ protected String TEST_CLASS_DIR = TEST_DIR + LineageTraceGPUTest.class.getSimpleName() + \"/\";\n+\n+ protected static final int numRecords = 10;\n+ protected static final int numFeatures = 5;\n+\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 simpleHLM_gpu() { //hyper-parameter tuning over LM (simple)\n+ testLineageTraceExec(TEST_NAME1);\n+ }\n+\n+ private void testLineageTraceExec(String testname) {\n+ System.out.println(\"------------ BEGIN \" + testname + \"------------\");\n+\n+ int gpuStatus = TestUtils.isGPUAvailable();\n+ getAndLoadTestConfiguration(testname);\n+ List<String> proArgs = new ArrayList<>();\n+\n+ proArgs.add(\"-stats\");\n+ if (gpuStatus == cudaError.cudaSuccess)\n+ proArgs.add(\"-gpu\");\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+ //NOTE: the generated program is CP-only.\n+ Data ret = LineageRecomputeUtils.parseNComputeLineageTrace(Rtrace, null);\n+\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromOutputDir(\"R\");\n+ MatrixBlock tmp = ((MatrixObject)ret).acquireReadAndRelease();\n+ TestUtils.compareMatrices(dmlfile, tmp, 1e-6);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/lineage/LineageTraceGPU1.dml", "diff": "+#-------------------------------------------------------------\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+SimlinRegDS = function(Matrix[Double] X, Matrix[Double] y, Double lamda, Integer N)\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+no_lamda = 10;\n+\n+stp = (0.1 - 0.0001)/no_lamda;\n+lamda = 0.0001;\n+lim = 0.1;\n+\n+X = rand(rows=1000, cols=100, seed=42);\n+y = rand(rows=1000, cols=1, seed=42);\n+N = ncol(X);\n+R = matrix(0, rows=N, cols=no_lamda+2);\n+i = 1;\n+\n+while (lamda < lim)\n+{\n+ beta = SimlinRegDS(X, y, lamda, N);\n+ R[,i] = beta;\n+ lamda = lamda + stp;\n+ i = i + 1;\n+}\n+write(R, $1);\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2893] Lineage tracing GPU instructions This patch extends lineage tracing for GPU instructions. This is the initial version and only a few operations are supported at this moment. Furthermore, this patch adds a test which tunes hyper-parameters for LM in GPU, recomputes the result from lineage in CPU and finally matches the results.
49,705
11.03.2021 18:08:44
-3,600
4001ba6cf0a3615e0588dde63b6176f89eea2726
Builtin for Denial Constraints Validation DIA Project WS2020/21 Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/denialConstraints.dml", "diff": "+#-------------------------------------------------------------\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 function considers some constraints indicating statements that can NOT happen in the data (denial constraints).\n+#\n+#\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# dataFrame Frame --- frame which columns represent the variables of the data and the rows correspond to different tuples or instances.\n+# Recommended to have a column indexing the instances from 1 to N (N=number of instances).\n+# constraintsFrame Frame --- frame with fixed columns and each row representing one constraint.\n+# 1. idx: (double) index of the constraint, from 1 to M (number of constraints)\n+# 2. constraint.type: (string) The constraints can be of 3 different kinds:\n+# - variableCompare: for each instance, it will compare the values of two variables (with a relation <, > or =).\n+# - valueCompare: for each instance, it will compare a fixed value and a variable value (with a relation <, > or =).\n+# - instanceCompare: for every couple of instances, it will compare the relation between two variables,\n+# ie if the value of the variable 1 in instance 1 is lower/higher than the value of variable 1 in instance 2,\n+# then the value of of variable 2 in instance 2 can't be lower/higher than the value of variable 2 in instance 2.\n+# 3. group.by: (boolean) if TRUE only one group of data (defined by a variable option) will be considered for the constraint.\n+# 4. group.variable: (string, only if group.by TRUE) name of the variable (column in dataFrame) that will divide our data in groups.\n+# 5. group.option: (only if group.by TRUE) option of the group.variable that defines the group to consider.\n+# 6. variable1: (string) first variable to compare (name of column in dataFrame).\n+# 7. relation: (string) can be < , > or = in the case of variableCompare and valueCompare, and < >, < < , > < or > >\n+# in the case of instanceCompare\n+# 8. variable2: (string) second variable to compare (name of column in dataFrame) or fixed value for the case of valueCompare.\n+#\n+\n+# -----------------------\n+# EXAMPLE:\n+# dataFrame:\n+#\n+# rank discipline yrs.since.phd yrs.service sex salary\n+# 1 Prof B 19 18 Male 139750\n+# 2 Prof B 20 16 Male 173200\n+# 3 AsstProf B 3 3 Male 79750.56\n+# 4 Prof B 45 39 Male 115000\n+# 5 Prof B 40 40 Male 141500\n+# 6 AssocProf B 6 6 Male 97000\n+# 7 Prof B 30 23 Male 175000\n+# 8 Prof B 45 45 Male 147765\n+# 9 Prof B 21 20 Male 119250\n+# 10 Prof B 18 18 Female 129000\n+# 11 AssocProf B 12 8 Male 119800\n+# 12 AsstProf B 7 2 Male 79800\n+# 13 AsstProf B 1 1 Male 77700\n+#\n+# constraintsFrame:\n+#\n+# idx constraint.type group.by group.variable group.option variable1 relation variable2\n+# 1 variableCompare FALSE yrs.since.phd < yrs.service\n+# 2 instanceCompare TRUE rank Prof yrs.service >< salary\n+# 3 valueCompare FALSE salary = 78182\n+# 4 variableCompare TRUE discipline B yrs.service > yrs.since.phd\n+#\n+#\n+# Example: explanation of constraint 2 --> it can't happen that one professor of rank Prof has more years of service than other, but lower salary.\n+#\n+#----------------------------------\n+# OUTPUT PARAMETERS:\n+#----------------------------------\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# --------------------------------------------------------------------------------\n+# WrongInstances Matrix Double Matrix of 2 columns.\n+# - First column shows the indexes of dataFrame that are wrong.\n+# - Second column shows the index of the denial constraint that is fulfilled\n+# If there are no wrong instances to show (0 constrains fulfilled) --> WrongInstances=matrix(0,1,2)\n+#\n+\n+\n+s_denialConstraints = function(Frame[Unknown] dataFrame, Frame[Unknown] constraintsFrame)\n+return(Matrix[double] WrongInstances)\n+{\n+ print(\"DENIAL CONSTRAINTS\");\n+\n+\n+ N = nrow(dataFrame); # rows in data frame\n+ M = nrow(constraintsFrame); # number of constraints\n+\n+ WrongInstances = matrix(0,rows=N*M,cols=2)\n+ flag=0\n+ colName = dataFrame[1,]\n+\n+ for(iConstraint in 2:M) { # loop starts in 2 because 1 is the name of the columns, not a constraint\n+ var1 = as.scalar(constraintsFrame[iConstraint,6]) # variable 1 of the constraint\n+ isCol1 = map(colName, \"x->x.equals(\\\"\"+var1+\"\\\")\") # find the column of dataFrame corresponding to var1\n+ rel = as.scalar(constraintsFrame[iConstraint,7]) # relation of the constraint\n+ colIdx1=0\n+ for(iLog in 1:ncol(colName)){\n+ if(as.scalar(isCol1[1,iLog])==\"true\"){\n+ colIdx1=iLog # number (index) of the column of dataFrame corresponding to var1\n+ }\n+ }\n+ if (colIdx1==0){\n+ print('Variable 1 for constraint ' + toString(iConstraint-1) + \" not found in dataFrame\")\n+ }\n+\n+ # DEFINE IF THE CONSTRAINT IS RESTRICTED TO A GROUP OF DATA:\n+\n+ if(as.scalar(constraintsFrame[iConstraint,3])==\"TRUE\" & colIdx1!=0) {\n+ varToGroup = as.scalar(constraintsFrame[iConstraint,4]) # variable that will divide our data in groups\n+ isColToGroup = map(colName, \"x->x.equals(\\\"\"+varToGroup+\"\\\")\") # find the column of dataFrame corresponding to varToGroup\n+ for(iLog in 1:ncol(colName)){\n+ if(as.scalar(isColToGroup[1,iLog])==\"true\"){\n+ colIdxToGroup=iLog\n+ }\n+ }\n+ groupInstances = dataFrame[,colIdxToGroup]\n+ groupOption = as.scalar(constraintsFrame[iConstraint,5]) # option of the group.variable that defines the group to consider\n+ IsGroupInstance= map(groupInstances, \"x->x.equals(\\\"\"+groupOption+\"\\\")\") # find the instances with varToGroup = groupOption\n+ IsGroupInstanceM = matrix(0, nrow(IsGroupInstance), 1)\n+ for(h in 1:nrow(IsGroupInstance)){\n+ IsGroupInstanceM[h,1] = ifelse(as.scalar(IsGroupInstance[h,1]) == \"true\",TRUE,FALSE)\n+ }\n+ } else if (colIdx1!=0){\n+ IsGroupInstanceM = matrix(0, N, 1)\n+ IsGroupInstance = matrix(1, N, 1)\n+ for(h in 1:N){\n+ IsGroupInstanceM[h,1] = ifelse(as.scalar(IsGroupInstance[h,1]) == 1,TRUE,FALSE)\n+ }\n+ }\n+\n+\n+\n+ # CONSTRAINT TO COMPARE VARIABLES OF THE SAME INSTANCE:\n+\n+ if(as.scalar(constraintsFrame[iConstraint,2])==\"variableCompare\" & colIdx1!=0){\n+ var2 = as.scalar(constraintsFrame[iConstraint,8]) # variable 2 of the constraint\n+ isCol2 = 0\n+ isCol2 = map(colName, \"x->x.equals(\\\"\"+var2+\"\\\")\")\n+ for(iLog in 1:ncol(colName)){\n+ if(as.scalar(isCol2[1,iLog])==\"true\"){\n+ colIdx2=iLog\n+ }\n+ }\n+ if (colIdx2==0){\n+ print('Variable 2 for constraint ' + toString(iConstraint-1) + \" not found in dataFrame\")\n+ }\n+ if(rel==\"<\" & colIdx2!=0){\n+ for(iInstance in 2:N){ # loop starts in 2 because 1 is the name of the columns, not an instance\n+ value1 = as.scalar(dataFrame[iInstance,colIdx1]) # value 1 to compare in the constraint\n+ value2 = as.scalar(dataFrame[iInstance,colIdx2]) # value 2 to compare in the constraint\n+ if(as.integer(value1)<as.integer(value2) & as.scalar(IsGroupInstanceM[iInstance,1])){\n+ flag = flag+1\n+ WrongInstances[flag,1] = iInstance-1\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ } else if(rel==\">\" & colIdx2!=0){\n+ for(iInstance in 2:N){\n+ value1 = as.scalar(dataFrame[iInstance,colIdx1]) # value 1 to compare in the constraint\n+ value2 = as.scalar(dataFrame[iInstance,colIdx2]) # value 2 to compare in the constraint\n+ if(as.integer(value1)>as.integer(value2) & as.scalar(IsGroupInstanceM[iInstance,1])){\n+ flag = flag+1\n+ WrongInstances[flag,1] = iInstance-1\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ } else if(rel==\"=\" & colIdx2!=0){\n+ for(iInstance in 2:N){\n+ value1 = as.scalar(dataFrame[iInstance,colIdx1]) # value 1 to compare in the constraint\n+ value2 = as.scalar(dataFrame[iInstance,colIdx2]) # value 2 to compare in the constraint\n+ if(as.integer(value1)==as.integer(value2) & as.scalar(IsGroupInstanceM[iInstance,1])){\n+ flag = flag+1\n+ WrongInstances[flag,1] = iInstance-1\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ }\n+\n+\n+ # CONSTRAINT TO COMPARE A VALUE AND A VARIABLE FOR EACH iNSTANCE\n+\n+ } else if(as.scalar(constraintsFrame[iConstraint,2])==\"valueCompare\" & colIdx1!=0){\n+ value2 = as.scalar(constraintsFrame[iConstraint,8]) # value 2 to compare in the constraint\n+ if(rel==\"<\"){\n+ for(iInstance in 2:N){\n+ value1 = as.scalar(dataFrame[iInstance,colIdx1]) # value 1 to compare in the constraint\n+ if(as.integer(value1)<as.integer(value2) & as.scalar(IsGroupInstanceM[iInstance,1])){\n+ flag = flag+1\n+ WrongInstances[flag,1] = iInstance-1\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ } else if(rel==\">\"){\n+ for(iInstance in 2:N){\n+ value1 = as.scalar(dataFrame[iInstance,colIdx1]) # value 1 to compare in the constraint\n+ if(as.integer(value1)>as.integer(value2) & as.scalar(IsGroupInstanceM[iInstance,1])){\n+ flag = flag+1\n+ WrongInstances[flag,1] = iInstance-1\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ } else if(rel==\"=\"){\n+ for(iInstance in 2:N){\n+ value1 = as.scalar(dataFrame[iInstance,colIdx1]) # value 1 to compare in the constraint\n+ if(as.integer(value1)==as.integer(value2) & as.scalar(IsGroupInstanceM[iInstance,1])){\n+ flag = flag+1\n+ WrongInstances[flag,1] = iInstance-1\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ }\n+\n+ # CONSTRAINT TO COMPARE THE RELATION BETWEEN VARIABLES FOR DIFFERENT INSTANCES\n+\n+ } else if(as.scalar(constraintsFrame[iConstraint,2])==\"instanceCompare\" & colIdx1!=0){\n+\n+ var2 = as.scalar(constraintsFrame[iConstraint,8]) # variable 2 of the constraint\n+ isCol2 = map(colName, \"x->x.equals(\\\"\"+var2+\"\\\")\")\n+ colIdx2=0\n+ for(iLog in 1:ncol(colName)){\n+ if(as.scalar(isCol2[1,iLog])==\"true\"){\n+ colIdx2=iLog\n+ }\n+ }\n+ if (colIdx2==0){\n+ print('Variable 2 for constraint ' + toString(iConstraint-1) + \" not found in dataFrame\")\n+ } else {\n+\n+ # Define a matrix with as many rows as it should be considered according to \"group.by\" and the following 3 columns:\n+ # (1) index of the instance, (2) instances or variable 1, (3) instances of the variable 2\n+ DataMatrix = matrix(0,cols=4,rows=N-1)\n+ flag3=0\n+ for(iInstance in 2:N){\n+ if(as.scalar(IsGroupInstanceM[iInstance,1])){\n+ flag3=flag3+1\n+ DataMatrix[flag3,1] = as.matrix(dataFrame[iInstance,1]) # InstanceIdx\n+ DataMatrix[flag3,2] = as.matrix(dataFrame[iInstance,colIdx1])\n+ DataMatrix[flag3,3] = as.matrix(dataFrame[iInstance,colIdx2])\n+ }\n+ }\n+ DataMatrix=DataMatrix[1:flag3,]\n+\n+ # order the matrix according to the values of variable 1, decreasing or increasing depending on the first part of the relation(> or <):\n+ if(rel==\"<>\" | rel==\"<<\"){\n+ DataMatrixOrdered = order(target=DataMatrix,by=2,decreasing=FALSE,index.return=FALSE)\n+ } else if(rel==\">>\" | rel==\"><\"){\n+ DataMatrixOrdered = order(target=DataMatrix,by=2,decreasing=TRUE,index.return=FALSE)\n+ }\n+\n+ # define groups of rows in the way that every group has the same value for variable 1 (second column of DataMatrixOrdered):\n+ idxToGroup=matrix(0,flag3,1)\n+ flag2=1\n+ for(iRow in 2:flag3){\n+ if((as.scalar(DataMatrixOrdered[iRow,2])-as.scalar(DataMatrixOrdered[iRow-1,2]))!=0){ # there is a change of group\n+ flag2=flag2+1\n+ idxToGroup[flag2,1]=iRow # vector with the row indexes where there is a change of group\n+ }\n+ }\n+ idxToGroup=idxToGroup[1:flag2,1]\n+ idxOrdered = DataMatrixOrdered[,1]\n+ # loop over the groups and see if they fulfill the constrain (compare every group with the next one):\n+ for (iGroup in 1:(flag2-2)){\n+ idx1 = as.scalar(idxToGroup[iGroup,1])\n+ idx2 = as.scalar(idxToGroup[iGroup+1,1])\n+ idx3 = as.scalar(idxToGroup[iGroup+2,1])\n+\n+ if(rel==\"<<\" | rel==\"><\"){\n+ G1 = DataMatrixOrdered[idx1+1:idx2,] # first group\n+ G2 = DataMatrixOrdered[idx2+1:idx3,] # second group\n+ M1 = min(G1[,3])\n+ M2 = max(G2[,3])\n+ if(M1<M2){\n+ for(iNumber in 1:nrow(G1)){\n+ if(as.integer(as.scalar(G1[iNumber,3]))<M2){\n+ flag = flag+1\n+ WrongInstances[flag,1] = as.scalar(G1[iNumber,1])\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ for(iNumber in 1:nrow(G2)){\n+ if(as.integer(as.scalar(G2[iNumber,3]))>M1){\n+ flag = flag+1\n+ WrongInstances[flag,1] = as.scalar(G2[iNumber,1])\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ }\n+\n+ } else if(rel==\"<>\" | rel==\">>\"){\n+ G1 = DataMatrixOrdered[idx1+1:idx2,] # first group\n+ G2 = DataMatrixOrdered[idx2+1:idx3,] # second group\n+ M1 = max(G1[,3])\n+ M2 = min(G2[,3])\n+ if(M1>M2){\n+ for(iNumber in 1:nrow(G1)){\n+ if(as.integer(as.scalar(G1[iNumber,3]))>as.integer(M2)){\n+ flag = flag+1\n+ WrongInstances[flag,1] = as.scalar(G1[iNumber,1])\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ for(iNumber in 1:nrow(G2)){\n+ if(as.integer(as.scalar(G2[iNumber,3]))<as.integer(M1)){\n+ flag = flag+1\n+ WrongInstances[flag,1] = as.scalar(G2[iNumber,1])\n+ WrongInstances[flag,2] = iConstraint-1\n+ }\n+ }\n+ }\n+ }\n+ }\n+ }\n+ }\n+ }\n+\n+ if (flag==0){\n+ flag=1\n+ print(\"0 constraints are fulfilled\")\n+ }\n+\n+ # Define the final output:\n+ WrongInstances=WrongInstances[1:flag,]\n+ WrongInstances = order(target=WrongInstances,by=1,decreasing=FALSE,index.return=FALSE)\n+}\n+\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -103,6 +103,7 @@ public enum Builtins {\nCOR(\"cor\", true),\nDBSCAN(\"dbscan\", true),\nDETECTSCHEMA(\"detectSchema\", false),\n+ DENIALCONSTRAINTS(\"denialConstraints\", true),\nDIAG(\"diag\", false),\nDISCOVER_FD(\"discoverFD\", true),\nDISCOVER_MD(\"mdedup\", true),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinDenialConstraintTest.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.apache.sysds.test.functions.builtin;\n+\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.lops.LopProperties.ExecType;\n+import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Test;\n+\n+import java.io.IOException;\n+import java.util.HashMap;\n+\n+public class BuiltinDenialConstraintTest extends AutomatedTestBase {\n+\n+ private final static String TEST_NAME = \"denial_constraints\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinDenialConstraintTest.class.getSimpleName() + \"/\";\n+ private final static double eps = 1e-10;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {\"M\"}));\n+ }\n+\n+ @Test\n+ public void testSpark() throws IOException {\n+ runConstraints_Test(ExecType.SPARK);\n+ }\n+ @Test\n+ public void testCP() throws IOException {\n+ runConstraints_Test(ExecType.CP);\n+ }\n+\n+\n+ private void runConstraints_Test(ExecType instType)\n+ {\n+ Types.ExecMode platformOld = setExecMode(instType);\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[] {\"-nvargs\", \"M=\"+ output(\"Mx\")};\n+\n+ runTest(true, false, null, -1);\n+ double[][] X = {{1, 1}, {1, 2}, {1, 5}, {2, 2}, {2, 5}, {3, 6}, {4 , 2}, {4, 5}, {5, 1}, {5, 2}, {5, 5},\n+ {6, 4}, {7, 2}, {8 , 2}, {9, 2}, {10, 1}, {10, 2}, {10 , 5}};\n+ HashMap<CellIndex, Double> dmlfile_m = readDMLMatrixFromOutputDir(\"Mx\");\n+ double[][] Y = TestUtils.convertHashMapToDoubleArray(dmlfile_m);\n+ TestUtils.compareMatrices(X, Y, eps);\n+\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/data/DenialConstraints.csv", "diff": "+idx,constrain.type,group.by,group.variable,group.option,variable1,relation1,variable2\n+1,variableCompare,FALSE,,,yrs.since.phd,<,yrs.service\n+2,instanceCompare,TRUE,rank,Prof,yrs.since.phd,><,salary\n+3,valueCompare,FALSE,,,salary,=,78182\n+4,variableCompare,TRUE,discipline,B,yrs.service,=,yrs.since.phd\n+5,instanceCompare,TRUE,rank,Prof,yrs.since.phd,<>,yrs.service\n+6,valueCompare,TRUE,discipline,B,salary,<,90000\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/data/Salaries_testDenialConstraints.csv", "diff": "+,rank,discipline,yrs.since.phd,yrs.service,sex,salary\n+1,Prof,B,17,18,Male,139750\n+2,Prof,B,20,16,Male,173200\n+3,AsstProf,B,4,3,Male,79750\n+4,Prof,B,45,39,Male,115000\n+5,Prof,B,40,41,Male,141500\n+6,AssocProf,B,6,6,Male,97000\n+7,Prof,B,30,23,Male,175000\n+8,Prof,A,45,45,Male,147765\n+9,Prof,A,21,20,Male,119250\n+10,Prof,A,18,21,Female,129000\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/denial_constraints.dml", "diff": "+#-------------------------------------------------------------\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+F1 = read(\"src/test/scripts/functions/builtin/data/Salaries_testDenialConstraints.csv\", data_type=\"frame\", format=\"csv\");\n+F2 = read(\"src/test/scripts/functions/builtin/data/DenialConstraints.csv\", data_type=\"frame\", format=\"csv\");\n+output1 = denialConstraints(F1, F2);\n+write(output1, $M);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2895] Builtin for Denial Constraints Validation DIA Project WS2020/21 Closes #1188.
49,706
11.03.2021 12:41:27
-3,600
d575d3190e65cff72e50b5e42311552620c78278
Spark Log4j propagation This commit modify out bin/systemds to properly propagate our log4j settings to workers and controller in spark to allow control over the log output from spark execution in systemds.
[ { "change_type": "MODIFY", "old_path": "bin/systemds", "new_path": "bin/systemds", "diff": "@@ -246,6 +246,7 @@ if [ -z \"$LOG4JPROP\" ] ; then\nif [ -z \"${LOG4JPROP}\" ]; then\nLOG4JPROP=\"\"\nelse\n+ SPARK_LOG4J_PATH=\"$LOG4JPROP\"\nLOG4JPROP=\"-Dlog4j.configuration=file:$LOG4JPROP\"\nfi\nelse\n@@ -254,8 +255,10 @@ else\nif [ -z \"${LOG4JPROP2}\" ]; then\nLOG4JPROP=\"\"\nelse\n+ SPARK_LOG4J_PATH=\"$LOG4JPROP2\"\nLOG4JPROP=\"-Dlog4j.configuration=file:$LOG4JPROP2\"\nfi\n+\nfi\nif [[ \"$*\" == *-config* ]]; then\n@@ -366,6 +369,9 @@ else\nexport SPARK_MAJOR_VERSION=2\nCMD=\" \\\nspark-submit $SYSTEMDS_DISTRIBUTED_OPTS \\\n+ --conf spark.driver.extraJavaOptions=-Dlog4j.configuration=file:$SPARK_LOG4J_PATH \\\n+ --conf spark.executor.extraJavaOptions=-Dlog4j.configuration=file:$SPARK_LOG4J_PATH \\\n+ --files $SPARK_LOG4J_PATH \\\n$SYSTEMDS_JAR_FILE \\\n-f $SCRIPT_FILE \\\n$*\"\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/conf/DMLConfig.java", "new_path": "src/main/java/org/apache/sysds/conf/DMLConfig.java", "diff": "@@ -126,7 +126,7 @@ public class DMLConfig\n_defaultVals.put(CP_PARALLEL_IO, \"true\" );\n_defaultVals.put(COMPRESSED_LINALG, Compression.CompressConfig.FALSE.name() );\n_defaultVals.put(COMPRESSED_LOSSY, \"false\" );\n- _defaultVals.put(COMPRESSED_VALID_COMPRESSIONS, \"SDC,DDC,RLE\");\n+ _defaultVals.put(COMPRESSED_VALID_COMPRESSIONS, \"SDC,DDC\");\n_defaultVals.put(COMPRESSED_OVERLAPPING, \"true\" );\n_defaultVals.put(COMPRESSED_SAMPLING_RATIO, \"0.01\");\n_defaultVals.put(COMPRESSED_COCODE, \"COST\");\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2896] Spark Log4j propagation This commit modify out bin/systemds to properly propagate our log4j settings to workers and controller in spark to allow control over the log output from spark execution in systemds.
49,698
14.03.2021 11:08:05
-19,080
e3e57ba710cfec43b13d4c9e158e53299a9865be
[MINOR] add link to windows dev doc
[ { "change_type": "MODIFY", "old_path": "docs/site/install.md", "new_path": "docs/site/install.md", "diff": "@@ -29,7 +29,7 @@ This guide helps in the install and setup of SystemDS from source code.\n## Windows\n-TODO\n+[Developer Guide](https://github.com/apache/systemds/blob/master/dev/docs/windows-source-installation.md)\n---\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] add link to windows dev doc
49,706
13.03.2021 11:00:01
-3,600
2bc40ed35e9be42e8442ca5227c61ec10220b7d4
CLA decompressing write
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/CompressedMatrixBlock.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/CompressedMatrixBlock.java", "diff": "@@ -205,32 +205,16 @@ public class CompressedMatrixBlock extends MatrixBlock {\n// preallocation sparse rows to avoid repeated reallocations\nMatrixBlock ret = new MatrixBlock(rlen, clen, false, -1);\n+ if(nonZeros == -1)\n+ ret.setNonZeros(this.recomputeNonZeros());\n+ else\n+ ret.setNonZeros(nonZeros);\nret.allocateDenseBlock();\n- // (nonZeros == -1) ?\n- // .allocateBlock() : new MatrixBlock(rlen, clen, sparse,\n- // nonZeros).allocateBlock();\n-\n- // if(ret.isInSparseFormat()) {\n- // int[] rnnz = new int[rlen];\n- // // for(ColGroup grp : _colGroups)\n- // // grp.countNonZerosPerRow(rnnz, 0, rlen);\n- // ret.allocateSparseRowsBlock();\n- // SparseBlock rows = ret.getSparseBlock();\n- // for(int i = 0; i < rlen; i++)\n- // rows.allocate(i, rnnz[i]);\n- // }\n+ // todo Add sparse decompress.\n- // core decompression (append if sparse)\nfor(AColGroup grp : _colGroups)\ngrp.decompressToBlockUnSafe(ret, 0, rlen, 0, grp.getValues());\n- // post-processing (for append in decompress)\n- if(ret.getNonZeros() == -1 || nonZeros == -1) {\n- ret.recomputeNonZeros();\n- }\n- else {\n- ret.setNonZeros(nonZeros);\n- }\nif(ret.isInSparseFormat())\nret.sortSparseRows();\n@@ -256,8 +240,10 @@ public class CompressedMatrixBlock extends MatrixBlock {\nTiming time = new Timing(true);\nMatrixBlock ret = new MatrixBlock(rlen, clen, false, -1).allocateBlock();\n-\n- nonZeros = 0;\n+ if(nonZeros == -1)\n+ ret.setNonZeros(this.recomputeNonZeros());\n+ else\n+ ret.setNonZeros(nonZeros);\nboolean overlapping = isOverlapping();\ntry {\nExecutorService pool = CommonThreadPool.get(k);\n@@ -272,20 +258,13 @@ public class CompressedMatrixBlock extends MatrixBlock {\nList<Future<Long>> rtasks = pool.invokeAll(tasks);\npool.shutdown();\nfor(Future<Long> rt : rtasks)\n- nonZeros += rt.get(); // error handling\n+ rt.get(); // error handling\n}\ncatch(InterruptedException | ExecutionException ex) {\nLOG.error(\"Parallel decompression failed defaulting to non parallel implementation \" + ex.getMessage());\n- nonZeros = -1;\nex.printStackTrace();\nreturn decompress();\n}\n- if(overlapping) {\n- ret.recomputeNonZeros();\n- }\n- else {\n- ret.setNonZeros(nonZeros);\n- }\nif(DMLScript.STATISTICS || LOG.isDebugEnabled()) {\ndouble t = time.stop();\n@@ -299,6 +278,22 @@ public class CompressedMatrixBlock extends MatrixBlock {\nreturn CLALibSquash.squash(this, k);\n}\n+ @Override\n+ public long recomputeNonZeros() {\n+ if(overlappingColGroups) {\n+ nonZeros = clen * rlen;\n+ }\n+ else {\n+ long nnz = 0;\n+ for(AColGroup g : _colGroups) {\n+ nnz += g.getNumberNonZeros();\n+ }\n+ nonZeros = nnz;\n+ }\n+ return nonZeros;\n+\n+ }\n+\n/**\n* Obtain an upper bound on the memory used to store the compressed block.\n*\n@@ -497,6 +492,7 @@ public class CompressedMatrixBlock extends MatrixBlock {\nCLALibLeftMultBy.leftMultByMatrixTransposed(this, tmp, out, k);\nout = LibMatrixReorg.transposeInPlace(out, k);\n+ out.recomputeNonZeros();\nreturn out;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/AColGroup.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/AColGroup.java", "diff": "@@ -646,6 +646,8 @@ public abstract class AColGroup implements Serializable {\npublic abstract boolean containsValue(double pattern);\n+ public abstract long getNumberNonZeros();\n+\n@Override\npublic String toString() {\nStringBuilder sb = new StringBuilder();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ADictionary.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ADictionary.java", "diff": "@@ -250,4 +250,6 @@ public abstract class ADictionary {\npublic abstract ADictionary reExpandColumns(int max);\npublic abstract boolean containsValue(double pattern);\n+\n+ public abstract long getNumberNonZeros(int[] counts, int nCol);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupUncompressed.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupUncompressed.java", "diff": "@@ -543,4 +543,9 @@ public class ColGroupUncompressed extends AColGroup {\npublic boolean containsValue(double pattern){\nreturn _data.containsValue(pattern);\n}\n+\n+ @Override\n+ public long getNumberNonZeros(){\n+ return _data.getNonZeros();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupValue.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupValue.java", "diff": "@@ -1030,4 +1030,10 @@ public abstract class ColGroupValue extends AColGroup implements Cloneable {\npublic boolean containsValue(double pattern){\nreturn _dict.containsValue(pattern);\n}\n+\n+ @Override\n+ public long getNumberNonZeros(){\n+ int[] counts = getCounts();\n+ return _dict.getNumberNonZeros(counts, _colIndexes.length);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/Dictionary.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/Dictionary.java", "diff": "@@ -387,4 +387,20 @@ public class Dictionary extends ADictionary {\nreturn false;\n}\n+\n+ @Override\n+ public long getNumberNonZeros(int[] counts, int nCol){\n+ long nnz = 0;\n+ final int nRow = _values.length / nCol;\n+ for(int i = 0; i < nRow; i++){\n+ long rowCount = 0;\n+ final int off = i * nCol;\n+ for(int j = off; j < off + nCol; j++){\n+ if(_values[j] != 0)\n+ rowCount ++;\n+ }\n+ nnz += rowCount * counts[i];\n+ }\n+ return nnz;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/QDictionary.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/QDictionary.java", "diff": "@@ -452,4 +452,20 @@ public class QDictionary extends ADictionary {\nreturn false;\nthrow new NotImplementedException(\"Not contains value on Q Dictionary\");\n}\n+\n+ @Override\n+ public long getNumberNonZeros(int[] counts, int nCol){\n+ long nnz = 0;\n+ final int nRow = _values.length / nCol;\n+ for(int i = 0; i < nRow; i++){\n+ long rowCount = 0;\n+ final int off = i * nCol;\n+ for(int j = off; j < off + nCol; j++){\n+ if(_values[j] != 0)\n+ rowCount ++;\n+ }\n+ nnz += rowCount * counts[i];\n+ }\n+ return nnz;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibAppend.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibAppend.java", "diff": "@@ -42,9 +42,7 @@ public class CLALibAppend {\n// return left;\nfinal int m = left.getNumRows();\nfinal int n = left.getNumColumns() + right.getNumColumns();\n- long nnz = left.getNonZeros() + right.getNonZeros();\n- if(left.getNonZeros() < 0 || right.getNonZeros() < 0)\n- nnz = -1;\n+\n// try to compress both sides (if not already compressed).\nif(!(left instanceof CompressedMatrixBlock) && m > 1000){\n@@ -85,8 +83,11 @@ public class CLALibAppend {\nret.getColGroups().add(tmp);\n}\n+ long nnzl = (leftC.getNonZeros() <= -1 ) ? leftC.recomputeNonZeros() : leftC.getNonZeros() ;\n+ long nnzr = (rightC.getNonZeros() <= -1 ) ? rightC.recomputeNonZeros() : rightC.getNonZeros() ;\n+\n// meta data maintenance\n- ret.setNonZeros(nnz);\n+ ret.setNonZeros(nnzl + nnzr);\nreturn ret;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibCompAgg.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibCompAgg.java", "diff": "@@ -56,7 +56,7 @@ public class CLALibCompAgg {\n// private static final Log LOG = LogFactory.getLog(LibCompAgg.class.getName());\n// private static final long MIN_PAR_AGG_THRESHOLD = 8 * 1024 * 1024;\n- private static final long MIN_PAR_AGG_THRESHOLD = 8;\n+ private static final long MIN_PAR_AGG_THRESHOLD = 8 * 1024 ;\nprivate static ThreadLocal<MatrixBlock> memPool = new ThreadLocal<MatrixBlock>() {\n@Override\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibLeftMultBy.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibLeftMultBy.java", "diff": "@@ -59,7 +59,9 @@ public class CLALibLeftMultBy {\npublic static MatrixBlock leftMultByMatrixTransposed(CompressedMatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int k){\nMatrixBlock transposed = new MatrixBlock(m2.getNumColumns(), m2.getNumRows(), false);\nLibMatrixReorg.transpose(m2, transposed);\n- return leftMultByMatrix(m1, transposed, ret, k );\n+ ret = leftMultByMatrix(m1, transposed, ret, k );\n+ ret.recomputeNonZeros();\n+ return ret;\n// return LibMatrixReorg.transpose(ret, new MatrixBlock(ret.getNumColumns(), ret.getNumRows(), false));\n}\n@@ -75,8 +77,10 @@ public class CLALibLeftMultBy {\npublic static MatrixBlock leftMultByMatrix(CompressedMatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int k) {\nprepareReturnMatrix(m1, m2, ret, false);\n- return leftMultByMatrix(m1\n+ ret = leftMultByMatrix(m1\n.getColGroups(), m2, ret, false, m1.getNumColumns(), m1.isOverlapping(), k, m1.getMaxNumValues());\n+ ret.recomputeNonZeros();\n+ return ret;\n}\nprivate static MatrixBlock leftMultByMatrix(List<AColGroup> groups, MatrixBlock that, MatrixBlock ret,\n@@ -172,48 +176,6 @@ public class CLALibLeftMultBy {\n}\n}\n- // public static MatrixBlock leftMultByVectorTranspose(List<AColGroup> colGroups, MatrixBlock vector,\n- // MatrixBlock result, boolean doTranspose, int k, Pair<Integer, int[]> v, boolean overlap) {\n-\n- // // transpose vector if required\n- // MatrixBlock rowVector = vector;\n- // if(doTranspose) {\n- // rowVector = new MatrixBlock(1, vector.getNumRows(), false);\n- // LibMatrixReorg.transpose(vector, rowVector);\n- // }\n-\n- // result.reset();\n- // result.allocateDenseBlock();\n-\n- // // multi-threaded execution\n- // try {\n- // // compute uncompressed column group in parallel\n- // // ColGroupUncompressed uc = getUncompressedColGroup();\n- // // if(uc != null)\n- // // uc.leftMultByRowVector(rowVector, result, k);\n-\n- // // compute remaining compressed column groups in parallel\n- // ExecutorService pool = CommonThreadPool.get(Math.min(colGroups.size(), k));\n- // ArrayList<LeftMatrixVectorMultTask> tasks = new ArrayList<>();\n-\n- // tasks.add(new LeftMatrixVectorMultTask(colGroups, rowVector, result, v));\n-\n- // List<Future<Object>> ret = pool.invokeAll(tasks);\n- // pool.shutdown();\n- // for(Future<Object> tmp : ret)\n- // tmp.get();\n-\n- // }\n- // catch(InterruptedException | ExecutionException e) {\n- // throw new DMLRuntimeException(e);\n- // }\n-\n- // // post-processing\n- // result.recomputeNonZeros();\n-\n- // return result;\n- // }\n-\nprivate static MatrixBlock leftMultByCompressedTransposedMatrix(List<AColGroup> colGroups,\nCompressedMatrixBlock that, MatrixBlock ret, int k, int numColumns, Pair<Integer, int[]> v,\nboolean overlapping) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibReExpand.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibReExpand.java", "diff": "@@ -68,8 +68,8 @@ public class CLALibReExpand {\nret.allocateColGroupList(newColGroups);\nret.setOverlapping(true);\n- ret.setNonZeros(-1);\n+ ret.recomputeNonZeros();\nreturn ret;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibRightMultBy.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibRightMultBy.java", "diff": "@@ -42,7 +42,9 @@ public class CLALibRightMultBy {\nprivate static final Log LOG = LogFactory.getLog(CLALibRightMultBy.class.getName());\npublic static MatrixBlock rightMultByMatrix(CompressedMatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int k, boolean allowOverlap){\n- return rightMultByMatrix(m1.getColGroups(), m2, ret, k, m1.getMaxNumValues(), allowOverlap);\n+ ret = rightMultByMatrix(m1.getColGroups(), m2, ret, k, m1.getMaxNumValues(), allowOverlap);\n+ ret.recomputeNonZeros();\n+ return ret;\n}\nprivate static MatrixBlock rightMultByMatrix(List<AColGroup> colGroups, MatrixBlock that, MatrixBlock ret, int k,\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibScalar.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibScalar.java", "diff": "@@ -57,7 +57,9 @@ public class CLALibScalar {\npublic static MatrixBlock scalarOperations(ScalarOperator sop, CompressedMatrixBlock m1, MatrixValue result) {\n// Special case handling of overlapping relational operations\nif(CLALibRelationalOp.isValidForRelationalOperation(sop, m1)) {\n- return CLALibRelationalOp.overlappingRelativeRelationalOperation(sop, m1);\n+ MatrixBlock ret = CLALibRelationalOp.overlappingRelativeRelationalOperation(sop, m1);\n+ ret.recomputeNonZeros();\n+ return ret;\n}\nif(isInvalidForCompressedOutput(m1, sop)) {\n@@ -96,7 +98,7 @@ public class CLALibScalar {\nret.setOverlapping(m1.isOverlapping());\n}\n- ret.setNonZeros(-1);\n+ ret.recomputeNonZeros();\nreturn ret;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibSquash.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibSquash.java", "diff": "@@ -59,7 +59,7 @@ public class CLALibSquash {\nret.allocateColGroupList(retCg);\nret.setOverlapping(false);\n- ret.setNonZeros(-1);\n+ ret.recomputeNonZeros();\nif(ret.isOverlapping())\nthrow new DMLCompressionException(\"Squash should output compressed nonOverlapping matrix\");\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/MatrixObject.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/MatrixObject.java", "diff": "@@ -35,6 +35,7 @@ import org.apache.sysds.conf.ConfigurationManager;\nimport org.apache.sysds.hops.OptimizerUtils;\nimport org.apache.sysds.lops.Lop;\nimport org.apache.sysds.runtime.DMLRuntimeException;\n+import org.apache.sysds.runtime.compress.CompressedMatrixBlock;\nimport org.apache.sysds.runtime.controlprogram.ParForProgramBlock.PDataPartitionFormat;\nimport org.apache.sysds.runtime.controlprogram.context.SparkExecutionContext;\nimport org.apache.sysds.runtime.controlprogram.federated.FederatedRange;\n@@ -583,13 +584,15 @@ public class MatrixObject extends CacheableData<MatrixBlock>\nbegin = System.currentTimeMillis();\n}\n- MetaDataFormat iimd = (MetaDataFormat) _metaData;\n-\nif(this.isFederated() && FileFormat.safeValueOf(ofmt) == FileFormat.FEDERATED){\nReaderWriterFederated.write(fname,this._fedMapping);\n}\nelse if (_data != null)\n{\n+ if(_data instanceof CompressedMatrixBlock)\n+ _data = CompressedMatrixBlock.getUncompressed(_data);\n+\n+ MetaDataFormat iimd = (MetaDataFormat) _metaData;\n// Get the dimension information from the metadata stored within MatrixObject\nDataCharacteristics mc = iimd.getDataCharacteristics();\n// Write the matrix to HDFS in requested format\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/util/DataConverter.java", "new_path": "src/main/java/org/apache/sysds/runtime/util/DataConverter.java", "diff": "@@ -31,6 +31,8 @@ import java.util.Map.Entry;\nimport java.util.StringTokenizer;\nimport org.apache.commons.lang.StringUtils;\n+import org.apache.commons.logging.Log;\n+import org.apache.commons.logging.LogFactory;\nimport org.apache.commons.math3.linear.Array2DRowRealMatrix;\nimport org.apache.commons.math3.linear.BlockRealMatrix;\nimport org.apache.commons.math3.linear.RealMatrix;\n@@ -79,7 +81,7 @@ import org.apache.sysds.runtime.meta.DataCharacteristics;\n*\n*/\npublic class DataConverter {\n- // private static final Log LOG = LogFactory.getLog(DataConverter.class.getName());\n+ private static final Log LOG = LogFactory.getLog(DataConverter.class.getName());\nprivate static final String DELIM = \" \";\n//////////////\n@@ -100,6 +102,9 @@ public class DataConverter {\npublic static void writeMatrixToHDFS(MatrixBlock mat, String dir, FileFormat fmt, DataCharacteristics dc, int replication, FileFormatProperties formatProperties, boolean diag)\nthrows IOException {\nMatrixWriter writer = MatrixWriterFactory.createMatrixWriter( fmt, replication, formatProperties );\n+ if(mat instanceof CompressedMatrixBlock)\n+ mat = CompressedMatrixBlock.getUncompressed(mat);\n+ LOG.error(mat.getNonZeros());\nwriter.writeMatrixToHDFS(mat, dir, dc.getRows(), dc.getCols(), dc.getBlocksize(), dc.getNonZeros(), diag);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2897] CLA decompressing write
49,706
15.03.2021 17:38:24
-3,600
96ecdfae36056efd976c0870b27e517ea9e05c7b
[MINOR] Ignore PCA rewrite tests Closes
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/codegenalg/partone/AlgorithmPCA.java", "new_path": "src/test/java/org/apache/sysds/test/functions/codegenalg/partone/AlgorithmPCA.java", "diff": "@@ -22,7 +22,6 @@ package org.apache.sysds.test.functions.codegenalg.partone;\nimport java.io.File;\nimport java.util.HashMap;\n-import org.junit.Test;\nimport org.apache.sysds.common.Types.ExecMode;\nimport org.apache.sysds.hops.OptimizerUtils;\nimport org.apache.sysds.lops.LopProperties.ExecType;\n@@ -31,6 +30,8 @@ import org.apache.sysds.test.AutomatedTestBase;\nimport org.apache.sysds.test.TestConfiguration;\nimport org.apache.sysds.test.TestUtils;\nimport org.junit.Assert;\n+import org.junit.Ignore;\n+import org.junit.Test;\npublic class AlgorithmPCA extends AutomatedTestBase\n{\n@@ -56,81 +57,97 @@ public class AlgorithmPCA extends AutomatedTestBase\n}\n@Test\n+ @Ignore\npublic void testPCADenseRewritesCP() {\nrunPCATest(TEST_NAME1, true, false, ExecType.CP, CodegenTestType.DEFAULT);\n}\n@Test\n+ @Ignore\npublic void testPCASparseRewritesCP() {\nrunPCATest(TEST_NAME1, true, true, ExecType.CP, CodegenTestType.DEFAULT);\n}\n@Test\n+ @Ignore\npublic void testPCADenseCP() {\nrunPCATest(TEST_NAME1, false, false, ExecType.CP, CodegenTestType.DEFAULT);\n}\n@Test\n+ @Ignore\npublic void testPCASparseCP() {\nrunPCATest(TEST_NAME1, false, true, ExecType.CP, CodegenTestType.DEFAULT);\n}\n@Test\n+ @Ignore\npublic void testPCADenseRewritesSP() {\nrunPCATest(TEST_NAME1, true, false, ExecType.SPARK, CodegenTestType.DEFAULT);\n}\n@Test\n+ @Ignore\npublic void testPCASparseRewritesSP() {\nrunPCATest(TEST_NAME1, true, true, ExecType.SPARK, CodegenTestType.DEFAULT);\n}\n@Test\n+ @Ignore\npublic void testPCADenseSP() {\nrunPCATest(TEST_NAME1, false, false, ExecType.SPARK, CodegenTestType.DEFAULT);\n}\n@Test\n+ @Ignore\npublic void testPCASparseSP() {\nrunPCATest(TEST_NAME1, false, true, ExecType.SPARK, CodegenTestType.DEFAULT);\n}\n@Test\n+ @Ignore\npublic void testPCADenseRewritesCPFuseAll() {\nrunPCATest(TEST_NAME1, true, false, ExecType.CP, CodegenTestType.FUSE_ALL);\n}\n@Test\n+ @Ignore\npublic void testPCASparseRewritesCPFuseAll() {\nrunPCATest(TEST_NAME1, true, true, ExecType.CP, CodegenTestType.FUSE_ALL);\n}\n@Test\n+ @Ignore\npublic void testPCADenseRewritesSPFuseAll() {\nrunPCATest(TEST_NAME1, true, false, ExecType.SPARK, CodegenTestType.FUSE_ALL);\n}\n@Test\n+ @Ignore\npublic void testPCASparseRewritesSPFuseAll() {\nrunPCATest(TEST_NAME1, true, true, ExecType.SPARK, CodegenTestType.FUSE_ALL);\n}\n@Test\n+ @Ignore\npublic void testPCADenseRewritesCPFuseNoRedundancy() {\nrunPCATest(TEST_NAME1, true, false, ExecType.CP, CodegenTestType.FUSE_NO_REDUNDANCY);\n}\n@Test\n+ @Ignore\npublic void testPCASparseRewritesCPFuseNoRedundancy() {\nrunPCATest(TEST_NAME1, true, true, ExecType.CP, CodegenTestType.FUSE_NO_REDUNDANCY);\n}\n@Test\n+ @Ignore\npublic void testPCADenseRewritesSPFuseNoRedundancy() {\nrunPCATest(TEST_NAME1, true, false, ExecType.SPARK, CodegenTestType.FUSE_NO_REDUNDANCY);\n}\n@Test\n+ @Ignore\npublic void testPCASparseRewritesSPFuseNoRedundancy() {\nrunPCATest(TEST_NAME1, true, true, ExecType.SPARK, CodegenTestType.FUSE_NO_REDUNDANCY);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Ignore PCA rewrite tests Closes #1201
49,720
17.03.2021 21:44:26
-3,600
2f3e3816635a0248f18dde6dea8594b8e27ca2ed
Minor built-ins for cleaning pipelines
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/imputeByMode.dml", "diff": "+#-------------------------------------------------------------\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+# Related to [SYSTEMDS-2902] dependency function for cleaning pipelines\n+\n+# impute the data by mode value\n+\n+# INPUT PARAMETERS:\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Double --- Data Matrix (Recoded Matrix for categorical features)\n+# ---------------------------------------------------------------------------------------------\n+\n+\n+#Output(s)\n+# ---------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ---------------------------------------------------------------------------------------------\n+# X Double --- imputed dataset\n+\n+\n+m_imputeByMode = function(Matrix[Double] X)\n+return(Matrix[Double] X)\n+{\n+\n+ Mask = is.na(X)\n+ X = replace(target=X, pattern=NaN, replacement=0)\n+ colMode = matrix(0, 1, ncol(X))\n+ for(i in 1: ncol(X)) {\n+ X_c = removeEmpty(target=X[, i], margin = \"rows\", select=(X[, i] < 1)==0)\n+ if(sum(X_c) == 0)\n+ colMode[1, i] = 1\n+ else {\n+ cat_counts = table(X_c, 1, nrow(X_c), 1); # counts for each category\n+ colMode[1,i] = as.scalar(rowIndexMax(t(cat_counts))) # mode\n+ }\n+ }\n+ Mask = Mask * colMode\n+ X = X + Mask\n+}\n+\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/splitBalanced.dml", "diff": "+#-------------------------------------------------------------\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+# Related to [SYSTEMDS-2902] dependency function for cleaning pipelines\n+\n+# Split input data X and Y into contiguous balanced ratio\n+# ------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# ------------------------------------------------------------------------------\n+# X Matrix --- Input feature matrix\n+# Y Matrix --- Input Labels\n+# f Double 0.7 Train set fraction [0,1]\n+# verbose Boolean FALSE print available\n+# ------------------------------------------------------------------------------\n+# X_train Matrix --- Train split of feature matrix\n+# X_test Matrix --- Test split of feature matrix\n+# y_train Matrix --- Train split of label matrix\n+# y_test Matrix --- Test split of label matrix\n+# ------------------------------------------------------------------------------\n+\n+m_splitBalanced = function(Matrix[Double] X, Matrix[Double] Y, Double splitRatio, Boolean verbose)\n+return (Matrix[Double] X_train, Matrix[Double] y_train, Matrix[Double] X_test,\n+ Matrix[Double] y_test)\n+{\n+\n+ XY = order(target = cbind(Y, X), by = 1, decreasing=FALSE, index.return=FALSE)\n+ # get the class count\n+ classes = table(XY[, 1], 1)\n+ split = floor(nrow(X) * splitRatio)\n+ start_class = 1\n+ train_row_s = 1\n+ test_row_s = 1\n+ train_row_e = 0\n+ test_row_e = 0\n+ end_class = 0\n+\n+ outTrain = matrix(0, split+nrow(classes), ncol(XY))\n+ outTest = matrix(0, (nrow(X) - split)+nrow(classes), ncol(XY))\n+\n+ classes_ratio_train = floor(classes*splitRatio)\n+ classes_ratio_test = classes - classes_ratio_train\n+ if(verbose) {\n+ print(\"rows \"+nrow(X))\n+ print(\"classes \\n\"+toString(classes))\n+ print(\"train ratio \\n\"+toString(classes_ratio_train))\n+ print(\"test ratio \\n\"+toString(classes_ratio_test))\n+ }\n+ for(i in 1:nrow(classes))\n+ {\n+ end_class = end_class + as.scalar(classes[i])\n+ class_t = XY[start_class:end_class, ]\n+\n+ train_row_e = train_row_e + as.scalar(classes_ratio_train[i])\n+ test_row_e = test_row_e + as.scalar(classes_ratio_test[i])\n+\n+ outTrain[train_row_s:train_row_e, ] = class_t[1:as.scalar(classes_ratio_train[i]), ]\n+\n+ outTest[test_row_s:test_row_e, ] = class_t[as.scalar(classes_ratio_train[i])+1:nrow(class_t), ]\n+\n+ train_row_s = train_row_e + 1\n+ test_row_s = test_row_e + 1\n+ start_class = end_class + 1\n+ }\n+ outTrain = removeEmpty(target = outTrain, margin = \"rows\")\n+ outTest = removeEmpty(target = outTest, margin = \"rows\")\n+ y_train = outTrain[, 1]\n+ X_train = outTrain[, 2:ncol(outTrain)]\n+ y_test = outTest[, 1]\n+ X_test = outTest[, 2:ncol(outTest)]\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -132,6 +132,7 @@ public enum Builtins {\nIMG_BRIGHTNESS(\"img_brightness\", true),\nIMPUTE_BY_MEAN(\"imputeByMean\", true),\nIMPUTE_BY_MEDIAN(\"imputeByMedian\", true),\n+ IMPUTE_BY_MODE(\"imputeByMode\", true),\nIMG_CROP(\"img_crop\", true),\nIMPUTE_FD(\"imputeByFD\", true),\nINTERQUANTILE(\"interQuantile\", false),\n@@ -221,6 +222,7 @@ public enum Builtins {\nSMOTE(\"smote\", true),\nSOLVE(\"solve\", false),\nSPLIT(\"split\", true),\n+ SPLIT_BALANCED(\"splitBalanced\", true),\nSTATSNA(\"statsNA\", true),\nSQRT(\"sqrt\", false),\nSUM(\"sum\", false),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinSplitBalancedTest.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.apache.sysds.test.functions.builtin;\n+\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.lops.LopProperties;\n+import org.apache.sysds.lops.LopProperties.ExecType;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.Test;\n+\n+public class BuiltinSplitBalancedTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"splitBalanced\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + BuiltinSplitTest.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[] {\"B\",}));\n+ }\n+\n+ public double eps = 0.00001;\n+ public int cols = 10;\n+ public int rows = 150;\n+\n+\n+ @Test\n+ public void test_CP1() {\n+\n+ runSplitTest(0.7, LopProperties.ExecType.CP);\n+\n+ }\n+ @Test\n+ public void test_CP2() {\n+\n+ runSplitTest(0.8, LopProperties.ExecType.CP);\n+\n+ }\n+\n+ @Test\n+ public void test_Spark() {\n+ runSplitTest( 0.8, LopProperties.ExecType.SPARK);\n+ }\n+\n+ private void runSplitTest(double splitRatio, ExecType instType) {\n+ ExecMode platformOld = setExecMode(instType);\n+\n+ try {\n+ setOutputBuffering(true);\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-nvargs\", \"cols=\" + cols, \"rows=\" + rows, \"split=\"+splitRatio, \"out=\"+output(\"O\")};\n+\n+ runTest(true, false, null, -1);\n+ Assert.assertTrue(TestUtils.readDMLBoolean(output(\"O\")));\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/splitBalanced.dml", "diff": "+#-------------------------------------------------------------\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+\n+X = rand(rows = $rows, cols=$cols, seed=1)\n+Y = ceil(rand(rows = $rows, cols=1, seed=13, sparsity= (1-$split)))\n+Y = Y+1\n+\n+classes = table(Y, 1)\n+\n+[Xtrain, Ytrain, Xtest, Ytest] = splitBalanced(X=X,Y=Y, splitRatio=$split, verbose=FALSE)\n+\n+classCountTrain = table(Ytrain, 1)\n+classCountTest = table(Ytest, 1)\n+\n+verify = as.scalar(classCountTest[2]) == ceil((as.scalar(classes[2]) * (1-$split)))\n+\n+write(verify, $out, format=\"text\")\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2902] Minor built-ins for cleaning pipelines
49,720
17.03.2021 22:48:11
-3,600
797ab881507ad2389aa947430411e04256fc1801
[MINOR] Added support for categorical features in SMOTE
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinGaussianClassifierTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinGaussianClassifierTest.java", "diff": "@@ -85,6 +85,7 @@ public class BuiltinGaussianClassifierTest extends AutomatedTestBase\npublic void testGaussianClassifier(int rows, int cols, double sparsity, int classes)\n{\n+ setOutputBuffering(true);\nloadTestConfiguration(getTestConfiguration(TEST_NAME));\nString HOME = SCRIPT_DIR + TEST_DIR;\nfullDMLScriptName = HOME + TEST_NAME + \".dml\";\n@@ -136,7 +137,7 @@ public class BuiltinGaussianClassifierTest extends AutomatedTestBase\ndouble[][] invcovsSYSTEMDS = TestUtils.convertHashMapToDoubleArray(invcovsSYSTEMDStemp);\nTestUtils.compareMatrices(priorR, priorSYSTEMDS, Math.pow(10, -5.0), \"priorR\", \"priorSYSTEMDS\");\n- TestUtils.compareMatricesBitAvgDistance(meansR, meansSYSTEMDS, 5L,5L, this.toString());\n+ TestUtils.compareMatricesBitAvgDistance(meansR, meansSYSTEMDS, 10L,10L, this.toString());\nTestUtils.compareMatricesBitAvgDistance(determinantsR, determinantsSYSTEMDS, (long)2E+12,(long)2E+12, this.toString());\nTestUtils.compareMatricesBitAvgDistance(invcovsR, invcovsSYSTEMDS, (long)2E+20,(long)2E+20, this.toString());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinSmoteTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinSmoteTest.java", "diff": "@@ -49,29 +49,45 @@ public class BuiltinSmoteTest extends AutomatedTestBase {\n@Test\npublic void testSmote0CP() {\n- runSmoteTest(100, 1, LopProperties.ExecType.CP);\n+ double[][] mask = new double[][]{{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};\n+ runSmoteTest(100, 3, mask, LopProperties.ExecType.CP);\n}\n@Test\npublic void testSmote1CP() {\n- runSmoteTest(300, 10, LopProperties.ExecType.CP);\n+ double[][] mask = new double[][]{{1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}};\n+ runSmoteTest(300, 10, mask, LopProperties.ExecType.CP);\n}\n@Test\npublic void testSmote2CP() {\n- runSmoteTest(400, 5, LopProperties.ExecType.CP);\n+ double[][] mask = new double[][]{{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};\n+ runSmoteTest(400, 5, mask, LopProperties.ExecType.CP);\n}\n@Test\n- public void testSmote1Spark() {\n- runSmoteTest(300, 3, LopProperties.ExecType.SPARK);\n+ public void testSmote3CP() {\n+ double[][] mask = new double[][]{{1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0}};\n+ runSmoteTest(300, 3, mask, LopProperties.ExecType.CP);\n}\n@Test\n- public void testSmote2Spark() { runSmoteTest(400, 5, LopProperties.ExecType.SPARK); }\n+ public void testSmote4CP() {\n+ double[][] mask = new double[][]{{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};\n+ runSmoteTest(400, 5, mask, LopProperties.ExecType.CP); }\n+ public void testSmote3Spark() {\n+ double[][] mask = new double[][]{{1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0}};\n+ runSmoteTest(300, 3, mask, LopProperties.ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testSmote4Spark() {\n+ double[][] mask = new double[][]{{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}};\n+ runSmoteTest(400, 5, mask, LopProperties.ExecType.SPARK); }\n- private void runSmoteTest(int sample, int nn, LopProperties.ExecType instType) {\n+\n+ private void runSmoteTest(int sample, int nn, double[][] mask, LopProperties.ExecType instType) {\nTypes.ExecMode platformOld = setExecMode(instType);\nboolean oldFlag = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n@@ -81,13 +97,16 @@ public class BuiltinSmoteTest extends AutomatedTestBase {\nloadTestConfiguration(getTestConfiguration(TEST_NAME));\nString HOME = SCRIPT_DIR + TEST_DIR;\nfullDMLScriptName = HOME + TEST_NAME + \".dml\";\n- programArgs = new String[] {\"-nvargs\", \"X=\" + input(\"X\"), \"S=\" + sample, \"K=\" + nn , \"Z=\"+output(\"Sum\"), \"T=\"+input(\"T\")};\n-\n- double[][] X = getRandomMatrix(rows, colsX, 0, 1, 0.3, 1);\n+ programArgs = new String[] {\"-nvargs\", \"X=\" + input(\"X\"), \"S=\" + sample, \"M=\"+input(\"M\"),\n+ \"K=\" + nn , \"Z=\"+output(\"Sum\"), \"T=\"+input(\"T\")};\n+ double[][] X = getRandomMatrix(rows, colsX, 1, 10, 1, 1);\n+ X = TestUtils.round(X);\nwriteInputMatrixWithMTD(\"X\", X, true);\n+ writeInputMatrixWithMTD(\"M\", mask, true);\n- double[][] T = getRandomMatrix(rows, colsX, 2, 3.0, 0.3, 3);\n+ double[][] T = getRandomMatrix(rows, colsX, 20, 30, 1, 3);\n+ T = TestUtils.round(T);\nwriteInputMatrixWithMTD(\"T\", T, true);\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/builtin/smote.dml", "new_path": "src/test/scripts/functions/builtin/smote.dml", "diff": "A = read($X);\n-B = smote(X = A, s=$S, k=$K, verbose=TRUE);\n+M = read($M)\n+B = smote(X = A, mask=M, s=$S, k=$K, verbose=TRUE);\n# test if all point fall in same cluster (closed to each other)\n# read some new data T != A\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Added support for categorical features in SMOTE
49,706
24.03.2021 19:55:01
-3,600
8ba9016dcc5aee402861617f94b069cbc7992257
[MINOR] Fix native warning on sparse MM
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixNative.java", "new_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixNative.java", "diff": "@@ -79,11 +79,12 @@ public class LibMatrixNative\nreturn;\n}\n- if( NativeHelper.isNativeLibraryLoaded()\n- && !isMatMultMemoryBound(m1.rlen, m1.clen, m2.clen)\n+ boolean isValidForNative = !isMatMultMemoryBound(m1.rlen, m1.clen, m2.clen)\n&& !m1.isInSparseFormat() && !m2.isInSparseFormat()\n- && m1.getDenseBlock().isContiguous() && m2.getDenseBlock().isContiguous()\n- && 8L * ret.getLength() < Integer.MAX_VALUE ) //contiguous but not allocated\n+ && m1.getDenseBlock().isContiguous() && m2.getDenseBlock().isContiguous() //contiguous but not allocated\n+ && 8L * ret.getLength() < Integer.MAX_VALUE;\n+\n+ if( NativeHelper.isNativeLibraryLoaded() && isValidForNative )\n{\nret.sparse = false;\nret.allocateDenseBlock();\n@@ -114,11 +115,14 @@ public class LibMatrixNative\n}\n//else record failure and fallback to java\nStatistics.incrementNativeFailuresCounter();\n- }\n- //fallback to default java implementation\nLOG.warn(\"matrixMult: Native mat mult failed. Falling back to java version (\"\n+ \"loaded=\" + NativeHelper.isNativeLibraryLoaded()\n+ \", sparse=\" + (m1.isInSparseFormat() | m2.isInSparseFormat()) + \")\");\n+ }\n+\n+ if(isValidForNative)\n+ LOG.debug(\"Was valid for native MM but native lib was not loaded\");\n+\nif (k == 1)\nLibMatrixMult.matrixMult(m1, m2, ret, !examSparsity);\nelse\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix native warning on sparse MM
49,689
25.03.2021 15:43:28
-3,600
b8bdfa8cef3563bd216615c4355a8c5ca097eeb9
Lineage-based reuse of GPU intermediates This patch brings the initial implementation of reuse of GPU memory pointers. This patch only enables reuse for AggregateBinaryGPU instructions. Minor code refactoring is needed to generally support reuse of all GPU operations.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/AggregateBinaryGPUInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/AggregateBinaryGPUInstruction.java", "diff": "@@ -41,7 +41,7 @@ import org.apache.sysds.utils.GPUStatistics;\npublic class AggregateBinaryGPUInstruction extends GPUInstruction implements LineageTraceable {\nprivate CPOperand _input1 = null;\nprivate CPOperand _input2 = null;\n- private CPOperand _output = null;\n+ public CPOperand _output = null;\nprivate boolean _isLeftTransposed;\nprivate boolean _isRightTransposed;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUContext.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUContext.java", "diff": "@@ -254,6 +254,12 @@ public class GPUContext {\nreturn ret;\n}\n+ public GPUObject shallowCopyGPUObject(GPUObject source, MatrixObject mo) {\n+ GPUObject ret = new GPUObject(this, source, mo);\n+ getMemoryManager().getGPUMatrixMemoryManager().addGPUObject(ret);\n+ return ret;\n+ }\n+\n/**\n* Gets the device properties for the active GPU (set with cudaSetDevice()).\n*\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUObject.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUObject.java", "diff": "@@ -102,6 +102,11 @@ public class GPUObject {\n*/\nfinal ShadowBuffer shadowBuffer;\n+ /**\n+ * whether cached in lineage cache\n+ */\n+ private boolean isLineageCached = false;\n+\n// ----------------------------------------------------------------------\n// Methods used to access, set and check jcudaDenseMatrixPtr\n@@ -432,7 +437,7 @@ public class GPUObject {\n/**\n* Initializes this GPUObject with a {@link MatrixObject} instance which will contain metadata about the enclosing matrix block\n*\n- * @param mat2 the matrix block that owns this {@link GPUObject}\n+ * @param mat2 the matrix object that owns this {@link GPUObject}\n*/\nGPUObject(GPUContext gCtx, MatrixObject mat2) {\ngpuContext = gCtx;\n@@ -440,6 +445,22 @@ public class GPUObject {\nthis.shadowBuffer = new ShadowBuffer(this);\n}\n+ public GPUObject(GPUContext gCtx, GPUObject that, MatrixObject mat) {\n+ dirty = that.dirty;\n+ readLocks.reset();\n+ writeLock = false;\n+ timestamp = new AtomicLong(that.timestamp.get());\n+ isSparse = that.isSparse;\n+ isLineageCached = that.isLineageCached;\n+ if (isDensePointerNull())\n+ setDensePointer(that.getDensePointer());\n+ if (getJcudaSparseMatrixPtr() != null)\n+ setSparseMatrixCudaPointer(that.getSparseMatrixCudaPointer());\n+ gpuContext = gCtx;\n+ this.mat = mat;\n+ shadowBuffer = new ShadowBuffer(this);\n+ }\n+\npublic boolean isSparse() {\nreturn isSparse;\n}\n@@ -959,6 +980,8 @@ public class GPUObject {\nif(LOG.isTraceEnabled()) {\nLOG.trace(\"GPU : clearData on \" + this + \", GPUContext=\" + getGPUContext());\n}\n+ if (isLineageCached)\n+ return;\nif (!isDensePointerNull()) {\ngetGPUContext().cudaFreeHelper(opcode, getDensePointer(), eager);\n}\n@@ -990,6 +1013,10 @@ public class GPUObject {\nreturn dirty;\n}\n+ public void setIsLinCached(boolean val) {\n+ isLineageCached = val;\n+ }\n+\n@Override\npublic String toString() {\nfinal StringBuilder sb = new StringBuilder(\"GPUObject{\");\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCache.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCache.java", "diff": "@@ -46,6 +46,9 @@ import org.apache.sysds.runtime.instructions.cp.MultiReturnBuiltinCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.ParameterizedBuiltinCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.ScalarObject;\nimport org.apache.sysds.runtime.instructions.fed.ComputationFEDInstruction;\n+import org.apache.sysds.runtime.instructions.gpu.AggregateBinaryGPUInstruction;\n+import org.apache.sysds.runtime.instructions.gpu.GPUInstruction;\n+import org.apache.sysds.runtime.instructions.gpu.context.GPUObject;\nimport org.apache.sysds.runtime.lineage.LineageCacheConfig.LineageCacheStatus;\nimport org.apache.sysds.runtime.lineage.LineageCacheConfig.ReuseCacheType;\nimport org.apache.sysds.runtime.matrix.data.MatrixBlock;\n@@ -91,7 +94,9 @@ public class LineageCache\nComputationCPInstruction cinst = inst instanceof ComputationCPInstruction ? (ComputationCPInstruction)inst : null;\nComputationFEDInstruction cfinst = inst instanceof ComputationFEDInstruction ? (ComputationFEDInstruction)inst : null;\n- LineageItem instLI = (cinst != null) ? cinst.getLineageItem(ec).getValue():cfinst.getLineageItem(ec).getValue();\n+ LineageItem instLI = (cinst != null) ? cinst.getLineageItem(ec).getValue()\n+ : (cfinst != null) ? cfinst.getLineageItem(ec).getValue()\n+ : ((LineageTraceable)inst).getLineageItem(ec).getValue(); //GPU instruction\nList<MutablePair<LineageItem, LineageCacheEntry>> liList = null;\nif (inst instanceof MultiReturnBuiltinCPInstruction) {\nliList = new ArrayList<>();\n@@ -127,8 +132,10 @@ public class LineageCache\nif(e == null && isMarkedForCaching(inst, ec)) {\nif (cinst != null)\nputIntern(item.getKey(), cinst.output.getDataType(), null, null, 0);\n- else\n+ else if (cfinst != null)\nputIntern(item.getKey(), cfinst.output.getDataType(), null, null, 0);\n+ else if (inst instanceof AggregateBinaryGPUInstruction)\n+ putIntern(item.getKey(), ((AggregateBinaryGPUInstruction)inst)._output.getDataType(), null, null, 0);\n//FIXME: different o/p datatypes for MultiReturnBuiltins.\n}\n}\n@@ -145,13 +152,19 @@ public class LineageCache\ngetOutput(entry.getKey().getOpcode().charAt(entry.getKey().getOpcode().length()-1)-'0').getName();\nelse if (inst instanceof ComputationCPInstruction)\noutName = cinst.output.getName();\n- else\n+ else if (inst instanceof ComputationFEDInstruction)\noutName = cfinst.output.getName();\n+ else if (inst instanceof AggregateBinaryGPUInstruction)\n+ outName = ((AggregateBinaryGPUInstruction) inst)._output.getName();\n- if (e.isMatrixValue())\n+ if (e.isMatrixValue() && e._gpuPointer == null)\nec.setMatrixOutput(outName, e.getMBValue());\n- else\n+ else if (e.isScalarValue())\nec.setScalarOutput(outName, e.getSOValue());\n+ else //TODO handle locks on gpu objects\n+ ec.getMatrixObject(outName).setGPUObject(ec.getGPUContext(0),\n+ ec.getGPUContext(0).shallowCopyGPUObject(e._gpuPointer, ec.getMatrixObject(outName)));\n+\nreuse = true;\nif (DMLScript.STATISTICS) //increment saved time\n@@ -393,6 +406,7 @@ public class LineageCache\nif (LineageCacheConfig.isReusable(inst, ec) ) {\n//if (!isMarkedForCaching(inst, ec)) return;\nList<Pair<LineageItem, Data>> liData = null;\n+ GPUObject liGpuObj = null;\nLineageItem instLI = ((LineageTraceable) inst).getLineageItem(ec).getValue();\nif (inst instanceof MultiReturnBuiltinCPInstruction) {\nliData = new ArrayList<>();\n@@ -404,11 +418,21 @@ public class LineageCache\nliData.add(Pair.of(li, value));\n}\n}\n+ else if (inst instanceof AggregateBinaryGPUInstruction)\n+ liGpuObj = ec.getMatrixObject(((AggregateBinaryGPUInstruction) inst)._output).getGPUObject(ec.getGPUContext(0));\nelse\nliData = inst instanceof ComputationCPInstruction ?\nArrays.asList(Pair.of(instLI, ec.getVariable(((ComputationCPInstruction) inst).output))) :\nArrays.asList(Pair.of(instLI, ec.getVariable(((ComputationFEDInstruction) inst).output)));\nsynchronized( _cache ) {\n+ if (liGpuObj != null) {\n+ LineageCacheEntry centry = _cache.get(instLI);\n+ liGpuObj.setIsLinCached(true);\n+ centry._gpuPointer = liGpuObj;\n+ centry._computeTime = computetime;\n+ centry._status = LineageCacheStatus.CACHED;\n+ return;\n+ }\nfor (Pair<LineageItem, Data> entry : liData) {\nLineageItem item = entry.getKey();\nData data = entry.getValue();\n@@ -640,6 +664,9 @@ public class LineageCache\nif (!LineageCacheConfig.getCompAssRW())\nreturn true;\n+ if (inst instanceof GPUInstruction)\n+ return true;\n+\nCPOperand output = inst instanceof ComputationCPInstruction ?\n((ComputationCPInstruction)inst).output :\n((ComputationFEDInstruction)inst).output;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCacheConfig.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCacheConfig.java", "diff": "@@ -32,6 +32,7 @@ import org.apache.sysds.runtime.instructions.cp.DataGenCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.ListIndexingCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.MatrixIndexingCPInstruction;\nimport org.apache.sysds.runtime.instructions.fed.ComputationFEDInstruction;\n+import org.apache.sysds.runtime.instructions.gpu.GPUInstruction;\nimport java.util.Comparator;\n@@ -188,6 +189,7 @@ public class LineageCacheConfig\npublic static boolean isReusable (Instruction inst, ExecutionContext ec) {\nboolean insttype = inst instanceof ComputationCPInstruction\n|| inst instanceof ComputationFEDInstruction\n+ || inst instanceof GPUInstruction\n&& !(inst instanceof ListIndexingCPInstruction);\nboolean rightop = (ArrayUtils.contains(REUSE_OPCODES, inst.getOpcode())\n|| (inst.getOpcode().equals(\"append\") && isVectorAppend(inst, ec))\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCacheEntry.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCacheEntry.java", "diff": "@@ -24,6 +24,7 @@ import java.util.Map;\nimport org.apache.sysds.common.Types.DataType;\nimport org.apache.sysds.runtime.DMLRuntimeException;\nimport org.apache.sysds.runtime.instructions.cp.ScalarObject;\n+import org.apache.sysds.runtime.instructions.gpu.context.GPUObject;\nimport org.apache.sysds.runtime.lineage.LineageCacheConfig.LineageCacheStatus;\nimport org.apache.sysds.runtime.matrix.data.MatrixBlock;\n@@ -39,6 +40,7 @@ public class LineageCacheEntry {\nprotected LineageItem _origItem;\nprivate String _outfile = null;\nprotected double score;\n+ protected GPUObject _gpuPointer;\npublic LineageCacheEntry(LineageItem key, DataType dt, MatrixBlock Mval, ScalarObject Sval, long computetime) {\n_key = key;\n@@ -49,6 +51,8 @@ public class LineageCacheEntry {\n_status = isNullVal() ? LineageCacheStatus.EMPTY : LineageCacheStatus.CACHED;\n_nextEntry = null;\n_origItem = null;\n+ _outfile = null;\n+ _gpuPointer = null;\n}\nprotected synchronized void setCacheStatus(LineageCacheStatus st) {\n@@ -99,6 +103,10 @@ public class LineageCacheEntry {\nreturn _dt.isMatrix();\n}\n+ public boolean isScalarValue() {\n+ return _dt.isScalar();\n+ }\n+\npublic synchronized void setValue(MatrixBlock val, long computetime) {\n_MBval = val;\n_computeTime = computetime;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/lineage/GPUFullReuseTest.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.apache.sysds.test.functions.lineage;\n+\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+import org.apache.sysds.runtime.lineage.Lineage;\n+import org.apache.sysds.runtime.matrix.data.MatrixValue;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assume;\n+import org.junit.BeforeClass;\n+import org.junit.Test;\n+\n+import jcuda.runtime.cudaError;\n+\n+public class GPUFullReuseTest extends AutomatedTestBase{\n+\n+ protected static final String TEST_DIR = \"functions/lineage/\";\n+ protected static final String TEST_NAME1 = \"FullReuseGPU1\";\n+ protected String TEST_CLASS_DIR = TEST_DIR + GPUFullReuseTest.class.getSimpleName() + \"/\";\n+\n+ @BeforeClass\n+ public static void checkGPU() {\n+ // Skip all the tests if no GPU is available\n+ Assume.assumeTrue(TestUtils.isGPUAvailable() == cudaError.cudaSuccess);\n+ }\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 ReuseSingleInst() { //reuse ba+*\n+ testLineageTraceExec(TEST_NAME1);\n+ }\n+\n+ private void testLineageTraceExec(String testname) {\n+ System.out.println(\"------------ BEGIN \" + testname + \"------------\");\n+ getAndLoadTestConfiguration(testname);\n+\n+ List<String> proArgs = new ArrayList<>();\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(output(\"R\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+ fullDMLScriptName = getScript();\n+\n+ //run the test\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+ HashMap<MatrixValue.CellIndex, Double> R_orig = readDMLMatrixFromOutputDir(\"R\");\n+\n+ AutomatedTestBase.TEST_GPU = true; //adds '-gpu'\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(\"reuse_full\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(output(\"R\"));\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+ AutomatedTestBase.TEST_GPU = false;\n+ HashMap<MatrixValue.CellIndex, Double> R_reused = readDMLMatrixFromOutputDir(\"R\");\n+\n+ //compare results\n+ TestUtils.compareMatrices(R_orig, R_reused, 1e-6, \"Origin\", \"Reused\");\n+ }\n+}\n+\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/lineage/LineageTraceGPUTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/lineage/LineageTraceGPUTest.java", "diff": "@@ -61,12 +61,12 @@ public class LineageTraceGPUTest extends AutomatedTestBase{\nSystem.out.println(\"------------ BEGIN \" + testname + \"------------\");\nint gpuStatus = TestUtils.isGPUAvailable();\n+ if (gpuStatus == cudaError.cudaSuccess)\n+ AutomatedTestBase.TEST_GPU = true; //adds '-gpu'\ngetAndLoadTestConfiguration(testname);\nList<String> proArgs = new ArrayList<>();\nproArgs.add(\"-stats\");\n- if (gpuStatus == cudaError.cudaSuccess)\n- proArgs.add(\"-gpu\");\nproArgs.add(\"-lineage\");\nproArgs.add(\"-args\");\nproArgs.add(output(\"R\"));\n@@ -81,6 +81,7 @@ public class LineageTraceGPUTest extends AutomatedTestBase{\n//get lineage and generate program\nString Rtrace = readDMLLineageFromHDFS(\"R\");\n+ AutomatedTestBase.TEST_GPU = false;\n//NOTE: the generated program is CP-only.\nData ret = LineageRecomputeUtils.parseNComputeLineageTrace(Rtrace, null);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/lineage/FullReuseGPU1.dml", "diff": "+#-------------------------------------------------------------\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+X = rand(rows=1000, cols=100, sparsity=1, seed=42);\n+y = rand(rows=100, cols=100, sparsity=1, seed=42);\n+for (i in 1:10) {\n+ tmp = X %*% y;\n+}\n+R = tmp;\n+\n+write(R, $1, format=\"text\");\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2913] Lineage-based reuse of GPU intermediates This patch brings the initial implementation of reuse of GPU memory pointers. This patch only enables reuse for AggregateBinaryGPU instructions. Minor code refactoring is needed to generally support reuse of all GPU operations.
49,693
25.03.2021 19:58:51
-3,600
9e6017351abb2090219b1a9c7394ad199965cfdc
Fixing GPU memory leak due to untracked GPUObjects that were used after removal.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/CacheableData.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/CacheableData.java", "diff": "@@ -437,6 +437,10 @@ public abstract class CacheableData<T extends CacheBlock> extends Data\nthrow new DMLRuntimeException(\"GPU : Inconsistent internal state - this CacheableData already has a GPUObject assigned to the current GPUContext (\" + gCtx + \")\");\n}\n+ public synchronized void removeGPUObject(GPUContext gCtx) {\n+ _gpuObjects.remove(gCtx);\n+ }\n+\n// *********************************************\n// *** ***\n// *** HIGH-LEVEL METHODS THAT SPECIFY ***\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUMemoryManager.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUMemoryManager.java", "diff": "@@ -450,6 +450,7 @@ public class GPUMemoryManager {\nif(LOG.isDebugEnabled())\nLOG.debug(\"Removing the GPU object: \" + gpuObj);\nmatrixMemoryManager.gpuObjects.remove(gpuObj);\n+ gpuObj.mat.removeGPUObject(gpuObj.getGPUContext());\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2915] Fixing GPU memory leak due to untracked GPUObjects that were used after removal.
49,738
25.03.2021 22:53:46
-3,600
9c7a08dfdbec8a400a378e539dccf295087f7896
[MINOR] Cleanup repo (warnings, compression config, native libs)
[ { "change_type": "MODIFY", "old_path": "conf/SystemDS-config.xml.template", "new_path": "conf/SystemDS-config.xml.template", "diff": "<sysds.cp.parallel.io>true</sysds.cp.parallel.io>\n<!-- enables compressed linear algebra, experimental feature -->\n- <sysds.compressed.linalg>auto</sysds.compressed.linalg>\n+ <sysds.compressed.linalg>false</sysds.compressed.linalg>\n<!-- enables operator fusion via code generation, experimental feature -->\n<sysds.codegen.enabled>false</sysds.codegen.enabled>\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixNative.java", "new_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixNative.java", "diff": "@@ -119,9 +119,8 @@ public class LibMatrixNative\n+ \"loaded=\" + NativeHelper.isNativeLibraryLoaded()\n+ \", sparse=\" + (m1.isInSparseFormat() | m2.isInSparseFormat()) + \")\");\n}\n-\n- if(isValidForNative)\n- LOG.debug(\"Was valid for native MM but native lib was not loaded\");\n+ else if(isValidForNative)\n+ LOG.warn(\"Was valid for native MM but native lib was not loaded\");\nif (k == 1)\nLibMatrixMult.matrixMult(m1, m2, ret, !examSparsity);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/transform/encode/ColumnEncoderDummycode.java", "new_path": "src/main/java/org/apache/sysds/runtime/transform/encode/ColumnEncoderDummycode.java", "diff": "@@ -60,7 +60,6 @@ public class ColumnEncoderDummycode extends ColumnEncoder {\npublic MatrixBlock apply(MatrixBlock in, MatrixBlock out, int outputCol) {\n// Out Matrix should already be correct size!\n// append dummy coded or unchanged values to output\n- final int clen = in.getNumColumns();\nfor(int i = 0; i < in.getNumRows(); i++) {\n// Using outputCol here as index since we have a MatrixBlock as input where dummycoding could have been\n// applied in a previous encoder\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/transform/TransformApplyEmptyRecodeMapTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/transform/TransformApplyEmptyRecodeMapTest.java", "diff": "@@ -26,7 +26,6 @@ import org.apache.sysds.common.Types.ValueType;\nimport org.apache.sysds.runtime.DMLRuntimeException;\nimport org.apache.sysds.runtime.matrix.data.FrameBlock;\nimport org.apache.sysds.runtime.matrix.data.MatrixBlock;\n-import org.apache.sysds.runtime.transform.encode.ColumnEncoder;\nimport org.apache.sysds.runtime.transform.encode.EncoderFactory;\nimport org.apache.sysds.runtime.util.DataConverter;\nimport org.apache.sysds.test.AutomatedTestBase;\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Cleanup repo (warnings, compression config, native libs)
49,738
27.03.2021 01:37:52
-3,600
c20e540095f0af30770f5f4558e93a0641c81f67
[MINOR] Fix IPA function call graph (missing cleanup debug output)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/ipa/FunctionCallGraph.java", "new_path": "src/main/java/org/apache/sysds/hops/ipa/FunctionCallGraph.java", "diff": "@@ -472,7 +472,6 @@ public class FunctionCallGraph\nif( !fstack.contains(lfkey) ) {\nfstack.push(lfkey);\n_fGraph.get(fkey).add(lfkey);\n- System.out.println(fkey+\" -> \"+lfkey);\nFunctionStatementBlock fsb = sb.getDMLProg()\n.getFunctionStatementBlock(fop.getFunctionNamespace(), fop.getFunctionName());\nFunctionStatement fs = (FunctionStatement) fsb.getStatement(0);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/compress/compressScale.java", "new_path": "src/test/java/org/apache/sysds/test/functions/compress/compressScale.java", "diff": "@@ -73,10 +73,11 @@ public class compressScale extends AutomatedTestBase {\n// compressTest(10, 200000, 0.2, ExecType.CP, 0, 5, 1, 0);\n// }\n- public void compressTest(int cols, int rows, double sparsity, LopProperties.ExecType instType, int min, int max,\n- int scale, int center) {\n+ public void compressTest(int cols, int rows, double sparsity, LopProperties.ExecType instType,\n+ int min, int max, int scale, int center) {\nTypes.ExecMode platformOld = setExecMode(instType);\n+ setOutputBuffering(true); //otherwise test fails in local\ntry {\nfullDMLScriptName = SCRIPT_DIR + \"/\" + getTestDir() + getTestName() + \".dml\";\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix IPA function call graph (missing cleanup debug output)
49,738
27.03.2021 15:44:54
-3,600
0c21990bc059697be57ed31bfe884d95cbc131d9
Fix IPA list size propagation across DAGs
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/recompile/Recompiler.java", "new_path": "src/main/java/org/apache/sysds/hops/recompile/Recompiler.java", "diff": "@@ -1418,12 +1418,13 @@ public class Recompiler\nelse if(HopRewriteUtils.isUnary(hop, OpOp1.CAST_AS_MATRIX)\n&& hop.getInput(0) instanceof IndexingOp && hop.getInput(0).getDataType().isList()\n&& HopRewriteUtils.isData(hop.getInput(0).getInput(0), OpOpData.TRANSIENTREAD) ) {\n- ListObject list = (ListObject) vars.get(hop.getInput(0).getInput(0).getName());\n+ Data ldat = vars.get(hop.getInput(0).getInput(0).getName()); //list, or matrix during IPA\nHop rix = hop.getInput(0);\n- if( list != null\n+ if( ldat != null && ldat instanceof ListObject\n&& rix.getInput(1) instanceof LiteralOp\n&& rix.getInput(2) instanceof LiteralOp\n&& HopRewriteUtils.isEqualValue(rix.getInput(1), rix.getInput(2))) {\n+ ListObject list = (ListObject) ldat;\nMatrixObject mo = (MatrixObject) ((rix.getInput(1).getValueType() == ValueType.STRING) ?\nlist.getData(((LiteralOp)rix.getInput(1)).getStringValue()) :\nlist.getData((int)HopRewriteUtils.getIntValueSafe(rix.getInput(1))-1));\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2918] Fix IPA list size propagation across DAGs
49,693
28.03.2021 00:21:41
-3,600
28894797ff7992806268255b45b52a59717db6ae
Follow-up fix to original issue only call removeGPUObject if necessary
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUObject.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUObject.java", "diff": "@@ -992,6 +992,7 @@ public class GPUObject {\nshadowBuffer.clearShadowPointer();\njcudaSparseMatrixPtr = null;\nresetReadWriteLock();\n+ if(mat.getGPUObject(getGPUContext()) == this)\ngetGPUContext().getMemoryManager().removeGPUObject(this);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2915] Follow-up fix to original issue #2915: only call removeGPUObject if necessary
49,738
27.03.2021 21:16:26
-3,600
28a6fa5443f29d878f182817ed1ac5f77a6c502f
Extended multi-threading element-wise binary operations This patch makes some minor performance improvements, by now also supporting multi-threading for matrix-vector (not just matrix-matrix) binary element-wise, sparse-safe operations. Furthermore, this also includes a small specialized code path for axpy (+* and -*).
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/functionobjects/MinusMultiply.java", "new_path": "src/main/java/org/apache/sysds/runtime/functionobjects/MinusMultiply.java", "diff": "@@ -40,6 +40,10 @@ public class MinusMultiply extends TernaryValueFunction implements ValueFunction\n_cnt = cnt;\n}\n+ public double getConstant() {\n+ return _cnt;\n+ }\n+\npublic static MinusMultiply getFnObject() {\nif ( singleObj == null )\nsingleObj = new MinusMultiply();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/functionobjects/PlusMultiply.java", "new_path": "src/main/java/org/apache/sysds/runtime/functionobjects/PlusMultiply.java", "diff": "@@ -46,6 +46,10 @@ public class PlusMultiply extends TernaryValueFunction implements ValueFunctionW\nreturn singleObj;\n}\n+ public double getConstant() {\n+ return _cnt;\n+ }\n+\n@Override\npublic double execute(double in1, double in2, double in3) {\nreturn in1 + in2 * in3;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixBincell.java", "new_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixBincell.java", "diff": "@@ -75,7 +75,11 @@ public class LibMatrixBincell\nMATRIX_COL_VECTOR,\nMATRIX_ROW_VECTOR,\nOUTER_VECTOR_VECTOR,\n- INVALID,\n+ INVALID;\n+ public boolean isMatrixVector() {\n+ return this == MATRIX_COL_VECTOR\n+ || this == MATRIX_ROW_VECTOR;\n+ }\n}\nprivate LibMatrixBincell() {\n@@ -194,7 +198,8 @@ public class LibMatrixBincell\nif( m1.isEmpty() || m2.isEmpty()\n|| ret.getLength() < PAR_NUMCELL_THRESHOLD2\n|| ((op.sparseSafe || isSparseSafeDivide(op, m2))\n- && atype != BinaryAccessType.MATRIX_MATRIX))\n+ && !(atype == BinaryAccessType.MATRIX_MATRIX\n+ || atype.isMatrixVector() && isAllDense(m1, m2, ret))))\n{\nbincellOp(m1, m2, ret, op);\nreturn;\n@@ -296,6 +301,10 @@ public class LibMatrixBincell\nreturn (op.fn instanceof Divide && rhs.getNonZeros()==(long)rhs.getNumRows()*rhs.getNumColumns());\n}\n+ public static boolean isAllDense(MatrixBlock... mb) {\n+ return Arrays.stream(mb).allMatch(m -> !m.sparse);\n+ }\n+\n//////////////////////////////////////////////////////\n// private sparse-safe/sparse-unsafe implementations\n///////////////////////////////////\n@@ -323,7 +332,7 @@ public class LibMatrixBincell\n{\n//note: m2 vector and hence always dense\nif( !m1.sparse && !m2.sparse && !ret.sparse ) //DENSE all\n- safeBinaryMVDense(m1, m2, ret, op);\n+ return safeBinaryMVDense(m1, m2, ret, op, rl, ru);\nelse if( m1.sparse && !m2.sparse && !ret.sparse\n&& atype == BinaryAccessType.MATRIX_ROW_VECTOR)\nsafeBinaryMVSparseDenseRow(m1, m2, ret, op);\n@@ -374,18 +383,20 @@ public class LibMatrixBincell\nreturn ret.getNonZeros();\n}\n- private static void safeBinaryMVDense(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, BinaryOperator op) {\n+ private static long safeBinaryMVDense(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, BinaryOperator op, int rl, int ru) {\nboolean isMultiply = (op.fn instanceof Multiply);\nboolean skipEmpty = (isMultiply);\nBinaryAccessType atype = getBinaryAccessType(m1, m2);\n- int rlen = m1.rlen;\nint clen = m1.clen;\n//early abort on skip and empy\nif( skipEmpty && (m1.isEmptyBlock(false) || m2.isEmptyBlock(false) ) )\n- return; // skip entire empty block\n+ return 0; // skip entire empty block\n+ //guard for postponed allocation in single-threaded exec\n+ if( !ret.isAllocated() )\nret.allocateDenseBlock();\n+\nDenseBlock da = m1.getDenseBlock();\nDenseBlock dc = ret.getDenseBlock();\nlong nnz = 0;\n@@ -394,15 +405,13 @@ public class LibMatrixBincell\n{\ndouble[] b = m2.getDenseBlockValues(); // always single block\n- for( int bi=0; bi<dc.numBlocks(); bi++ ) {\n- double[] a = da.valuesAt(bi);\n- double[] c = dc.valuesAt(bi);\n- int len = dc.blockSize(bi);\n- int off = bi * dc.blockSize();\n- for( int i=0, ix=0; i<len; i++, ix+=clen )\n- {\n+ for( int i=rl; i<ru; i++ ) {\n+ double[] a = da.values(i);\n+ double[] c = dc.values(i);\n+ int ix = da.pos(i);\n+\n//replicate vector value\n- double v2 = (b==null) ? 0 : b[off+i];\n+ double v2 = (b==null) ? 0 : b[i];\nif( skipEmpty && v2 == 0 ) //skip empty rows\ncontinue;\n@@ -414,8 +423,8 @@ public class LibMatrixBincell\nelse { //GENERAL CASE\nif( a != null )\nfor( int j=0; j<clen; j++ ) {\n- c[ix+j] = op.fn.execute( a[ix+j], v2 );\n- nnz += (c[ix+j] != 0) ? 1 : 0;\n+ double val = op.fn.execute( a[ix+j], v2 );\n+ nnz += ((c[ix+j] = val) != 0) ? 1 : 0;\n}\nelse {\ndouble val = op.fn.execute( 0, v2 );\n@@ -425,44 +434,42 @@ public class LibMatrixBincell\n}\n}\n}\n- }\nelse if( atype == BinaryAccessType.MATRIX_ROW_VECTOR )\n{\ndouble[] b = m2.getDenseBlockValues(); // always single block\nif( da==null && b==null ) { //both empty\n- double v = op.fn.execute( 0, 0 );\n- dc.set(v);\n- nnz += (v != 0) ? (long)rlen*clen : 0;\n+ double val = op.fn.execute( 0, 0 );\n+ dc.set(rl, ru, 0, clen, val);\n+ nnz += (val != 0) ? (long)(ru-rl)*clen : 0;\n}\nelse if( da==null ) //left empty\n{\n//compute first row\n- double[] c = dc.valuesAt(0);\n+ double[] c = dc.values(rl);\nfor( int j=0; j<clen; j++ ) {\n- c[j] = op.fn.execute( 0, b[j] );\n- nnz += (c[j] != 0) ? rlen : 0;\n+ double val = op.fn.execute( 0, b[j] );\n+ nnz += ((c[j]=val) != 0) ? (ru-rl) : 0;\n}\n//copy first to all other rows\n- for( int i=1; i<rlen; i++ )\n+ for( int i=rl+1; i<ru; i++ )\ndc.set(i, c);\n}\nelse //default case (incl right empty)\n{\n- for( int bi=0; bi<dc.numBlocks(); bi++ ) {\n- double[] a = da.valuesAt(bi);\n- double[] c = dc.valuesAt(bi);\n- int len = dc.blockSize(bi);\n- for( int i=0, ix=0; i<len; i++, ix+=clen )\n+ for( int i=rl; i<ru; i++ ) {\n+ double[] a = da.values(i);\n+ double[] c = dc.values(i);\n+ int ix = da.pos(i);\nfor( int j=0; j<clen; j++ ) {\n- c[ix+j] = op.fn.execute( a[ix+j], ((b!=null) ? b[j] : 0) );\n- nnz += (c[ix+j] != 0) ? 1 : 0;\n+ double val = op.fn.execute( a[ix+j], ((b!=null) ? b[j] : 0) );\n+ nnz += ((c[ix+j]=val) != 0) ? 1 : 0;\n}\n}\n}\n}\n- ret.nonZeros = nnz;\n+ return nnz;\n}\nprivate static void safeBinaryMVSparseDenseRow(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, BinaryOperator op) {\n@@ -924,6 +931,10 @@ public class LibMatrixBincell\nprivate static long safeBinaryMMDenseDenseDense(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret,\nBinaryOperator op, int rl, int ru)\n{\n+ boolean isPM = m1.clen >= 512 & (op.fn instanceof PlusMultiply | op.fn instanceof MinusMultiply);\n+ double cntPM = !isPM ? Double.NaN : (op.fn instanceof PlusMultiply ?\n+ ((PlusMultiply)op.fn).getConstant() : -1d * ((MinusMultiply)op.fn).getConstant());\n+\n//guard for postponed allocation in single-threaded exec\nif( !ret.isAllocated() )\nret.allocateDenseBlock();\n@@ -941,11 +952,19 @@ public class LibMatrixBincell\ndouble[] b = db.values(i);\ndouble[] c = dc.values(i);\nint pos = da.pos(i);\n+\n+ if( isPM ) {\n+ System.arraycopy(a, pos, c, pos, clen);\n+ LibMatrixMult.vectMultiplyAdd(cntPM, b, c, pos, pos, clen);\n+ lnnz += UtilFunctions.computeNnz(c, pos, clen);\n+ }\n+ else {\nfor(int j=pos; j<pos+clen; j++) {\nc[j] = fn.execute(a[j], b[j]);\nlnnz += (c[j]!=0)? 1 : 0;\n}\n}\n+ }\nreturn lnnz;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2856] Extended multi-threading element-wise binary operations This patch makes some minor performance improvements, by now also supporting multi-threading for matrix-vector (not just matrix-matrix) binary element-wise, sparse-safe operations. Furthermore, this also includes a small specialized code path for axpy (+* and -*).
49,693
02.04.2021 13:26:45
-7,200
9566bdf109c154bac48d97df17619e2053a8f736
Fix in cloned GPUObject removal logic This is a 2nd follow-up fix to properly remove any references to GPUObjects that are to be removed.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUMemoryManager.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUMemoryManager.java", "diff": "@@ -449,8 +449,12 @@ public class GPUMemoryManager {\npublic void removeGPUObject(GPUObject gpuObj) {\nif(LOG.isDebugEnabled())\nLOG.debug(\"Removing the GPU object: \" + gpuObj);\n- matrixMemoryManager.gpuObjects.remove(gpuObj);\n+\n+ // clear reference in MatrixObject if exists (could be a clone)\n+ if(gpuObj.mat.getGPUObject(gpuObj.getGPUContext()) == gpuObj)\ngpuObj.mat.removeGPUObject(gpuObj.getGPUContext());\n+\n+ matrixMemoryManager.gpuObjects.remove(gpuObj);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUObject.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUObject.java", "diff": "@@ -992,7 +992,6 @@ public class GPUObject {\nshadowBuffer.clearShadowPointer();\njcudaSparseMatrixPtr = null;\nresetReadWriteLock();\n- if(mat.getGPUObject(getGPUContext()) == this)\ngetGPUContext().getMemoryManager().removeGPUObject(this);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2915] Fix in cloned GPUObject removal logic This is a 2nd follow-up fix to properly remove any references to GPUObjects that are to be removed.
49,700
02.04.2021 16:23:29
-7,200
ff84032ff6160f06fdfac56ff82379e1e7b400d5
[MINOR] Close
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/TernaryFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/TernaryFEDInstruction.java", "diff": "@@ -176,7 +176,14 @@ public class TernaryFEDInstruction extends ComputationFEDInstruction {\nsetOutputFedMapping(ec, mo1, fr3.getID());\n}\n- // check aligned matrices and return vars\n+ /**\n+ * Check alignment of matrices and return aligned federated data.\n+ * @param ec execution context\n+ * @param mo1 first input matrix\n+ * @param mo2 second input matrix\n+ * @param mo3 third input matrix\n+ * @return aligned federated data\n+ */\nprivate RetAlignedValues getAlignedInputs(ExecutionContext ec, MatrixObject mo1, MatrixObject mo2, MatrixObject mo3) {\nlong[] vars = new long[0];\nFederatedRequest[] fr = new FederatedRequest[0];\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Close #1193
49,738
03.04.2021 14:31:46
-7,200
1d9cf802b2bba705ee0ad29183f28b92387315fa
[MINOR] Updated documentation slicefinder builtin (ML model debugging)
[ { "change_type": "MODIFY", "old_path": "scripts/builtin/slicefinder.dml", "new_path": "scripts/builtin/slicefinder.dml", "diff": "#\n#-------------------------------------------------------------\n+# This builtin function imlements SliceLine, a linear-algebra-based\n+# ML model debugging technique for finding the top-k data slices where\n+# a trained models performs significantly worse than on the overall\n+# dataset. For a detailed description and experimental results, see:\n+#\n+# Svetlana Sagadeeva, Matthias Boehm: SliceLine: Fast,\n+# Linear-Algebra-based Slice Finding for ML Model Debugging.\n+# In: SIGMOD 2021.\n+\n#-------------------------------------------------------------\n# X Input matrix (integer encoded [1..v])\n# e error vector (classification accuracy, l2 norm, etc)\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Updated documentation slicefinder builtin (ML model debugging) Co-authored-by: gilgenbergg <[email protected]>
49,698
11.04.2021 06:52:05
-19,080
0cf5125ab6fdc74abd07cfc9779ca4eba7890b69
[SYSTEMDS-2926][1/3] Update readme with administrative setup Closes
[ { "change_type": "MODIFY", "old_path": "scripts/aws/README.md", "new_path": "scripts/aws/README.md", "diff": "@@ -17,13 +17,113 @@ limitations under the License.\n{% endcomment %}\n-->\n-Instructions:\n+## Administrator setup\n-1. Create aws account / use your existing aws account\n-2. Install aws-cli on your system\n+### With [`Cloud Shell`](https://console.aws.amazon.com/cloudshell/home):\n+\n+Assumed variables,\n+\n+| Name | Value |\n+| --- | --- |\n+| `UserName` | `systemds-bot` |\n+| `GroupName` | `systemds-group` |\n+\n+#### 1. Create a user and a group\n+\n+Create a user and a group, and join user to the created group.\n+\n+[`create-user`](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-user.html)\n+```sh\n+[cloudshell-user@host ~]$ aws iam create-user --user-name systemds-bot\n+{\n+ \"User\": {\n+ \"Path\": \"/\",\n+ \"UserName\": \"systemds-bot\",\n+ \"UserId\": \"AIDAQSHHX7DDAODFXYZ3\",\n+ \"Arn\": \"arn:aws:iam::12345:user/systemds-bot\",\n+ \"CreateDate\": \"2021-04-10T20:36:59+00:00\"\n+ }\n+}\n+```\n+\n+[`create-group`](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-group.html)\n+\n+```sh\n+[cloudshell-user@host ~]$aws iam create-group --group-name systemds-group\n+{\n+ \"Group\": {\n+ \"Path\": \"/\",\n+ \"GroupName\": \"systemds-group\",\n+ \"GroupId\": \"AGPAQSHHX7DDB3XYZABCW\",\n+ \"Arn\": \"arn:aws:iam::12345:group/systemds-group\",\n+ \"CreateDate\": \"2021-04-10T20:41:58+00:00\"\n+ }\n+}\n+```\n+\n+#### 2. Attach roles to the group\n+\n+[`attach-group-policy`](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-group-policy.html)\n+\n+```sh\n+aws iam attach-group-policy --policy-arn arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceRole --group-name systemds-group\n+aws iam attach-group-policy --policy-arn arn:aws:iam::aws:policy/service-role/AmazonElasticMapReduceforEC2Role --group-name systemds-group\n+aws iam attach-group-policy --policy-arn arn:aws:iam::aws:policy/AmazonElasticMapReduceFullAccess --group-name systemds-group\n+aws iam attach-group-policy --policy-arn arn:aws:iam::aws:policy/AWSKeyManagementServicePowerUser --group-name systemds-group\n+aws iam attach-group-policy --policy-arn arn:aws:iam::aws:policy/IAMUserSSHKeys --group-name systemds-group\n+\n+# Grant cloud shell access too.\n+aws iam attach-group-policy --policy-arn arn:aws:iam::aws:policy/AWSCloudShellFullAccess --group-name systemds-group\n+\n+# To create EC2 keys\n+aws iam attach-group-policy --policy-arn arn:aws:iam::aws:policy/AmazonEC2FullAccess --group-name systemds-group\n+```\n+\n+#### 3. Add user to the group\n-(https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html)\n+```sh\n+aws iam add-user-to-group --user-name systemds-bot --group-name systemds-group\n+```\n+\n+#### 4. Create the login-profile with credentials\n+\n+```sh\n+$ aws iam create-login-profile --generate-cli-skeleton > login-profile.json\n+```\n+\n+`login-profile.json` contains\n+\n+```json\n+{\n+ \"LoginProfile\": {\n+ \"UserName\": \"\",\n+ \"Password\": \"\",\n+ \"PasswordResetRequired\": false\n+ }\n+}\n+```\n+\n+Create the credentials manually by editing `login-profile.json`.\n+\n+| Name | Value |\n+| --- | --- |\n+| `UserName` | `systemds-bot` |\n+| `Password` | For example, `9U*tYP` |\n+| `PasswordResetRequired` | `false` |\n+\n+Now, create the login profile.\n+\n+```sh\n+aws iam create-login-profile --cli-input-json file://login-profile.json\n+```\n+\n+---\n+### With [`AWS CLI`](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html):\n+\n+1. Create aws account / use your existing aws account\n+\n+2. Install `aws-cli` specific to your Operating System.\n3. Create a user\n@@ -45,6 +145,8 @@ Instructions:\n4. Configure your aws-cli (https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html#cli-quick-configuration)\n+## User Setup\n+\n5. Spin up an EMR cluster with SystemDS\n* Put your SystemDS artifacts (dml-scripts, jars, config-file) in the directory systemds\n" }, { "change_type": "MODIFY", "old_path": "scripts/aws/spinup_systemds_cluster.sh", "new_path": "scripts/aws/spinup_systemds_cluster.sh", "diff": "@@ -44,17 +44,18 @@ set_config \"SPARK_NUM_EXECUTORS\" $CORE_INSTANCES_COUNT\nset_config \"SPARK_EXECUTOR_CORES\" $SPARK_EXECUTOR_CORES\nset_config \"SPARK_EXECUTOR_MEMORY\" $SPARK_EXECUTOR_MEMORY\nset_config \"SPARK_DRIVER_MEMORY\" \"1G\"\n+set_config \"BUCKET\" $BUCKET-$(((RANDOM % 999) + 1000))\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+aws s3api create-bucket --bucket $BUCKET --region $REGION &> /dev/null\n+aws s3api create-bucket --bucket $BUCKET-logs --region $REGION &> /dev/null\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+aws s3 sync $SYSTEMDS_TARGET_DIRECTORY s3://$BUCKET --exclude \"*\" --include \"*.dml\" --include \"*config.xml\" --include \"*DS.jar*\"\n# Create keypair\nif [ ! -f ${KEYPAIR_NAME}.pem ]; then\n- aws ec2 create-key-pair --key-name $KEYPAIR_NAME --query \"KeyMaterial\" --output text > \"$KEYPAIR_NAME.pem\"\n+ aws ec2 create-key-pair --key-name $KEYPAIR_NAME --region $REGION --query \"KeyMaterial\" --output text > \"$KEYPAIR_NAME.pem\"\nchmod 700 \"${KEYPAIR_NAME}.pem\"\necho \"${KEYPAIR_NAME}.pem private key created!\"\nfi\n@@ -67,7 +68,7 @@ CLUSTER_INFO=$(aws emr create-cluster \\\n--service-role EMR_DefaultRole \\\n--enable-debugging \\\n--release-label $EMR_VERSION \\\n- --log-uri \"s3n://system-ds-logs/\" \\\n+ --log-uri \"s3://$BUCKET-logs/\" \\\n--name \"SystemDS cluster\" \\\n--instance-groups '[{\"InstanceCount\":'${MASTER_INSTANCES_COUNT}',\n\"InstanceGroupType\":\"MASTER\",\n@@ -102,6 +103,7 @@ aws emr wait cluster-running --cluster-id $CLUSTER_ID\necho \"Cluster info:\"\nexport CLUSTER_URL=$(aws emr describe-cluster --cluster-id $CLUSTER_ID | jq .Cluster.MasterPublicDnsName | tr -d '\"')\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+aws emr ssh --cluster-id $CLUSTER_ID --key-pair-file ${KEYPAIR_NAME}.pem --region $REGION \\\n+ --command 'aws s3 cp s3://system-ds-bucket/target . --recursive --exclude \"*\" --include \"*DS.jar*\"'\necho \"Spinup finished.\"\n" }, { "change_type": "MODIFY", "old_path": "scripts/aws/systemds_cluster.config", "new_path": "scripts/aws/systemds_cluster.config", "diff": "KEYPAIR_NAME=\"SystemDSkeynamex\"\nREGION=\"us-east-1\"\n+BUCKET=\"systemds-bucket\"\nEMR_VERSION=\"emr-5.28.0\"\nINSTANCES_TYPE=\"m5.xlarge\"\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2926][1/3] Update readme with administrative setup Closes #1222.
49,720
10.04.2021 21:01:15
-7,200
549bf201dcf8de55680e06a705eb083887bf14ab
[MINOR] Minor fixes in cleaning pipelines (print statements, sample size)
[ { "change_type": "MODIFY", "old_path": "scripts/builtin/bandit.dml", "new_path": "scripts/builtin/bandit.dml", "diff": "@@ -24,6 +24,7 @@ m_bandit = function(Matrix[Double] X_train, Matrix[Double] Y_train, List[Unknown\nFrame[Unknown] lp, Frame[Unknown] primitives, Frame[Unknown] param, Integer k = 3, Integer R=50, Boolean verbose = TRUE)\nreturn (Frame[Unknown] bestPipeline, Matrix[Double] bestHyperparams, Matrix[Double] bestAccuracy, Frame[String] feaFrameOuter)\n{\n+ print(\"Starting optimizer\")\nNUM_FEATURES = 14\nprint(\"null in data \"+sum(is.na(X_train)))\nbestPipeline = frame(\"\", rows=1, cols=1)\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestClassification.java", "new_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestClassification.java", "diff": "@@ -51,9 +51,9 @@ public class CleaningTestClassification extends AutomatedTestBase {\n}\n- @Test\n+ @Ignore\npublic void testCP1() {\n- runFindPipelineTest(0.5, 5,10, 2,\n+ runFindPipelineTest(0.1, 5,10, 2,\ntrue, \"classification\", Types.ExecMode.SINGLE_NODE);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestCompare.java", "new_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestCompare.java", "diff": "@@ -51,14 +51,14 @@ public class CleaningTestCompare extends AutomatedTestBase {\n@Test\npublic void testCP1() {\n- runFindPipelineTest(0.5, 5,10, 2,\n+ runFindPipelineTest(5,10, 2,\ntrue, \"compare\", Types.ExecMode.SINGLE_NODE);\n}\n- private void runFindPipelineTest(Double sample, int topk, int resources, int crossfold,\n+ private void runFindPipelineTest(int topk, int resources, int crossfold,\nboolean weightedAccuracy, String target, Types.ExecMode et) {\n- setOutputBuffering(true);\n+ setOutputBuffering(false);\nString HOME = SCRIPT_DIR+\"functions/pipelines/\" ;\nTypes.ExecMode modeOld = setExecMode(et);\ntry {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/pipelines/intermediates/hyperparams.csv", "diff": "+36.0,0,0,0,0,1.0,0,0,0,2.0,2.0,0,0,0,0,0,0,0,0,0,0,0,0,1.0,0,0,0,2.0,3.0,69.0,0,0,0,0,0,0,2.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n+36.0,0,0,0,0,1.0,0,0,0,2.0,2.0,0,0,0,0,0,0,0,0,0,0,0,0,1.0,0,0,0,2.0,3.0,69.0,1.0,0,0,0,0,0,2.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n+36.0,0,0,0,0,1.0,0,0,0,2.0,2.0,1.0,1.0,0,0,0,0,0,0,0,0,0,0,1.0,0,0,0,2.0,3.0,58.0,1.0,0,0,0,0,0,2.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n+36.0,0,0,0,0,1.0,0,0,0,2.0,2.0,1.0,1.0,0,0,0,0,0,0,0,0,0,0,1.0,0,0,0,2.0,3.0,89.0,0,0,0,0,0,0,2.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n+36.0,0,0,0,0,1.0,0,0,0,2.0,2.0,0,0,0,0,0,0,0,0,0,0,0,0,1.0,0,0,0,2.0,3.0,61.0,1.0,0,0,0,0,0,2.0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/pipelines/intermediates/pipelines.csv", "diff": "+imputeByMedian,scale,dummycoding,pca\n+imputeByMedian,scale,dummycoding,pca\n+imputeByMedian,scale,dummycoding,pca\n+imputeByMean,scale,dummycoding,pca\n+imputeByMedian,scale,dummycoding,pca\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/pipelines/testCompare.dml", "new_path": "src/test/scripts/functions/pipelines/testCompare.dml", "diff": "@@ -40,8 +40,9 @@ cleanData = read($cleanData, data_type=\"frame\", format=\"csv\", header=TRUE,\n# take the sample of 500 rows to avoid java heap issue\n-F = F[1:500,]\n-cleanData = cleanData[1:500,]\n+F = F[1:200, 1:20]\n+cleanData = cleanData[1:200, 1:20]\n+metaInfo = metaInfo[, 1:21]\nif(nrow(metaInfo) < 2)\nstop(\"incomplete meta info\")\n@@ -91,7 +92,7 @@ FD = discoverFD(X=replace(target=eX, pattern=NaN, replacement=1), Mask=getFdMask\nFD = (diag(matrix(1, rows=nrow(FD), cols=1)) ==0) * FD\nFD = FD > 0\n-expectedAccuracy = 0.6\n+expectedAccuracy = 0.5\nmetaList = list(mask=getMask, schema=getSchema, fd=FD)\ntargetClassification = list(target=targetApplicaton, cv=0, wAccuracy=FALSE,\n@@ -125,14 +126,14 @@ print(toString(acc))\nclean_accuracy = as.scalar(acc[1,1])\n-result = expectedAccuracy <= clean_accuracy\n+result = expectedAccuracy < clean_accuracy\nprint(\"result satisfied ------------\"+result)\naccuracies = cbind(as.matrix(expectedAccuracy), as.matrix(clean_accuracy))\n-write(pip, output+\"/pipelines.csv\", format=\"csv\")\n-write(hp, output+\"/hyperparams.csv\", format=\"csv\")\n-write(acc, output+\"/accuracies.csv\", format=\"csv\")\n-write(accuracies , output+\"/BestAccuracy.csv\", format=\"csv\")\n+# write(pip, output+\"/pipelines.csv\", format=\"csv\")\n+# write(hp, output+\"/hyperparams.csv\", format=\"csv\")\n+# write(acc, output+\"/accuracies.csv\", format=\"csv\")\n+# write(accuracies , output+\"/BestAccuracy.csv\", format=\"csv\")\nwrite(result , $O)\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Minor fixes in cleaning pipelines (print statements, sample size)
49,706
12.04.2021 10:09:08
-7,200
a2da7905e38f2bd473a303ecba510440329b2745
[MINOR] Fix regression algorithms python The commit yesterday made the builtin auto generated __init__ file incorrect for executing the python api without the install from pip, this commit fixes this such that it works both if installed and if run from the src/main/python folder.
[ { "change_type": "MODIFY", "old_path": "src/main/python/generator/generator.py", "new_path": "src/main/python/generator/generator.py", "diff": "@@ -42,7 +42,7 @@ class PythonAPIFileGenerator(object):\ninit_path = os.path.join(os.path.dirname(os.path.dirname(\n__file__)), 'systemds', 'operator', 'algorithm', '__init__.py')\n- init_import = u\"from .builtin import {function} \\n\"\n+ init_import = u\"from .builtin.{function} import {function} \\n\"\ninit_all = u\"__all__ = {functions} \\n\"\ndef __init__(self, source_path: str, extension: str = 'py'):\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/__init__.py", "new_path": "src/main/python/systemds/operator/algorithm/__init__.py", "diff": "# Autogenerated By : src/main/python/generator/generator.py\n-from .builtin import abstain\n-from .builtin import als\n-from .builtin import alsCG\n-from .builtin import alsDS\n-from .builtin import alsPredict\n-from .builtin import alsTopkPredict\n-from .builtin import arima\n-from .builtin import bandit\n-from .builtin import bivar\n-from .builtin import components\n-from .builtin import confusionMatrix\n-from .builtin import cor\n-from .builtin import cox\n-from .builtin import cspline\n-from .builtin import csplineDS\n-from .builtin import cvlm\n-from .builtin import dbscan\n-from .builtin import decisionTree\n-from .builtin import discoverFD\n-from .builtin import dist\n-from .builtin import gaussianClassifier\n-from .builtin import getAccuracy\n-from .builtin import glm\n-from .builtin import gmm\n-from .builtin import gmmPredict\n-from .builtin import gnmf\n-from .builtin import gridSearch\n-from .builtin import hyperband\n-from .builtin import img_brightness\n-from .builtin import img_crop\n-from .builtin import img_mirror\n-from .builtin import imputeByFD\n-from .builtin import imputeByMean\n-from .builtin import imputeByMedian\n-from .builtin import imputeByMode\n-from .builtin import intersect\n-from .builtin import km\n-from .builtin import kmeans\n-from .builtin import kmeansPredict\n-from .builtin import knnbf\n-from .builtin import l2svm\n-from .builtin import l2svmPredict\n-from .builtin import lasso\n-from .builtin import lm\n-from .builtin import lmCG\n-from .builtin import lmDS\n-from .builtin import logSumExp\n-from .builtin import msvm\n-from .builtin import msvmPredict\n-from .builtin import multiLogReg\n-from .builtin import multiLogRegPredict\n-from .builtin import na_locf\n-from .builtin import naivebayes\n-from .builtin import normalize\n-from .builtin import outlier\n-from .builtin import outlierByArima\n-from .builtin import outlierByIQR\n-from .builtin import outlierBySd\n-from .builtin import pca\n-from .builtin import pnmf\n-from .builtin import ppca\n-from .builtin import randomForest\n-from .builtin import scale\n-from .builtin import scaleApply\n-from .builtin import sherlock\n-from .builtin import sherlockPredict\n-from .builtin import sigmoid\n-from .builtin import slicefinder\n-from .builtin import smote\n-from .builtin import split\n-from .builtin import splitBalanced\n-from .builtin import statsNA\n-from .builtin import steplm\n-from .builtin import toOneHot\n-from .builtin import tomeklink\n-from .builtin import univar\n-from .builtin import vectorToCsv\n-from .builtin import winsorize\n-from .builtin import xdummy1\n-from .builtin import xdummy2\n+from .builtin.abstain import abstain\n+from .builtin.als import als\n+from .builtin.alsCG import alsCG\n+from .builtin.alsDS import alsDS\n+from .builtin.alsPredict import alsPredict\n+from .builtin.alsTopkPredict import alsTopkPredict\n+from .builtin.arima import arima\n+from .builtin.bandit import bandit\n+from .builtin.bivar import bivar\n+from .builtin.components import components\n+from .builtin.confusionMatrix import confusionMatrix\n+from .builtin.cor import cor\n+from .builtin.cox import cox\n+from .builtin.cspline import cspline\n+from .builtin.csplineDS import csplineDS\n+from .builtin.cvlm import cvlm\n+from .builtin.dbscan import dbscan\n+from .builtin.decisionTree import decisionTree\n+from .builtin.discoverFD import discoverFD\n+from .builtin.dist import dist\n+from .builtin.gaussianClassifier import gaussianClassifier\n+from .builtin.getAccuracy import getAccuracy\n+from .builtin.glm import glm\n+from .builtin.gmm import gmm\n+from .builtin.gmmPredict import gmmPredict\n+from .builtin.gnmf import gnmf\n+from .builtin.gridSearch import gridSearch\n+from .builtin.hyperband import hyperband\n+from .builtin.img_brightness import img_brightness\n+from .builtin.img_crop import img_crop\n+from .builtin.img_mirror import img_mirror\n+from .builtin.imputeByFD import imputeByFD\n+from .builtin.imputeByMean import imputeByMean\n+from .builtin.imputeByMedian import imputeByMedian\n+from .builtin.imputeByMode import imputeByMode\n+from .builtin.intersect import intersect\n+from .builtin.km import km\n+from .builtin.kmeans import kmeans\n+from .builtin.kmeansPredict import kmeansPredict\n+from .builtin.knnbf import knnbf\n+from .builtin.l2svm import l2svm\n+from .builtin.l2svmPredict import l2svmPredict\n+from .builtin.lasso import lasso\n+from .builtin.lm import lm\n+from .builtin.lmCG import lmCG\n+from .builtin.lmDS import lmDS\n+from .builtin.logSumExp import logSumExp\n+from .builtin.msvm import msvm\n+from .builtin.msvmPredict import msvmPredict\n+from .builtin.multiLogReg import multiLogReg\n+from .builtin.multiLogRegPredict import multiLogRegPredict\n+from .builtin.na_locf import na_locf\n+from .builtin.naivebayes import naivebayes\n+from .builtin.normalize import normalize\n+from .builtin.outlier import outlier\n+from .builtin.outlierByArima import outlierByArima\n+from .builtin.outlierByIQR import outlierByIQR\n+from .builtin.outlierBySd import outlierBySd\n+from .builtin.pca import pca\n+from .builtin.pnmf import pnmf\n+from .builtin.ppca import ppca\n+from .builtin.randomForest import randomForest\n+from .builtin.scale import scale\n+from .builtin.scaleApply import scaleApply\n+from .builtin.sherlock import sherlock\n+from .builtin.sherlockPredict import sherlockPredict\n+from .builtin.sigmoid import sigmoid\n+from .builtin.slicefinder import slicefinder\n+from .builtin.smote import smote\n+from .builtin.split import split\n+from .builtin.splitBalanced import splitBalanced\n+from .builtin.statsNA import statsNA\n+from .builtin.steplm import steplm\n+from .builtin.toOneHot import toOneHot\n+from .builtin.tomeklink import tomeklink\n+from .builtin.univar import univar\n+from .builtin.vectorToCsv import vectorToCsv\n+from .builtin.winsorize import winsorize\n+from .builtin.xdummy1 import xdummy1\n+from .builtin.xdummy2 import xdummy2\n__all__ = [abstain, als, alsCG, alsDS, alsPredict, alsTopkPredict, arima, bandit, bivar, components, confusionMatrix, cor, cox, cspline, csplineDS, cvlm, dbscan, decisionTree, discoverFD, dist, gaussianClassifier, getAccuracy, glm, gmm, gmmPredict, gnmf, gridSearch, hyperband, img_brightness, img_crop, img_mirror, imputeByFD, imputeByMean, imputeByMedian, imputeByMode, intersect, km, kmeans, kmeansPredict, knnbf, l2svm, l2svmPredict, lasso, lm, lmCG, lmDS, logSumExp, msvm, msvmPredict, multiLogReg, multiLogRegPredict, na_locf, naivebayes, normalize, outlier, outlierByArima, outlierByIQR, outlierBySd, pca, pnmf, ppca, randomForest, scale, scaleApply, sherlock, sherlockPredict, sigmoid, slicefinder, smote, split, splitBalanced, statsNA, steplm, toOneHot, tomeklink, univar, vectorToCsv, winsorize, xdummy1, xdummy2]\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix regression algorithms python The commit yesterday made the builtin auto generated __init__ file incorrect for executing the python api without the install from pip, this commit fixes this such that it works both if installed and if run from the src/main/python folder.
49,693
12.04.2021 23:06:32
-7,200
769f0e3db1646acdb7212bbe0c2275d69013a2c2
Fix incomplete cbind support in codegen row templates (CUDA) This patch is the CUDA version of the original bugfix (commit 1ec292a932c6e732bbac835a81cdb59371002114)
[ { "change_type": "MODIFY", "old_path": "src/main/cuda/headers/spoof_utils.cuh", "new_path": "src/main/cuda/headers/spoof_utils.cuh", "diff": "@@ -336,19 +336,31 @@ __device__ void vectDivAdd(T* a, T b, T* c, int ai, int ci, int len) {\nvectAdd_atomic<T, DivOp<T>>(a, b, c, ai, ci, len, op);\n}\n+template<typename T>\n+__device__ Vector<T>& vectCbindWrite(T* a, T* b, uint32_t ai, uint32_t bi, uint32_t alen, uint32_t blen, TempStorage<T>* fop) {\n+ Vector<T>& c = fop->getTempStorage(alen+blen);\n+ auto i = threadIdx.x;\n+ while(i < alen) {\n+ c[i] = a[ai + i];\n+ i+=gridDim.x;\n+ }\n+ while(i < blen) {\n+ c[alen + i] = b[bi + i];\n+ }\n+ return c;\n+}\n+\ntemplate<typename T>\n__device__ Vector<T>& vectCbindWrite(T* a, T b, uint32_t ai, uint32_t len, TempStorage<T>* fop) {\nVector<T>& c = fop->getTempStorage(len+1);\n-\n- if(threadIdx.x < len) {\n-// if(blockIdx.x==1 && threadIdx.x ==0)\n-// printf(\"vecCbindWrite: bid=%d, tid=%d, ai=%d, len=%d, a[%d]=%f\\n\", blockIdx.x, threadIdx.x, ai, len, ai * len + threadIdx.x, a[ai * len + threadIdx.x]);\n- c[threadIdx.x] = a[ai + threadIdx.x];\n+ auto i = threadIdx.x;\n+ while(i < len) {\n+ c[i] = a[ai + i];\n+ i += gridDim.x;\n}\n- if(threadIdx.x == len) {\n-// printf(\"---> block %d thread %d, b=%f,, len=%d, a[%d]=%f\\n\",blockIdx.x, threadIdx.x, b, len, ai, a[ai]);\n- c[threadIdx.x] = b;\n+ if(i == len) {\n+ c[i] = b;\n}\nreturn c;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/cuda/Binary.java", "new_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/cuda/Binary.java", "diff": "@@ -30,6 +30,19 @@ public class Binary extends CodeTemplate\npublic String getTemplate(CNodeBinary.BinType type, boolean sparseLhs, boolean sparseRhs,\nboolean scalarVector, boolean scalarInput, boolean vectorVector)\n{\n+ if(type == CNodeBinary.BinType.VECT_CBIND) {\n+ if(scalarInput)\n+ return \"\\t\\tVector<T>& %TMP% = vectCbindWrite(%IN1%, %IN2%, this);\\n\";\n+ else if (!vectorVector)\n+ return sparseLhs ?\n+ \"\\t\\tVector<T>& %TMP% = vectCbindWrite(%IN1v%, %IN2%, %IN1i%, %POS1%, alen, %LEN%, this);\\n\" :\n+ \"\\t\\tVector<T>& %TMP% = vectCbindWrite(%IN1%, %IN2%, %POS1%, %LEN%, this);\\n\";\n+ else //vect/vect\n+ return sparseLhs ?\n+ \"\\t\\tVector<T>& %TMP% = vectCbindWrite(%IN1v%, %IN2%, %IN1i%, %POS1%, %POS2%, alen, %LEN1%, %LEN2%, this);\\n\" :\n+ \"\\t\\tVector<T>& %TMP% = vectCbindWrite(%IN1%, %IN2%, %POS1%, %POS2%, %LEN1%, %LEN2%, this);\\n\";\n+ }\n+\nif(isSinglePrecision()) {\nswitch(type) {\ncase DOT_PRODUCT:\n@@ -84,14 +97,6 @@ public class Binary extends CodeTemplate\nelse\nreturn sparseLhs ? \" T[] %TMP% = LibSpoofPrimitives.vect\" + vectName + \"Write(%IN1v%, %IN2%, %IN1i%, %POS1%, alen, %LEN%);\\n\" : \" T[] %TMP% = LibSpoofPrimitives.vect\" + vectName + \"Write(%IN1%, %IN2%, %POS1%, %LEN%);\\n\";\n}\n-\n- case VECT_CBIND:\n- if(scalarInput)\n- return \" Vector<T>& %TMP% = vectCbindWrite(%IN1%, %IN2%, this);\\n\";\n- else\n-// return sparseLhs ? \" T[] %TMP% = LibSpoofPrimitives.vectCbindWrite(%IN1v%, %IN2%, %IN1i%, %POS1%, alen, %LEN%);\\n\" : \" T[] %TMP% = LibSpoofPrimitives.vectCbindWrite(%IN1%, %IN2%, %POS1%, %LEN%);\\n\";\n- return sparseLhs ? \" T[] %TMP% = LibSpoofPrimitives.vectCbindWrite(%IN1v%, %IN2%, %IN1i%, %POS1%, alen, %LEN%);\\n\" : \" Vector<T>& %TMP% = vectCbindWrite(%IN1%, %IN2%, %POS1%, %LEN%, this);\\n\";\n-\n//vector-vector operations\ncase VECT_MULT:\ncase VECT_DIV:\n@@ -223,14 +228,6 @@ public class Binary extends CodeTemplate\nreturn sparseLhs ? \" Vector<T>& %TMP% = vect\" + vectName + \"Write(%IN1v%, %IN2%, %IN1i%, %POS1%, alen, %LEN%, this);\\n\" : \" Vector<T>& %TMP% = vect\" + vectName + \"Write(%IN1%, %IN2%, static_cast<uint32_t>(%POS1%), %LEN%, this);\\n\";\n}\n- case VECT_CBIND:\n- if(scalarInput)\n- return \" Vector<T>& %TMP% = vectCbindWrite(%IN1%, %IN2%, this);\\n\";\n- else\n-// return sparseLhs ? \" T[] %TMP% = LibSpoofPrimitives.vectCbindWrite(%IN1v%, %IN2%, %IN1i%, %POS1%, alen, %LEN%);\\n\" : \" T[] %TMP% = LibSpoofPrimitives.vectCbindWrite(%IN1%, %IN2%, %POS1%, %LEN%);\\n\";\n-// return sparseLhs ? \" T[] %TMP% = vectCbindWrite(%IN1v%, %IN2%, %IN1i%, %POS1%, alen, %LEN%);\\n\" : \" T* %TMP% = vectCbindWrite(%IN1%, %IN2%, %POS1%, %LEN%);\\n\";\n- return sparseLhs ? \" T[] %TMP% = LibSpoofPrimitives.vectCbindWrite(%IN1v%, %IN2%, %IN1i%, %POS1%, alen, %LEN%);\\n\" : \" Vector<T>& %TMP% = vectCbindWrite(%IN1%, %IN2%, %POS1%, %LEN%, this);\\n\";\n-\n//vector-vector operations\ncase VECT_MULT:\ncase VECT_DIV:\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2888] Fix incomplete cbind support in codegen row templates (CUDA) This patch is the CUDA version of the original bugfix (commit 1ec292a932c6e732bbac835a81cdb59371002114)
49,693
13.04.2021 00:35:06
-7,200
3faacace2cc766c1684d3818dba0aca5a9b7781c
[MINOR] Compilation issue with CUDA codegen's vectCountnnz() function fixed.
[ { "change_type": "MODIFY", "old_path": "src/main/cuda/headers/operators.cuh", "new_path": "src/main/cuda/headers/operators.cuh", "diff": "@@ -106,6 +106,17 @@ struct NotEqualOp {\n}\n};\n+template<typename T>\n+struct NotZero {\n+ __device__ __forceinline__ T operator()(T a, T b) const {\n+ return (a != 0) ? 1.0 : 0.0;\n+ }\n+\n+ __device__ __forceinline__ static T exec(T a, T b) {\n+ return (a != 0) ? 1.0 : 0.0;\n+ }\n+};\n+\ntemplate<typename T>\nstruct XorOp {\n__device__ __forceinline__ static T exec(T a, T b) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/cuda/headers/spoof_utils.cuh", "new_path": "src/main/cuda/headers/spoof_utils.cuh", "diff": "@@ -693,9 +693,8 @@ Vector<T>& vectPow2Write(T* avals, uint32_t* aix, uint32_t ai, uint32_t alen, ui\ntemplate<typename T>\nT vectCountnnz(T* a, uint32_t ai, uint32_t len) {\nSumOp<T> agg_op;\n- NotEqualOp<T> load_op;\n- T result = BLOCK_ROW_AGG(&a[ai], &a[ai], len, agg_op, load_op);\n- return result;\n+ NotZero<T> load_op;\n+ return BLOCK_ROW_AGG(&a[ai], &a[ai], len, agg_op, load_op);\n}\ntemplate<typename T>\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Compilation issue with CUDA codegen's vectCountnnz() function fixed.
49,706
14.04.2021 13:14:32
-7,200
14709cf5ac68f00508cff7e4d7a89d04c53f1acb
[MINOR] Catch exception on tearDown in component convert
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/component/convert/RDDConverterUtilsExtTest.java", "new_path": "src/test/java/org/apache/sysds/test/component/convert/RDDConverterUtilsExtTest.java", "diff": "@@ -24,6 +24,8 @@ import static org.junit.Assert.assertTrue;\nimport java.util.ArrayList;\nimport java.util.List;\n+import org.apache.commons.logging.Log;\n+import org.apache.commons.logging.LogFactory;\nimport org.apache.spark.SparkConf;\nimport org.apache.spark.SparkException;\nimport org.apache.spark.api.java.JavaRDD;\n@@ -36,16 +38,18 @@ import org.apache.spark.sql.SparkSession;\nimport org.apache.spark.sql.types.DataTypes;\nimport org.apache.spark.sql.types.StructField;\nimport org.apache.spark.sql.types.StructType;\n+import org.apache.sysds.runtime.controlprogram.context.SparkExecutionContext;\n+import org.apache.sysds.runtime.instructions.spark.utils.RDDConverterUtilsExt;\n+import org.apache.sysds.test.AutomatedTestBase;\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n-import org.apache.sysds.runtime.controlprogram.context.SparkExecutionContext;\n-import org.apache.sysds.runtime.instructions.spark.utils.RDDConverterUtilsExt;\n-import org.apache.sysds.test.AutomatedTestBase;\npublic class RDDConverterUtilsExtTest extends AutomatedTestBase {\n+ protected static final Log LOG = LogFactory.getLog(RDDConverterUtilsExtTest.class.getName());\n+\nprivate static SparkConf conf;\nprivate static JavaSparkContext sc;\n@@ -156,6 +160,11 @@ public class RDDConverterUtilsExtTest extends AutomatedTestBase {\ntry{\nsc.stop();\n}\n+ catch(Exception e){\n+ // Since it does not matter if the Spark context is closed properly if only executing component tests\n+ // we simply write a warning. This is because our GitHub Actions tests fail sometimes with the spark context.\n+ LOG.warn(e);\n+ }\nfinally{\nsc = null;\nconf = null;\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Catch exception on tearDown in component convert
49,693
14.04.2021 17:13:53
-7,200
6df1ea3c13613e122b4dad5742d2f6db4513f572
Remove function pointers from SPOOF CUDA's MatrixAccessor class The use of function pointers to abstract dense and sparse matrices is a major performance bottleneck. Relying on a conditional if sparse/dense for now. Also sets values per thread to 1 in cellwise template (better performance).
[ { "change_type": "MODIFY", "old_path": "src/main/cuda/headers/Matrix.h", "new_path": "src/main/cuda/headers/Matrix.h", "diff": "@@ -41,7 +41,6 @@ struct Matrix {\ncol_idx(reinterpret_cast<uint32_t*>((jvals[4]))), data(reinterpret_cast<T*>(jvals[5])) {}\n};\n-//#ifdef __CUDACC_RTC__\n#ifdef __CUDACC__\ntemplate<typename T>\n@@ -66,90 +65,47 @@ class MatrixAccessor {\nMatrix<T>* _mat;\n- // Member function pointers\n- uint32_t (MatrixAccessor::*_len)();\n- uint32_t (MatrixAccessor::*_row_len)(uint32_t);\n- uint32_t (MatrixAccessor::*_pos)(uint32_t);\n- uint32_t* (MatrixAccessor::*_col_idxs)(uint32_t);\n-\n- T& (MatrixAccessor::*_val_i)(uint32_t);\n- T& (MatrixAccessor::*_val_rc)(uint32_t, uint32_t);\n- T* (MatrixAccessor::*_vals)(uint32_t);\n- void (MatrixAccessor::*_set)(uint32_t, uint32_t, T);\n-\npublic:\nMatrixAccessor() = default;\n- __device__ MatrixAccessor(Matrix<T>* mat) { init(mat); }\n-\n- __device__ void init(Matrix<T>* mat) {\n- _mat = mat;\n-\n- if (_mat->row_ptr == nullptr) {\n- _len = &MatrixAccessor::len_dense;\n- _pos = &MatrixAccessor::pos_dense;\n- _col_idxs = &MatrixAccessor::cols_dense;\n- _val_rc = &MatrixAccessor::val_dense_rc;\n- _vals = &MatrixAccessor::vals_dense;\n- _row_len = &MatrixAccessor::row_len_dense;\n- _val_i = &MatrixAccessor::val_dense_i;\n- } else {\n- _len = &MatrixAccessor::len_sparse;\n- _pos = &MatrixAccessor::pos_sparse;\n- _col_idxs = &MatrixAccessor::cols_sparse;\n- _val_rc = &MatrixAccessor::val_sparse_rc;\n- _vals = &MatrixAccessor::vals_sparse;\n- _row_len = &MatrixAccessor::row_len_sparse;\n- _val_i = &MatrixAccessor::val_sparse_i;\n- _set = &MatrixAccessor::set_sparse;\n- }\n- }\n+ __device__ MatrixAccessor(Matrix<T>* mat) : _mat(mat) {}\n+\n+ __device__ void init(Matrix<T>* mat) { _mat = mat; }\n__device__ uint32_t& nnz() { return _mat->nnz; }\n__device__ uint32_t cols() { return _mat->cols; }\n__device__ uint32_t rows() { return _mat->rows; }\n- __device__ uint32_t len() { return (this->*_len)(); }\n+ __device__ uint32_t len() { return _mat->data == nullptr ? len_sparse() : len_dense(); }\n__device__ uint32_t pos(uint32_t rix) {\n- return (this->*_pos)(rix);\n+ return _mat->data == nullptr ? pos_sparse(rix) : pos_dense(rix);\n}\n__device__ T& val(uint32_t r, uint32_t c) {\n- return (this->*_val_rc)(r, c);\n+ return _mat->data == nullptr ? val_sparse_rc(r, c) : val_dense_rc(r,c);\n}\n__device__ T& val(uint32_t i) {\n- return (this->*_val_i)(i);\n+ return _mat->data == nullptr ? val_sparse_i(i) : val_dense_i(i);\n}\n+ __device__ T& operator[](uint32_t i) { return val(i); }\n__device__ T* vals(uint32_t rix) {\n- return (this->*_vals)(rix);\n- }\n-\n- __device__ T& operator[](uint32_t i) {\n- return (this->*_val_i)(i);\n+ return _mat->data == nullptr ? vals_sparse(rix) : vals_dense(rix);\n}\n__device__ uint32_t row_len(uint32_t rix) {\n- return (this->*_row_len)(rix);\n+ return _mat->data == nullptr ? row_len_sparse(rix) : row_len_dense(rix);\n}\n- __device__ uint32_t* col_idxs(uint32_t rix) {\n- return (this->*_col_idxs)(rix);\n- }\n+ __device__ uint32_t* col_idxs(uint32_t rix) { return cols_sparse(rix); }\n- __device__ void set(uint32_t r, uint32_t c, T v) {\n- (this->*_set)(r,c,v);\n- }\n+ __device__ void set(uint32_t r, uint32_t c, T v) { set_sparse(r,c,v); }\n- __device__ uint32_t* indexes() {\n- return _mat->row_ptr;\n- }\n+ __device__ uint32_t* indexes() { return _mat->row_ptr; }\n- __device__ bool hasData() {\n- return _mat->data != nullptr;\n- }\n+ __device__ bool hasData() { return _mat->data != nullptr; }\nprivate:\n__device__ uint32_t len_dense() {\nreturn _mat->rows * _mat->cols;\n@@ -159,11 +115,6 @@ private:\nreturn _mat->cols * rix;\n}\n- __device__ uint32_t* cols_dense(uint32_t rix) {\n- printf(\"ERROR: no column indices array in a dense matrix! This will likely crash :-/\\n\");\n- return nullptr;\n- }\n-\n__device__ T& val_dense_rc(uint32_t r, uint32_t c) {\nreturn _mat->data[_mat->cols * r + c];\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/cuda/spoof-launcher/SpoofCellwise.h", "new_path": "src/main/cuda/spoof-launcher/SpoofCellwise.h", "diff": "@@ -133,7 +133,7 @@ struct SpoofCellwiseNoAgg {\n// num ctas\n// ToDo: adaptive VT\n- const uint32_t VT = 4;\n+ const uint32_t VT = 1;\nuint32_t NB = std::ceil((N + NT * VT - 1) / (NT * VT));\nif(sparse_input)\nNB = input.front().rows;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNodeCell.java", "new_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNodeCell.java", "diff": "@@ -158,7 +158,7 @@ public class CNodeCell extends CNodeTpl\nif(api == GeneratorAPI.CUDA) {\n// ToDo: initial_value is misused to pass VT (values per thread) to no_agg operator\nString agg_op = \"IdentityOp\";\n- String initial_value = \"(T)4.0\";\n+ String initial_value = \"(T)1.0\";\nif(_aggOp != null)\nswitch(_aggOp) {\ncase SUM:\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2930] Remove function pointers from SPOOF CUDA's MatrixAccessor class The use of function pointers to abstract dense and sparse matrices is a major performance bottleneck. Relying on a conditional if sparse/dense for now. Also sets values per thread to 1 in cellwise template (better performance).
49,693
14.04.2021 23:59:51
-7,200
f10eb03821dbc30bcec731b2cc93125ec39ea3ff
[MINOR] Reduce memory footprint of reduceALL GPU operation The temporary buffer needs to hold at most num_blocks (of first reduction wave) items of size <data-type>, not N (size of input).
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixCUDA.java", "new_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixCUDA.java", "diff": "@@ -933,10 +933,9 @@ public class LibMatrixCUDA {\nint[] tmp = getKernelParamsForReduceAll(gCtx, n);\nint blocks = tmp[0], threads = tmp[1], sharedMem = tmp[2];\n- Pointer tempOut = gCtx.allocate(instName, n*sizeOfDataType);\n+ Pointer tempOut = gCtx.allocate(instName, (long) blocks * sizeOfDataType);\ngetCudaKernels(gCtx).launchKernel(kernelFunction, new ExecutionConfig(blocks, threads, sharedMem), in, tempOut, n);\n- //cudaDeviceSynchronize;\nint s = blocks;\nwhile (s > 1) {\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Reduce memory footprint of reduceALL GPU operation The temporary buffer needs to hold at most num_blocks (of first reduction wave) items of size <data-type>, not N (size of input).
49,698
15.04.2021 04:50:18
-19,080
cd7772ae013255d6efa2de656fb4a01e1d3726f0
[MINOR] fix metadata for builtins-reference.md
[ { "change_type": "MODIFY", "old_path": "docs/_includes/header.html", "new_path": "docs/_includes/header.html", "diff": "@@ -46,6 +46,7 @@ limitations under the License.\n<li class=\"divider\"></li>\n<li><b>Language Guides:</b></li>\n<li><a href=\".{% if page.path contains 'site' %}/..{% endif %}/site/dml-language-reference.html\">DML Language Reference</a></li>\n+ <li><a href=\".{% if page.path contains 'site' %}/..{% endif %}/site/builtins-reference.html\">Built-in Functions Reference</a></li>\n<li class=\"divider\"></li>\n<li><b>ML Algorithms:</b></li>\n<li><a href=\".{% if page.path contains 'site' %}/..{% endif %}/site/algorithms-reference.html\">Algorithms Reference</a></li>\n" }, { "change_type": "MODIFY", "old_path": "docs/site/builtins-reference.md", "new_path": "docs/site/builtins-reference.md", "diff": "---\nlayout: site\n-title: Builtin Reference---\n+title: Builtin Functions Reference\n+---\n<!--\n{% comment %}\nLicensed to the Apache Software Foundation (ASF) under one or more\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] fix metadata for builtins-reference.md
49,720
15.04.2021 16:44:38
-7,200
8dcb720136d048b1fe7027c4b87254f1a948276e
[MINOR] Row-wise frame initialization support Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/DataGenCPInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/DataGenCPInstruction.java", "diff": "@@ -22,6 +22,7 @@ package org.apache.sysds.runtime.instructions.cp;\nimport java.util.Arrays;\nimport java.util.Random;\n+import org.apache.commons.lang3.ArrayUtils;\nimport org.apache.commons.lang3.tuple.Pair;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n@@ -353,15 +354,26 @@ public class DataGenCPInstruction extends UnaryCPInstruction {\n}\nelse {\nString[] data = frame_data.split(DataExpression.DELIM_NA_STRING_SEP);\n- if(data.length != schemaLength && data.length > 1)\n+ int rowLength = data.length/lrows;\n+ if(data.length != schemaLength && data.length > 1 && rowLength != schemaLength)\nthrow new DMLRuntimeException(\n\"data values should be equal to number of columns,\" + \" or a single values for all columns\");\nout = new FrameBlock(vt);\nFrameBlock outF = (FrameBlock) out;\n- if(data.length > 1) {\n+ if(data.length > 1 && rowLength != schemaLength) {\nfor(int i = 0; i < lrows; i++)\noutF.appendRow(data);\n}\n+ else if(data.length > 1 && rowLength == schemaLength)\n+ {\n+ int beg = 0;\n+ for(int i = 1; i <= lrows; i++) {\n+ int end = lcols * i;\n+ String[] data1 = ArrayUtils.subarray(data, beg, end);\n+ beg = end;\n+ outF.appendRow(data1);\n+ }\n+ }\nelse {\nString[] data1 = new String[lcols];\nArrays.fill(data1, frame_data);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/spark/RandSPInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/spark/RandSPInstruction.java", "diff": "@@ -27,6 +27,7 @@ import java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.Random;\n+import org.apache.commons.lang3.ArrayUtils;\nimport org.apache.commons.lang3.tuple.Pair;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n@@ -993,14 +994,26 @@ public class RandSPInstruction extends UnarySPInstruction {\n}\nelse {\nString[] data = _data.split(DataExpression.DELIM_NA_STRING_SEP);\n- if(data.length != _schema.length && data.length > 1)\n+ int rowLength = data.length/(int)_rlen;\n+ if(data.length != _schema.length && data.length > 1 && rowLength != _schema.length)\nthrow new DMLRuntimeException(\"data values should be equal \"\n+ \"to number of columns, or a single values for all columns\");\n- if(data.length > 1) {\n+ if(data.length > 1 && rowLength != _schema.length) {\nout = new FrameBlock(_schema);\nfor(int i = 0; i < lrlen; i++)\nout.appendRow(data);\n}\n+ else if(data.length > 1 && rowLength == _schema.length)\n+ {\n+ out = new FrameBlock(_schema);\n+ int beg = 0;\n+ for(int i = 1; i <= lrlen; i++) {\n+ int end = (int)_clen * i;\n+ String[] data1 = ArrayUtils.subarray(data, beg, end);\n+ beg = end;\n+ out.appendRow(data1);\n+ }\n+ }\nelse {\nout = new FrameBlock(_schema);\nString[] data1 = new String[(int)_clen];\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/frame/FrameConstructorTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/frame/FrameConstructorTest.java", "diff": "@@ -52,7 +52,8 @@ public class FrameConstructorTest extends AutomatedTestBase {\nNAMED,\nNO_SCHEMA,\nRANDOM_DATA,\n- SINGLE_DATA\n+ SINGLE_DATA,\n+ MULTI_ROW_DATA\n}\n@Override\n@@ -66,25 +67,25 @@ public class FrameConstructorTest extends AutomatedTestBase {\n@Test\npublic void testFrameNamedParam() {\n- FrameBlock exp = createExpectedFrame(schemaStrings1, false);\n+ FrameBlock exp = createExpectedFrame(schemaStrings1, rows,\"mixed\");\nrunFrameTest(TestType.NAMED, exp, Types.ExecMode.SINGLE_NODE);\n}\n@Test\npublic void testFrameNamedParamSP() {\n- FrameBlock exp = createExpectedFrame(schemaStrings1, false);\n+ FrameBlock exp = createExpectedFrame(schemaStrings1, rows,\"mixed\");\nrunFrameTest(TestType.NAMED, exp, Types.ExecMode.SPARK);\n}\n@Test\npublic void testNoSchema() {\n- FrameBlock exp = createExpectedFrame(schemaStrings2, false);\n+ FrameBlock exp = createExpectedFrame(schemaStrings2, rows,\"mixed\");\nrunFrameTest(TestType.NO_SCHEMA, exp, Types.ExecMode.SINGLE_NODE);\n}\n@Test\npublic void testNoSchemaSP() {\n- FrameBlock exp = createExpectedFrame(schemaStrings2, false);\n+ FrameBlock exp = createExpectedFrame(schemaStrings2, rows,\"mixed\");\nrunFrameTest(TestType.NO_SCHEMA, exp, Types.ExecMode.SPARK);\n}\n@@ -102,16 +103,28 @@ public class FrameConstructorTest extends AutomatedTestBase {\n@Test\npublic void testSingleData() {\n- FrameBlock exp = createExpectedFrame(schemaStrings1, true);\n+ FrameBlock exp = createExpectedFrame(schemaStrings1, rows,\"constant\");\nrunFrameTest(TestType.SINGLE_DATA, exp, Types.ExecMode.SINGLE_NODE);\n}\n@Test\npublic void testSingleDataSP() {\n- FrameBlock exp = createExpectedFrame(schemaStrings1, true);\n+ FrameBlock exp = createExpectedFrame(schemaStrings1, rows,\"constant\");\nrunFrameTest(TestType.SINGLE_DATA, exp, Types.ExecMode.SPARK);\n}\n+ @Test\n+ public void testMultiRowData() {\n+ FrameBlock exp = createExpectedFrame(schemaStrings1, 5,\"multi-row\");\n+ runFrameTest(TestType.MULTI_ROW_DATA, exp, Types.ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ public void testMultiRowDataSP() {\n+ FrameBlock exp = createExpectedFrame(schemaStrings1, 5,\"multi-row\");\n+ runFrameTest(TestType.MULTI_ROW_DATA, exp, Types.ExecMode.SPARK);\n+ }\n+\nprivate void runFrameTest(TestType type, FrameBlock expectedOutput, Types.ExecMode et) {\nTypes.ExecMode platformOld = setExecMode(et);\nboolean oldFlag = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n@@ -144,11 +157,20 @@ public class FrameConstructorTest extends AutomatedTestBase {\n}\n}\n- private static FrameBlock createExpectedFrame(ValueType[] schema, boolean constant) {\n+ private static FrameBlock createExpectedFrame(ValueType[] schema, int rows, String type) {\nFrameBlock exp = new FrameBlock(schema);\n- String[] out = constant ?\n- new String[]{\"1\", \"1\", \"1\", \"1\"} :\n- new String[]{\"1\", \"abc\", \"2.5\", \"TRUE\"};\n+ String[] out = null;\n+ if(type.equals(\"mixed\"))\n+ out = new String[]{\"1\", \"abc\", \"2.5\", \"TRUE\"};\n+ else if(type.equals(\"constant\"))\n+ out = new String[]{\"1\", \"1\", \"1\", \"1\"};\n+ else if (type.equals(\"multi-row\")) //multi-row data\n+ out = new String[]{\"1\", \"abc\", \"2.5\", \"TRUE\"};\n+ else {\n+ System.out.println(\"invalid test type\");\n+ System.exit(1);\n+ }\n+\nfor(int i=0; i<rows; i++)\nexp.appendRow(out);\nreturn exp;\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/frame/FrameConstructorTest.dml", "new_path": "src/test/scripts/functions/frame/FrameConstructorTest.dml", "diff": "@@ -28,6 +28,9 @@ if($1 == \"RANDOM_DATA\")\nf1 = frame(\"\", rows=40, cols=4, schema=[\"INT64\", \"STRING\", \"FP64\", \"BOOLEAN\"]) # no data\nif($1 == \"SINGLE_DATA\")\nf1 = frame(1, rows=40, cols=4, schema=[\"INT64\", \"STRING\", \"FP64\", \"BOOLEAN\"]) # no data\n+if($1 == \"MULTI_ROW_DATA\")\n+ f1 = frame(data=[\"1\", \"abc\", \"2.5\", \"TRUE\", \"1\", \"abc\", \"2.5\", \"TRUE\", \"1\", \"abc\", \"2.5\", \"TRUE\", \"1\", \"abc\", \"2.5\", \"TRUE\",\n+ \"1\", \"abc\", \"2.5\", \"TRUE\" ], rows=5, cols=4, schema=[\"INT64\", \"STRING\", \"FP64\", \"BOOLEAN\"]) # initialization by row\n# f1 = frame(1, 4, 3) # unnamed parameters not working\nwrite(f1, $2, format=\"csv\")\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Row-wise frame initialization support Closes #1228.
49,706
15.04.2021 10:09:33
-7,200
c83d1ab6a7cd29dbbb907bb869b0a59e8a3570bb
[MINOR] Convert Component Test spark retry This commit tries to retry the spark creation and set random ports for the unstable component tests. Closes
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/component/convert/RDDConverterUtilsExtTest.java", "new_path": "src/test/java/org/apache/sysds/test/component/convert/RDDConverterUtilsExtTest.java", "diff": "@@ -59,7 +59,12 @@ public class RDDConverterUtilsExtTest extends AutomatedTestBase {\npublic static void setUpClass() {\nif (conf == null)\nconf = SparkExecutionContext.createSystemDSSparkConf().setAppName(\"RDDConverterUtilsExtTest\")\n- .setMaster(\"local\");\n+ .set(\"spark.port.maxRetries\", \"100\")\n+ .setMaster(\"local\")\n+ .set(\"spark.driver.bindAddress\", \"127.0.0.1\")\n+ .set(\"SPARK_MASTER_PORT\", \"0\")\n+ .set(\"SPARK_WORKER_PORT\", \"0\");\n+\nif (sc == null)\nsc = new JavaSparkContext(conf);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Convert Component Test spark retry This commit tries to retry the spark creation and set random ports for the unstable component tests. Closes #1226
49,693
17.04.2021 00:42:53
-7,200
79011098016d5f35259edd2b204c313f1cd852c5
[MINOR][BUGFIX] Correctly counting device to host transfers if dense pointer was cleared along the way
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUObject.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUObject.java", "diff": "@@ -935,7 +935,9 @@ public class GPUObject {\nmat.release();\nreturn;\n}\n-\n+ boolean sparse = false;\n+ if(isDensePointerNull())\n+ sparse = true;\nMatrixBlock tmp = null;\nlong start = DMLScript.STATISTICS ? System.nanoTime() : 0;\nif (!isDensePointerNull()) {\n@@ -965,7 +967,7 @@ public class GPUObject {\nif (DMLScript.STATISTICS && !isEviction) {\n// Eviction time measure in malloc\nlong totalTime = System.nanoTime() - start;\n- int count = !isDensePointerNull() ? 1 : 3;\n+ int count = sparse ? 3 : 1;\nGPUStatistics.cudaFromDevTime.add(totalTime);\nGPUStatistics.cudaFromDevCount.add(count);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR][BUGFIX] Correctly counting device to host transfers if dense pointer was cleared along the way
49,698
15.04.2021 08:49:05
-19,080
1c210b8776fbf452a2e7496b0b81b214a106670b
[DOC] Add commit description guide * the philosophy behind the commit * tyes of commits with examples * commit tags used in the repository Closes
[ { "change_type": "MODIFY", "old_path": "CONTRIBUTING.md", "new_path": "CONTRIBUTING.md", "diff": "@@ -17,19 +17,17 @@ limitations under the License.\n{% end comment %}\n-->\n-# Contributing to SystemDS\n+# Contribution Guidelines and Standards for `SystemDS`\n-Thanks for taking the time to contribute to SystemDS!\n+Thank you for contributing to SystemDS. :smile:\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-### Contribution Guidelines and Standards\n+> The following are mostly guidelines, not rules. Use your best judgement, and\n+> feel free to propose changes to this doc.\nBefore contributing a pull request for [review](https://github.com/apache/systemds/pulls),\nlet's make sure the changes are consistent with the guidelines and coding style.\n-#### General Guidelines and Philosophy for contribution\n+## General Guidelines and Philosophy for contribution\n* Inclusion of unit tests when contributing new features, will help\n1. prove that the code works correctly, and\n@@ -37,24 +35,184 @@ let's make sure the changes are consistent with the guidelines and coding style.\n* Formatting changes can be handled in a separate PR.\nExample [`bf4ba16b`](https://github.com/apache/systemds/commit/bf4ba16b9aaa9afee20a3f1c03b0ff49c5346a9d)\n* New features (e.g., a new cutting edge machine learning algorithm) typically will\n- live in [scripts/staging](./scripts/staging) or its equivalent folder for specific\n+ live in [`scripts/staging`](./scripts/staging) or its equivalent folder for specific\nfeature to get some airtime and sufficient testing before a decision is made regarding\nwhether they are to migrated to the top-level.\n* When a new contribution is made to SystemDS, the maintenance burden is (by default)\ntransferred to the SystemDS team. The benefit of the contribution is to be compared\nagainst the cost of maintaining the feature.\n-#### Code Style\n+## Code Style\n-Before contributing a pull request, we highly suggest applying a code formatter to the written code.\n+We suggest applying a code formatter to the written code. Generally, this is done automatically.\n-We have provided at profile for java located in [Codestyle File ./docs/CodeStyle.eclipse.xml](dev/CodeStyle_eclipse.xml). This can be loaded in most editors e.g.:\n+We have provided at profile for java located in [Codestyle File `./docs/CodeStyle.eclipse.xml`](dev/CodeStyle_eclipse.xml). This can be loaded in most editors e.g.:\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-#### License\n+## Commit Style\n+\n+SystemDS project has linear history throughout. Rebase cleanly and verify that the commit-SHA's\n+of the Apache Repo are not altered.\n+A general guideline is never to change a commit inside the systemds official repo, which is\n+the standard practice. If you have accidentally committed a functionality or tag, let others know.\n+And create a new commit to revert the functionality of the previous commit but **do not force push**.\n+\n+\n+### Tags\n+\n+The tags can be used in combination to one another. These are the only tags available.\n+\n+* `[MINOR]`: Small changesets with additional functionality\n+\n+ > Examples:\n+ >\n+ > This commit makes small software updates with refactoring\n+ >\n+ > [`030fdab3`](https://github.com/apache/systemds/commit/030fdab3ebe6dedc3b4bb860e0ec5acfd9c38e5d) - `[MINOR] Added package to R dependency; updated Docker test image`\n+ >\n+ > This commit cleans up the redundant code for simplification\n+ >\n+ > [`f4fa5650`](https://github.com/apache/systemds/commit/f4fa565013de13270df05dd37610382ca80f7354) - `[MINOR][SYSTEMDS-43] Cleanup scale builtin function (readability)`\n+ >\n+\n+* `[SYSTEMDS-#]`: A changeset which will a specific purpose such as a bug, Improvement,\n+ New feature, etc. The tag value is found from [SystemDS jira issue tracker](https://issues.apache.org/jira/projects/SYSTEMDS/issues).\n+\n+* `[DOC]` also `[DOCS]`: Changes to the documentation\n+\n+* `[HOTFIX]`: Introduces changes into the already released versions.\n+\n+ > Example:\n+ >\n+ > This commit fixes the corrupted language path\n+ >\n+ > [`87bc3584`](https://github.com/apache/systemds/commit/87bc3584db2148cf78b2d46418639e88ca27ec64) - `[HOTFIX] Fix validation of scalar-scalar binary min/max operations`\n+ >\n+\n+### Commit description\n+\n+> A commit or PR description is a public record of **what** change is being made and **why**.\n+\n+#### Structure of the description\n+\n+##### First Line\n+\n+1. A summary of what the changeset.\n+2. A complete sentence, crafted as though it was an order.\n+ - an imperative sentence\n+ - Writing the rest of the description as an imperative is optional.\n+3. Follow by an empty line.\n+\n+##### Body\n+\n+It consists of the following.\n+\n+1. A brief description of the problem solved.\n+2. Why this is the best approach?.\n+3. Shortcomings to the approach, if any (important!).\n+\n+Additional info\n+\n+4. background information\n+ - bug/issue/jira numbers\n+ - benchmark/test results\n+ - links to design documents\n+ - code attributions\n+5. Include enough context for\n+ - reviewers\n+ - future readers to understand the Changes.\n+6. Add PR number, like `Closes #1000`.\n+\n+The following is a commit description with all the points mentioned.\n+\n+[`1abe9cb`](https://github.com/apache/systemds/commit/1abe9cb79d8001992f1c79ba5e638e6b423a1382)\n+\n+Commit message:\n+```txt\n+[SYSTEMDS-418] Performance improvements lineage reuse probing/spilling\n+\n+This patch makes some minor performance improvements to the lineage\n+reuse probing and cache put operations. Specifically, we now avoid\n+unnecessary lineage hashing and comparisons by using lists instead of\n+hash maps, move the time computations into the reuse path (to not affect\n+the code path without lineage reuse), avoid unnecessary branching, and\n+materialize the score of cache entries to avoid repeated computation\n+for the log N comparisons per add/remove/constaints operation.\n+For 100K iterations and ~40 ops per iteration, lineage tracing w/ reuse\n+improved from 41.9s to 38.8s (pure lineage tracing: 27.9s).\n+```\n+\n+#### Good commit description\n+\n+The following are some of the types of code changes with examples.\n+\n+##### Functionality change\n+\n+[`1101533`](https://github.com/apache/systemds/commit/1101533fd1b2be4e475a18052dbb4bc930bb05d9)\n+\n+Commit message:\n+```txt\n+[SYSTEMDS-2603] New hybrid approach for lineage deduplication\n+\n+This patch makes a major refactoring of the lineage deduplication\n+framework. This changes the design of tracing all the\n+distinct paths in a loop-body before the first iteration, to trace\n+during execution. The number of distinct paths grows exponentially\n+with the number of control flow statements. Tracing all the paths\n+in advance can be a huge waste and overhead.\n+We now trace an iteration during execution. We count the number of\n+distinct paths before the iterations start, and we stop tracing\n+once all the paths are traced. Tracing during execution fits\n+very well with our multi-level reuse infrastructure.\n+Refer to JIRA for detailed discussions.\n+```\n+\n+\n+##### Refactoring\n+\n+> Refactoring is a series of behaviour preserving changes with restructuring to\n+> existing code body. Refactoring does not alter the external behaviour or the\n+> output of a function, but the internal changes to the function to keep the code\n+> more organized, readable or to accomodate a more complex functionality.\n+\n+\n+[`e581b5a`](https://github.com/apache/systemds/commit/e581b5a6248b56a70e18ffe6ba699e8142a2d679)\n+\n+Commit message:\n+```txt\n+[SYSTEMDS-2575] Fix eval function calls (incorrect pinning of inputs)\n+\n+This patch fixes an issue of indirect eval function calls where wrong\n+input variable names led to missing pinning of inputs and thus too eager\n+cleanup of these variables (which causes crashes if the inputs are used\n+in other operations of the eval call).\n+The fix is simple. We avoid such inconsistent construction and\n+invocation of fcall instructions by using a narrower interface and\n+constructing the materialized names internally in the fcall.\n+```\n+\n+##### Small Changeset still needs some context.\n+\n+[`7af2ae0`](https://github.com/apache/systemds/commit/7af2ae04f28ddcb36158719a25a7fa34b22d3266)\n+\n+Commit message:\n+```txt\n+[MINOR] Update docker images organization\n+\n+Changes the docker images to use the docker organization systemds\n+add install dependency for R dbScan\n+Change the tests to use the new organizations docker images\n+\n+Closes #1008\n+```\n+\n+> Protip: to reference other commits use first 7 letters of the commit SHA-1.\n+> eg. `1b81d8c` for referencing `1b81d8cb19d8da6d865b7fca5a095dd5fec8d209`\n+\n+## License\nIncluding a license at the top of new files helps validate the consistency of license.\n@@ -66,8 +224,8 @@ Examples:\n- [Bash](./src/main/bash/sparkDML2.sh#L2-L21)\n- [XML/HTML](./src/assembly/bin.xml#L2-L19)\n- [dml/R](./scripts/algorithms/ALS-CG.dml#L1-L20)\n-- [Makefile/.proto](./src/main/cpp/kernels/Makefile#L1-L18)\n-- Markdown - refer to the top of this file!\n+- [Makefile/.proto](./src/main/python/docs/Makefile#L1-L20)\n+- Markdown - refer to the top of this file in raw format.\n___\n" } ]
Java
Apache License 2.0
apache/systemds
[DOC] Add commit description guide * the philosophy behind the commit * tyes of commits with examples * commit tags used in the repository Closes #1231.
49,706
21.04.2021 10:08:03
-7,200
18b705bb3a6bf7e19188163f1d73e0ee32d491a4
[MINOR] Surefire update to version 3.0.0-M5 This update is done because some tests sometimes crash with "The forked VM terminated without properly saying goodbye". This update seems to resolve this issue.
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<plugin> <!-- unit tests -->\n<groupId>org.apache.maven.plugins</groupId>\n<artifactId>maven-surefire-plugin</artifactId>\n- <version>3.0.0-M4</version><!--$NO-MVN-MAN-VER$ -->\n+ <version>3.0.0-M5</version>\n<configuration>\n<skipTests>${maven.test.skip}</skipTests>\n<parallel>classes</parallel>\n- <!-- <useUnlimitedThreads>true</useUnlimitedThreads> -->\n<threadCount>12</threadCount>\n<!-- 1C means the number of threads times 1 possible maximum forks for testing-->\n<forkCount>1C</forkCount>\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Surefire update to version 3.0.0-M5 This update is done because some tests sometimes crash with "The forked VM terminated without properly saying goodbye". This update seems to resolve this issue.
49,698
20.04.2021 21:26:31
-19,080
728e009985a576929cc0bea1b3f01fec6b696664
Add .asf.yaml to control Github settings * Updates the GitHub project metadata - description, labels * Disables merge commit option, according to our commit style guide at CONTRIBUTING.md * .asf.yaml file provides expressive syntax to configure fine grained settings for hosting asf-site Closes
[ { "change_type": "ADD", "old_path": null, "new_path": ".asf.yaml", "diff": "+#-------------------------------------------------------------\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+# Document for .asf.yml file is available at\n+# https://cwiki.apache.org/confluence/display/INFRA/Git+-+.asf.yaml+features\n+\n+github:\n+ description: \"Apache SystemDS - A versatile system for the end-to-end data science lifecycle\"\n+ homepage: https://systemds.apache.org/\n+ labels:\n+ - systemds\n+ - java\n+ - dml\n+\n+ features:\n+ # Enable issues management\n+ issues: false\n+ # Enable projects for project management boards\n+ projects: false\n+ # Enable wiki for documentation\n+ wiki: false\n+\n+ # Choose the type of commit merge in the PR UI\n+ enabled_merge_buttons:\n+ # Enable squash button\n+ squash: true\n+ # Enable merge button\n+ merge: false\n+ # Enable rebase button\n+ rebase: true\n+\n+\n+ protected_branches:\n+ master:\n+ # Do not allow merge commits\n+ # by allowing linear history\n+ required_linear_history: true\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2910] Add .asf.yaml to control Github settings * Updates the GitHub project metadata - description, labels * Disables merge commit option, according to our commit style guide at CONTRIBUTING.md * .asf.yaml file provides expressive syntax to configure fine grained settings for hosting asf-site Closes #1233.
49,722
30.01.2021 16:00:47
-3,600
42f3b1594bba4f4f49316c9866912bb978e6dd8d
Federated ctable instruction Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/CtableFEDInstruction.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.apache.sysds.runtime.instructions.fed;\n+\n+import java.util.Arrays;\n+import java.util.Collections;\n+import java.util.concurrent.Future;\n+import java.util.stream.IntStream;\n+\n+import org.apache.commons.lang3.tuple.Pair;\n+import org.apache.sysds.common.Types.DataType;\n+import org.apache.sysds.common.Types.ValueType;\n+import org.apache.sysds.lops.Lop;\n+import org.apache.sysds.runtime.DMLRuntimeException;\n+import org.apache.sysds.runtime.controlprogram.caching.MatrixObject;\n+import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\n+import org.apache.sysds.runtime.controlprogram.federated.FederatedRange;\n+import org.apache.sysds.runtime.controlprogram.federated.FederatedRequest;\n+import org.apache.sysds.runtime.controlprogram.federated.FederatedResponse;\n+import org.apache.sysds.runtime.controlprogram.federated.FederatedUDF;\n+import org.apache.sysds.runtime.controlprogram.federated.FederationMap;\n+import org.apache.sysds.runtime.controlprogram.federated.FederationUtils;\n+import org.apache.sysds.runtime.functionobjects.And;\n+import org.apache.sysds.runtime.instructions.Instruction;\n+import org.apache.sysds.runtime.instructions.InstructionUtils;\n+import org.apache.sysds.runtime.instructions.cp.CPOperand;\n+import org.apache.sysds.runtime.instructions.cp.Data;\n+import org.apache.sysds.runtime.instructions.cp.ScalarObject;\n+import org.apache.sysds.runtime.lineage.LineageItem;\n+import org.apache.sysds.runtime.matrix.data.MatrixBlock;\n+import org.apache.sysds.runtime.matrix.operators.BinaryOperator;\n+\n+public class CtableFEDInstruction extends ComputationFEDInstruction {\n+ private final CPOperand _outDim1;\n+ private final CPOperand _outDim2;\n+ private final boolean _isExpand;\n+ private final boolean _ignoreZeros;\n+\n+ private CtableFEDInstruction(CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out, String outputDim1, boolean dim1Literal, String outputDim2, boolean dim2Literal, boolean isExpand,\n+ boolean ignoreZeros, String opcode, String istr) {\n+ super(FEDType.Ctable, null, in1, in2, in3, out, opcode, istr);\n+ _outDim1 = new CPOperand(outputDim1, ValueType.FP64, DataType.SCALAR, dim1Literal);\n+ _outDim2 = new CPOperand(outputDim2, ValueType.FP64, DataType.SCALAR, dim2Literal);\n+ _isExpand = isExpand;\n+ _ignoreZeros = ignoreZeros;\n+ }\n+\n+ public static CtableFEDInstruction parseInstruction(String inst) {\n+ String[] parts = InstructionUtils.getInstructionPartsWithValueType(inst);\n+ InstructionUtils.checkNumFields(parts, 7);\n+\n+ String opcode = parts[0];\n+\n+ //handle opcode\n+ if(!(opcode.equalsIgnoreCase(\"ctable\"))) {\n+ throw new DMLRuntimeException(\"Unexpected opcode in CtableFEDInstruction: \" + inst);\n+ }\n+\n+ //handle operands\n+ CPOperand in1 = new CPOperand(parts[1]);\n+ CPOperand in2 = new CPOperand(parts[2]);\n+ CPOperand in3 = new CPOperand(parts[3]);\n+\n+ //handle known dimension information\n+ String[] dim1Fields = parts[4].split(Instruction.LITERAL_PREFIX);\n+ String[] dim2Fields = parts[5].split(Instruction.LITERAL_PREFIX);\n+\n+ CPOperand out = new CPOperand(parts[6]);\n+ boolean ignoreZeros = Boolean.parseBoolean(parts[7]);\n+\n+ // ctable does not require any operator, so we simply pass-in a dummy operator with null functionobject\n+ return new CtableFEDInstruction(in1,\n+ in2, in3, out, dim1Fields[0], Boolean.parseBoolean(dim1Fields[1]),\n+ dim2Fields[0], Boolean.parseBoolean(dim2Fields[1]), false, ignoreZeros, opcode, inst);\n+ }\n+\n+ @Override\n+ public void processInstruction(ExecutionContext ec) {\n+ MatrixObject mo1 = ec.getMatrixObject(input1);\n+ MatrixObject mo2 = ec.getMatrixObject(input2);\n+\n+ boolean reversed = false;\n+ if(!mo1.isFederated() && mo2.isFederated()) {\n+ mo1 = ec.getMatrixObject(input2);\n+ mo2 = ec.getMatrixObject(input1);\n+ reversed = true;\n+ }\n+\n+ // get new output dims\n+ Long[] dims1 = getOutputDimension(mo1, input1, _outDim1, mo1.getFedMapping().getFederatedRanges());\n+ Long[] dims2 = getOutputDimension(mo2, input2, _outDim2, mo1.getFedMapping().getFederatedRanges());\n+\n+ MatrixObject mo3 = input3 != null && input3.isMatrix() ? ec.getMatrixObject(input3) : null;\n+\n+ boolean reversedWeights = mo3 != null && mo3.isFederated() && !(mo1.isFederated() || mo2.isFederated());\n+ if(reversedWeights) {\n+ mo3 = mo1;\n+ mo1 = ec.getMatrixObject(input3);\n+ }\n+\n+ long dim1 = Collections.max(Arrays.asList(dims1), Long::compare);\n+ boolean fedOutput = dim1 % mo1.getFedMapping().getSize() == 0 && dims1.length == Arrays.stream(dims1).distinct().count();\n+\n+ processRequest(ec, mo1, mo2, mo3, reversed, reversedWeights, fedOutput, dims1, dims2);\n+ }\n+\n+ private void processRequest(ExecutionContext ec, MatrixObject mo1, MatrixObject mo2, MatrixObject mo3,\n+ boolean reversed, boolean reversedWeights, boolean fedOutput, Long[] dims1, Long[] dims2) {\n+ Future<FederatedResponse>[] ffr;\n+\n+ FederatedRequest[] fr1 = mo1.getFedMapping().broadcastSliced(mo2, false);\n+ FederatedRequest fr2, fr3;\n+ if(mo3 == null) {\n+ if(!reversed)\n+ fr2 = FederationUtils.callInstruction(instString, output, new CPOperand[] {input1, input2},\n+ new long[] {mo1.getFedMapping().getID(), fr1[0].getID()});\n+ else\n+ fr2 = FederationUtils.callInstruction(instString, output, new CPOperand[] {input1, input2},\n+ new long[] {fr1[0].getID(), mo1.getFedMapping().getID()});\n+\n+ fr3 = new FederatedRequest(FederatedRequest.RequestType.GET_VAR, fr2.getID());\n+ FederatedRequest fr4 = mo1.getFedMapping().cleanup(getTID(), fr1[0].getID());\n+ ffr = mo1.getFedMapping().execute(getTID(), true, fr1, fr2, fr3, fr4);\n+\n+ } else {\n+ FederatedRequest[] fr4 = mo1.getFedMapping().broadcastSliced(mo3, false);\n+ if(!reversed && !reversedWeights)\n+ fr2 = FederationUtils.callInstruction(instString, output, new CPOperand[] {input1, input2, input3},\n+ new long[] {mo1.getFedMapping().getID(), fr1[0].getID(), fr4[0].getID()});\n+ else if(reversed && !reversedWeights)\n+ fr2 = FederationUtils.callInstruction(instString, output, new CPOperand[] {input1, input2, input3},\n+ new long[] {fr1[0].getID(), mo1.getFedMapping().getID(), fr4[0].getID()});\n+ else\n+ fr2 = FederationUtils.callInstruction(instString, output, new CPOperand[] {input1, input2, input3},\n+ new long[] {fr1[0].getID(), fr4[0].getID(), mo1.getFedMapping().getID()});\n+\n+ fr3 = new FederatedRequest(FederatedRequest.RequestType.GET_VAR, fr2.getID());\n+ FederatedRequest fr5 = mo1.getFedMapping().cleanup(getTID(), fr1[0].getID(), fr4[0].getID());\n+ ffr = mo1.getFedMapping().execute(getTID(), true, fr1, fr4, fr2, fr3, fr5);\n+ }\n+\n+ if(fedOutput && isFedOutput(ffr, dims1)) {\n+ MatrixObject out = ec.getMatrixObject(output);\n+ FederationMap newFedMap = modifyFedRanges(mo1.getFedMapping(), dims1, dims2);\n+ setFedOutput(mo1, out, newFedMap, dims1, fr2.getID());\n+ } else {\n+ ec.setMatrixOutput(output.getName(), aggResult(ffr));\n+ }\n+ }\n+\n+ boolean isFedOutput(Future<FederatedResponse>[] ffr, Long[] dims1) {\n+ boolean fedOutput = true;\n+\n+ long fedSize = Collections.max(Arrays.asList(dims1), Long::compare) / ffr.length;\n+ try {\n+ MatrixBlock curr;\n+ MatrixBlock prev =(MatrixBlock) ffr[0].get().getData()[0];\n+ for(int i = 1; i < ffr.length && fedOutput; i++) {\n+ curr = (MatrixBlock) ffr[i].get().getData()[0];\n+ MatrixBlock sliced = curr.slice((int) (curr.getNumRows() - fedSize), curr.getNumRows() - 1);\n+\n+ // no intersection\n+ if(curr.getNumRows() == (i+1) * prev.getNumRows() && curr.getNonZeros() <= prev.getLength()\n+ && (curr.getNumRows() - sliced.getNumRows()) == i * prev.getNumRows()\n+ && curr.getNonZeros() - sliced.getNonZeros() == 0)\n+ continue;\n+\n+ // check intersect with AND and compare number of nnz\n+ MatrixBlock prevExtend = new MatrixBlock(curr.getNumRows(), curr.getNumColumns(), 0.0);\n+ prevExtend.copy(0, prev.getNumRows()-1, 0, prev.getNumColumns()-1, prev, true);\n+\n+ MatrixBlock intersect = curr.binaryOperationsInPlace(new BinaryOperator(And.getAndFnObject()), prevExtend);\n+ if(intersect.getNonZeros() != 0)\n+ fedOutput = false;\n+ prev = sliced;\n+ }\n+ }\n+ catch(Exception e) {\n+ e.printStackTrace();\n+ }\n+ return fedOutput;\n+ }\n+\n+\n+ private void setFedOutput(MatrixObject mo1, MatrixObject out, FederationMap fedMap, Long[] dims1, long outId) {\n+ long fedSize = Collections.max(Arrays.asList(dims1), Long::compare) / dims1.length;\n+\n+ long d1 = Collections.max(Arrays.asList(dims1), Long::compare);\n+ long d2 = Collections.max(Arrays.asList(dims1), Long::compare);\n+\n+ // set output\n+ out.getDataCharacteristics().set(d1, d2, (int) mo1.getBlocksize(), mo1.getNnz());\n+ out.setFedMapping(fedMap.copyWithNewID(outId));\n+\n+ long varID = FederationUtils.getNextFedDataID();\n+ out.getFedMapping().mapParallel(varID, (range, data) -> {\n+ try {\n+ FederatedResponse response = data.executeFederatedOperation(new FederatedRequest(\n+ FederatedRequest.RequestType.EXEC_UDF, -1,\n+ new SliceOutput(data.getVarID(), fedSize))).get();\n+ if(!response.isSuccessful())\n+ response.throwExceptionFromResponse();\n+ }\n+ catch(Exception e) {\n+ throw new DMLRuntimeException(e);\n+ }\n+ return null;\n+ });\n+ }\n+\n+ private MatrixBlock aggResult(Future<FederatedResponse>[] ffr) {\n+ MatrixBlock resultBlock = new MatrixBlock(1, 1, 0);\n+ int dim1 = 0, dim2 = 0;\n+ for(int i = 0; i < ffr.length; i++) {\n+ try {\n+ MatrixBlock mb = ((MatrixBlock) ffr[i].get().getData()[0]);\n+ dim1 = mb.getNumRows() > dim1 ? mb.getNumRows() : dim1;\n+ dim2 = mb.getNumColumns() > dim2 ? mb.getNumColumns() : dim2;\n+\n+ // set next and prev to same output dimensions\n+ MatrixBlock prev = new MatrixBlock(dim1, dim2, 0.0);\n+ prev.copy(0, resultBlock.getNumRows()-1, 0, resultBlock.getNumColumns()-1, resultBlock, true);\n+\n+ MatrixBlock next = new MatrixBlock(dim1, dim2, 0.0);\n+ next.copy(0, mb.getNumRows()-1, 0, mb.getNumColumns()-1, mb, true);\n+\n+ // add worker results\n+ BinaryOperator plus = InstructionUtils.parseBinaryOperator(\"+\");\n+ resultBlock = prev.binaryOperationsInPlace(plus, next);\n+ }\n+ catch(Exception e) {\n+ e.printStackTrace();\n+ }\n+ }\n+ return resultBlock;\n+ }\n+\n+ private FederationMap modifyFedRanges(FederationMap fedMap, Long[] dims1, Long[] dims2) {\n+ IntStream.range(0, fedMap.getFederatedRanges().length).forEach(i -> {\n+ fedMap.getFederatedRanges()[i]\n+ .setBeginDim(0, i == 0 ? 0 : fedMap.getFederatedRanges()[i - 1].getEndDims()[0]);\n+ fedMap.getFederatedRanges()[i].setEndDim(0, dims1[i]);\n+ fedMap.getFederatedRanges()[i]\n+ .setBeginDim(1, i == 0 ? 0 : fedMap.getFederatedRanges()[i - 1].getBeginDims()[1]);\n+ fedMap.getFederatedRanges()[i].setEndDim(1, dims2[i]);\n+ });\n+ return fedMap;\n+ }\n+\n+ private Long[] getOutputDimension(MatrixObject in, CPOperand inOp, CPOperand outOp, FederatedRange[] federatedRanges) {\n+ Long[] fedDims = new Long[federatedRanges.length];\n+\n+ if(!in.isFederated()) {\n+ //slice\n+ MatrixBlock mb = in.acquireReadAndRelease();\n+ IntStream.range(0, federatedRanges.length).forEach(i -> {\n+ MatrixBlock sliced = mb\n+ .slice(federatedRanges[i].getBeginDimsInt()[0], federatedRanges[i].getEndDimsInt()[0] - 1);\n+ fedDims[i] = (long) sliced.max();\n+ });\n+ return fedDims;\n+ }\n+\n+ String maxInstString = constructMaxInstString(inOp.getName(), outOp.getName());\n+\n+ // get max per worker\n+ FederationMap map = in.getFedMapping();\n+ FederatedRequest fr1 = FederationUtils.callInstruction(maxInstString, outOp,\n+ new CPOperand[]{inOp}, new long[]{in.getFedMapping().getID()});\n+ FederatedRequest fr2 = new FederatedRequest(FederatedRequest.RequestType.GET_VAR, fr1.getID());\n+ FederatedRequest fr3 = map.cleanup(getTID(), fr1.getID());\n+ Future<FederatedResponse>[] tmp = map.execute(getTID(), fr1, fr2, fr3);\n+\n+ return computeOutputDims(tmp);\n+ }\n+\n+ private Long[] computeOutputDims(Future<FederatedResponse>[] tmp) {\n+ Long[] fedDims = new Long[tmp.length];\n+ for(int i = 0; i < tmp.length; i ++)\n+ try {\n+ fedDims[i] = ((ScalarObject) tmp[i].get().getData()[0]).getLongValue();\n+ }\n+ catch(Exception e) {\n+ e.printStackTrace();\n+ }\n+ return fedDims;\n+ }\n+\n+ private String constructMaxInstString(String in, String out) {\n+ String maxInstrString = instString.replace(\"ctable\", \"uamax\");\n+ String[] instParts = maxInstrString.split(Lop.OPERAND_DELIMITOR);\n+ String[] maxInstParts = new String[] {instParts[0], instParts[1],\n+ InstructionUtils.concatOperandParts(in, DataType.MATRIX.name(), (ValueType.FP64).name()),\n+ InstructionUtils.concatOperandParts(out, DataType.SCALAR.name(), (ValueType.FP64).name()), \"16\"};\n+ return String.join(Lop.OPERAND_DELIMITOR, maxInstParts);\n+ }\n+\n+ private static class SliceOutput extends FederatedUDF {\n+\n+ private static final long serialVersionUID = -2808597461054603816L;\n+ private final long _fedSize;\n+\n+ protected SliceOutput(long input, long fedSize) {\n+ super(new long[] {input});\n+ _fedSize = fedSize;\n+ }\n+\n+ public FederatedResponse execute(ExecutionContext ec, Data... data) {\n+ MatrixObject mo = (MatrixObject) data[0];\n+ MatrixBlock mb = mo.acquireReadAndRelease();\n+\n+ MatrixBlock sliced = mb.slice((int) (mb.getNumRows()-_fedSize), mb.getNumRows()-1);\n+ mo.acquireModify(sliced);\n+ mo.release();\n+\n+ return new FederatedResponse(FederatedResponse.ResponseType.SUCCESS, new Object[] {});\n+ }\n+ @Override\n+ public Pair<String, LineageItem> getLineageItem(ExecutionContext ec) {\n+ return null;\n+ }\n+ }\n+}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstruction.java", "diff": "@@ -32,6 +32,7 @@ public abstract class FEDInstruction extends Instruction {\nAggregateTernary,\nAppend,\nBinary,\n+ Ctable,\nCumulativeAggregate,\nInit,\nMultiReturnParameterizedBuiltin,\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "diff": "@@ -31,6 +31,7 @@ import org.apache.sysds.runtime.instructions.cp.AggregateBinaryCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.AggregateTernaryCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.AggregateUnaryCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.BinaryCPInstruction;\n+import org.apache.sysds.runtime.instructions.cp.CtableCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.Data;\nimport org.apache.sysds.runtime.instructions.cp.IndexingCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.MMChainCPInstruction;\n@@ -223,6 +224,14 @@ public class FEDInstructionUtils {\nif(instruction.getOperatorClass().getSuperclass() == SpoofCellwise.class && instruction.isFederated(ec))\nfedinst = SpoofFEDInstruction.parseInstruction(instruction.getInstructionString());\n}\n+ else if(inst instanceof CtableCPInstruction) {\n+ CtableCPInstruction cinst = (CtableCPInstruction) inst;\n+ if(inst.getOpcode().equalsIgnoreCase(\"ctable\")\n+ && ( ec.getCacheableData(cinst.input1).isFederated(FType.ROW)\n+ || (cinst.input2.isMatrix() && ec.getCacheableData(cinst.input2).isFederated(FType.ROW))\n+ || (cinst.input3.isMatrix() && ec.getCacheableData(cinst.input3).isFederated(FType.ROW))))\n+ fedinst = CtableFEDInstruction.parseInstruction(cinst.getInstructionString());\n+ }\n//set thread id for federated context management\nif( fedinst != null ) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/federated/algorithms/FederatedCorTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/federated/algorithms/FederatedCorTest.java", "diff": "@@ -107,10 +107,6 @@ public class FederatedCorTest extends AutomatedTestBase {\nThread t3 = startLocalFedWorkerThread(port3, FED_WORKER_WAIT_S);\nThread t4 = startLocalFedWorkerThread(port4);\n- rtplatform = execMode;\n- if(rtplatform == ExecMode.SPARK)\n- DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n-\nTestConfiguration config = availableTestConfigurations.get(TEST_NAME);\nloadTestConfiguration(config);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedCtableTest.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.apache.sysds.test.functions.federated.primitives;\n+\n+import java.util.Arrays;\n+import java.util.Collection;\n+\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.runtime.meta.MatrixCharacteristics;\n+import org.apache.sysds.runtime.util.HDFSTool;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+\n+@RunWith(value = Parameterized.class)\[email protected]\n+public class FederatedCtableTest extends AutomatedTestBase {\n+ private final static String TEST_DIR = \"functions/federated/\";\n+ private final static String TEST_NAME1 = \"FederatedCtableTest\";\n+ private final static String TEST_NAME2 = \"FederatedCtableFedOutput\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + FederatedCtableTest.class.getSimpleName() + \"/\";\n+\n+ private final static int blocksize = 1024;\n+ @Parameterized.Parameter()\n+ public int rows;\n+ @Parameterized.Parameter(1)\n+ public int cols;\n+ @Parameterized.Parameter(2)\n+ public int maxVal1;\n+ @Parameterized.Parameter(3)\n+ public int maxVal2;\n+ @Parameterized.Parameter(4)\n+ public boolean reversedInputs;\n+ @Parameterized.Parameter(5)\n+ public boolean weighted;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] {\"F\"}));\n+ addTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] {\"F\"}));\n+ }\n+\n+ @Parameterized.Parameters\n+ public static Collection<Object[]> data() {\n+ return Arrays.asList(new Object[][] {\n+ {12, 4, 4, 7, true, true}, {12, 4, 4, 7, true, false},\n+ {12, 4, 4, 7, false, true}, {12, 4, 4, 7, false, false},\n+\n+ {100, 14, 4, 7, true, true}, {100, 14, 4, 7, true, false},\n+ {100, 14, 4, 7, false, true}, {100, 14, 4, 7, false, false},\n+\n+ // {1000, 14, 4, 7, true, true}, {1000, 14, 4, 7, true, false},\n+ // {1000, 14, 4, 7, false, true}, {1000, 14, 4, 7, false, false}\n+ });\n+ }\n+\n+ @Test\n+ public void federatedCtableSinglenode() { runCtable(Types.ExecMode.SINGLE_NODE, false, false); }\n+\n+ @Test\n+ public void federatedCtableFedOutputSinglenode() { runCtable(Types.ExecMode.SINGLE_NODE, true, false); }\n+\n+ @Test\n+ public void federatedCtableMatrixInputSinglenode() { runCtable(Types.ExecMode.SINGLE_NODE, false, true); }\n+\n+\n+ public void runCtable(Types.ExecMode execMode, boolean fedOutput, boolean matrixInput) {\n+ String TEST_NAME = fedOutput ? TEST_NAME2 : TEST_NAME1;\n+ Types.ExecMode platformOld = setExecMode(execMode);\n+\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+ int port1 = getRandomAvailablePort();\n+ int port2 = getRandomAvailablePort();\n+ int port3 = getRandomAvailablePort();\n+ int port4 = getRandomAvailablePort();\n+ Thread t1 = startLocalFedWorkerThread(port1, FED_WORKER_WAIT_S);\n+ Thread t2 = startLocalFedWorkerThread(port2, FED_WORKER_WAIT_S);\n+ Thread t3 = startLocalFedWorkerThread(port3, FED_WORKER_WAIT_S);\n+ Thread t4 = startLocalFedWorkerThread(port4);\n+\n+ TestConfiguration config = availableTestConfigurations.get(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ if(fedOutput)\n+ runFedCtable(HOME, TEST_NAME, port1, port2, port3, port4);\n+ else\n+ runNonFedCtable(HOME, TEST_NAME, matrixInput, port1, port2, port3, port4);\n+ checkResults();\n+\n+ TestUtils.shutdownThreads(t1, t2, t3, t4);\n+ resetExecMode(platformOld);\n+ }\n+\n+ private void runNonFedCtable(String HOME, String TEST_NAME, boolean matrixInput, int port1, int port2, int port3, int port4) {\n+ int r = rows / 4;\n+ cols = matrixInput ? cols : 1;\n+ double[][] X1 = TestUtils.floor(getRandomMatrix(r, cols, 1, maxVal1, 1, 3));\n+ double[][] X2 = TestUtils.floor(getRandomMatrix(r, cols, 1, maxVal1, 1, 7));\n+ double[][] X3 = TestUtils.floor(getRandomMatrix(r, cols, 1, maxVal1, 1, 8));\n+ double[][] X4 = TestUtils.floor(getRandomMatrix(r, cols, 1, maxVal1, 1, 9));\n+\n+ MatrixCharacteristics mc = new MatrixCharacteristics(r, cols, blocksize, r);\n+ writeInputMatrixWithMTD(\"X1\", X1, false, mc);\n+ writeInputMatrixWithMTD(\"X2\", X2, false, mc);\n+ writeInputMatrixWithMTD(\"X3\", X3, false, mc);\n+ writeInputMatrixWithMTD(\"X4\", X4, false, mc);\n+\n+ double[][] Y = TestUtils.floor(getRandomMatrix(rows, cols, 1, maxVal2, 1, 9));\n+ writeInputMatrixWithMTD(\"Y\", Y, false, new MatrixCharacteristics(rows, cols, blocksize, r));\n+\n+ // empty script name because we don't execute any script, just start the worker\n+ fullDMLScriptName = \"\";\n+\n+ // Run reference dml script with normal matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-args\", input(\"X1\"), input(\"X2\"), input(\"X3\"), input(\"X4\"),\n+ input(\"Y\"), Boolean.toString(reversedInputs).toUpperCase(), Boolean.toString(weighted).toUpperCase(),expected(\"F\")};\n+ runTest(true, false, null, -1);\n+\n+ // Run actual dml script with federated matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-nvargs\",\n+ \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"X1\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"X2\")),\n+ \"in_X3=\" + TestUtils.federatedAddress(port3, input(\"X3\")),\n+ \"in_X4=\" + TestUtils.federatedAddress(port4, input(\"X4\")), \"in_Y=\" + input(\"Y\"),\n+ \"rows=\" + rows, \"cols=\" + cols, \"revIn=\" + Boolean.toString(reversedInputs).toUpperCase(),\n+ \"weighted=\" + Boolean.toString(weighted).toUpperCase(), \"out=\" + output(\"F\")};\n+ runTest(true, false, null, -1);\n+ }\n+\n+ private void runFedCtable(String HOME, String TEST_NAME, int port1, int port2, int port3, int port4) {\n+ int r = rows / 4;\n+ int c = cols;\n+\n+ double[][] X1 = getRandomMatrix(r, c, 1, 3, 1, 3);\n+ double[][] X2 = getRandomMatrix(r, c, 1, 3, 1, 7);\n+ double[][] X3 = getRandomMatrix(r, c, 1, 3, 1, 8);\n+ double[][] X4 = getRandomMatrix(r, c, 1, 3, 1, 9);\n+\n+ MatrixCharacteristics mc = new MatrixCharacteristics(r, c, blocksize, r * c);\n+ writeInputMatrixWithMTD(\"X1\", X1, false, mc);\n+ writeInputMatrixWithMTD(\"X2\", X2, false, mc);\n+ writeInputMatrixWithMTD(\"X3\", X3, false, mc);\n+ writeInputMatrixWithMTD(\"X4\", X4, false, mc);\n+\n+ //execute main test\n+ fullDMLScriptName = HOME + TEST_NAME2 + \"Reference.dml\";\n+ programArgs = new String[]{\"-stats\", \"100\", \"-args\",\n+ input(\"X1\"), input(\"X2\"), input(\"X3\"), input(\"X4\"), Boolean.toString(reversedInputs).toUpperCase(),\n+ Boolean.toString(weighted).toUpperCase(), expected(\"F\")};\n+ runTest(true, false, null, -1);\n+\n+ // Run actual dml script with federated matrix\n+ fullDMLScriptName = HOME + TEST_NAME2 + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-nvargs\",\n+ \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"X1\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"X2\")),\n+ \"in_X3=\" + TestUtils.federatedAddress(port3, input(\"X3\")),\n+ \"in_X4=\" + TestUtils.federatedAddress(port4, input(\"X4\")),\n+ \"rows=\" + rows, \"cols=\" + cols, \"revIn=\" + Boolean.toString(reversedInputs).toUpperCase(),\n+ \"weighted=\" + Boolean.toString(weighted).toUpperCase(), \"out=\" + output(\"F\")\n+ };\n+ runTest(true, false, null, -1);\n+ }\n+\n+ void checkResults() {\n+ // compare via files\n+ compareResults(1e-9);\n+\n+ // check for federated operations\n+ Assert.assertTrue(heavyHittersContainsString(\"fed_ctable\"));\n+\n+ // check that federated input files are still existing\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X1\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X2\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X3\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X4\")));\n+ }\n+\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedCtableFedOutput.dml", "diff": "+#-------------------------------------------------------------\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 = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+\n+m = nrow(X);\n+n = ncol(X);\n+\n+# prepare offset vectors and one-hot encoded X\n+maxs = colMaxs(X);\n+rix = matrix(seq(1,m)%*%matrix(1,1,n), m*n, 1);\n+cix = matrix(X + (t(cumsum(t(maxs))) - maxs), m*n, 1);\n+\n+W = rix + cix;\n+\n+if($revIn)\n+ if($weighted)\n+ X2 = table(cix, rix, W);\n+ else\n+ X2 = table(cix, rix);\n+else\n+ if($weighted)\n+ X2 = table(rix, cix, W);\n+ else\n+ X2 = table(rix, cix);\n+\n+write(X2, $out);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedCtableFedOutputReference.dml", "diff": "+#-------------------------------------------------------------\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 = rbind(read($1), read($2), read($3), read($4));\n+\n+m = nrow(X);\n+n = ncol(X);\n+\n+# prepare offset vectors and one-hot encoded X\n+maxs = colMaxs(X);\n+\n+rix = matrix(seq(1,m)%*%matrix(1,1,n), m*n, 1)\n+cix = matrix(X + (t(cumsum(t(maxs))) - maxs), m*n, 1);\n+\n+W = rix + cix;\n+\n+if($5)\n+ if($6)\n+ X2 = table(cix, rix, W);\n+ else\n+ X2 = table(cix, rix);\n+else\n+ if($6)\n+ X2 = table(rix, cix, W);\n+ else\n+ X2 = table(rix, cix);\n+\n+write(X2, $7);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedCtableTest.dml", "diff": "+#-------------------------------------------------------------\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 = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+\n+Y = read($in_Y);\n+W = Y * 2;\n+\n+if($revIn)\n+ if($weighted)\n+ F = table(X, Y, W);\n+ else\n+ F = table(X, Y);\n+else\n+ if($weighted)\n+ F = table(X, Y, W);\n+ else\n+ F = table(X, Y);\n+\n+write(F, $out);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedCtableTestReference.dml", "diff": "+#-------------------------------------------------------------\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 = rbind(read($1), read($2), read($3), read($4));\n+Y = read($5);\n+W = Y * 2;\n+\n+if($6)\n+ if($7)\n+ F = table(X, Y, W);\n+ else\n+ F = table(X, Y);\n+else\n+ if($7)\n+ F = table(X, Y, W);\n+ else\n+ F = table(X, Y);\n+\n+write(F, $8);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2863] Federated ctable instruction Closes #1184
49,722
07.04.2021 00:51:10
-7,200
c07cd15ba100d4133548336e91082922bf160337
Federated left indexing Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederationMap.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederationMap.java", "diff": "@@ -40,6 +40,7 @@ import org.apache.sysds.runtime.controlprogram.federated.FederatedRequest.Reques\nimport org.apache.sysds.runtime.DMLRuntimeException;\nimport org.apache.sysds.runtime.instructions.cp.ScalarObject;\nimport org.apache.sysds.runtime.instructions.cp.VariableCPInstruction;\n+import org.apache.sysds.runtime.matrix.data.FrameBlock;\nimport org.apache.sysds.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysds.runtime.util.CommonThreadPool;\nimport org.apache.sysds.runtime.util.IndexRange;\n@@ -172,6 +173,22 @@ public class FederationMap {\nreturn ret;\n}\n+ public FederatedRequest[] broadcastSliced(CacheableData<?> data, boolean isFrame, int[][] ix) {\n+ if( _type == FType.FULL )\n+ return new FederatedRequest[]{broadcast(data)};\n+\n+ // prepare broadcast id and pin input\n+ long id = FederationUtils.getNextFedDataID();\n+ CacheBlock cb = data.acquireReadAndRelease();\n+\n+ // multi-threaded block slicing and federation request creation\n+ FederatedRequest[] ret = new FederatedRequest[ix.length];\n+ Arrays.setAll(ret,\n+ i -> new FederatedRequest(RequestType.PUT_VAR, id,\n+ cb.slice(ix[i][0], ix[i][1], ix[i][2], ix[i][3], isFrame ? new FrameBlock() : new MatrixBlock())));\n+ return ret;\n+ }\n+\npublic boolean isAligned(FederationMap that, boolean transposed) {\n// determines if the two federated data are aligned row/column partitions\n// at the same federated site (which allows for purely federated operation)\n@@ -214,17 +231,20 @@ public class FederationMap {\n}\n@SuppressWarnings(\"unchecked\")\n- public Future<FederatedResponse>[] execute(long tid, boolean wait, FederatedRequest[] frSlices1, FederatedRequest[] frSlices2, FederatedRequest... fr) {\n+ public Future<FederatedResponse>[] execute(long tid, boolean wait, FederatedRange[] fedRange1, FederatedRequest elseFr, FederatedRequest[] frSlices1, FederatedRequest[] frSlices2, FederatedRequest... fr) {\n// executes step1[] - step 2 - ... step4 (only first step federated-data-specific)\nsetThreadID(tid, frSlices1, fr);\nsetThreadID(tid, frSlices2, fr);\nList<Future<FederatedResponse>> ret = new ArrayList<>();\nint pos = 0;\nfor(Entry<FederatedRange, FederatedData> e : _fedMap.entrySet()) {\n- FederatedRequest[] newFr = (frSlices1!=null) ?\n- ((frSlices2!=null)? (addAll(frSlices2[pos], addAll(frSlices1[pos++], fr))) : addAll(frSlices1[pos++], fr)) : fr;\n+ if(Arrays.asList(fedRange1).contains(e.getKey())) {\n+ FederatedRequest[] newFr = (frSlices1 != null) ? ((frSlices2 != null) ? (addAll(frSlices2[pos],\n+ addAll(frSlices1[pos++], fr))) : addAll(frSlices1[pos++], fr)) : fr;\nret.add(e.getValue().executeFederatedOperation(newFr));\n}\n+ else ret.add(e.getValue().executeFederatedOperation(elseFr));\n+ }\n// prepare results (future federated responses), with optional wait to ensure the\n// order of requests without data dependencies (e.g., cleanup RPCs)\n@@ -233,6 +253,10 @@ public class FederationMap {\nreturn ret.toArray(new Future[0]);\n}\n+ public Future<FederatedResponse>[] execute(long tid, boolean wait, FederatedRequest[] frSlices1, FederatedRequest[] frSlices2, FederatedRequest... fr) {\n+ return execute(tid, wait, Arrays.stream(_fedMap.keySet().toArray()).toArray(FederatedRange[]::new), null, frSlices1, frSlices2, fr);\n+ }\n+\n@SuppressWarnings(\"unchecked\")\npublic Future<FederatedResponse>[] executeMultipleSlices(long tid, boolean wait,\nFederatedRequest[][] frSlices, FederatedRequest[] fr) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/VariableCPInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/VariableCPInstruction.java", "diff": "@@ -436,8 +436,9 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\ncase CopyVariable:\n// Value types are not given here\n- in1 = new CPOperand(parts[1], ValueType.UNKNOWN, DataType.UNKNOWN);\n- in2 = new CPOperand(parts[2], ValueType.UNKNOWN, DataType.UNKNOWN);\n+ boolean withTypes = parts[1].split(VALUETYPE_PREFIX).length > 2 && parts[2].split(VALUETYPE_PREFIX).length > 2;\n+ in1 = withTypes ? new CPOperand(parts[1]) : new CPOperand(parts[1], ValueType.UNKNOWN, DataType.UNKNOWN);\n+ in2 = withTypes ? new CPOperand(parts[2]) : new CPOperand(parts[2], ValueType.UNKNOWN, DataType.UNKNOWN);\nbreak;\ncase MoveVariable:\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "diff": "@@ -174,8 +174,7 @@ public class FEDInstructionUtils {\nelse if(inst instanceof IndexingCPInstruction) {\n// matrix and frame indexing\nIndexingCPInstruction minst = (IndexingCPInstruction) inst;\n- if(inst.getOpcode().equalsIgnoreCase(\"rightIndex\")\n- && (minst.input1.isMatrix() || minst.input1.isFrame())\n+ if((minst.input1.isMatrix() || minst.input1.isFrame())\n&& ec.getCacheableData(minst.input1).isFederated()) {\nfedinst = IndexingFEDInstruction.parseInstruction(minst.getInstructionString());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/IndexingFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/IndexingFEDInstruction.java", "diff": "@@ -23,6 +23,7 @@ import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n+import java.util.Objects;\nimport org.apache.sysds.common.Types;\nimport org.apache.sysds.common.Types.ValueType;\n@@ -40,6 +41,7 @@ import org.apache.sysds.runtime.controlprogram.federated.FederationMap;\nimport org.apache.sysds.runtime.controlprogram.federated.FederationUtils;\nimport org.apache.sysds.runtime.instructions.InstructionUtils;\nimport org.apache.sysds.runtime.instructions.cp.CPOperand;\n+import org.apache.sysds.runtime.instructions.cp.VariableCPInstruction;\nimport org.apache.sysds.runtime.util.IndexRange;\npublic final class IndexingFEDInstruction extends UnaryFEDInstruction {\n@@ -95,7 +97,25 @@ public final class IndexingFEDInstruction extends UnaryFEDInstruction {\n}\n}\nelse if(opcode.equalsIgnoreCase(LeftIndex.OPCODE)) {\n- throw new DMLRuntimeException(\"Left indexing not implemented for federated operations.\");\n+ if ( parts.length == 8 ) {\n+ CPOperand lhsInput, rhsInput, rl, ru, cl, cu, out;\n+ lhsInput = new CPOperand(parts[1]);\n+ rhsInput = new CPOperand(parts[2]);\n+ rl = new CPOperand(parts[3]);\n+ ru = new CPOperand(parts[4]);\n+ cl = new CPOperand(parts[5]);\n+ cu = new CPOperand(parts[6]);\n+ out = new CPOperand(parts[7]);\n+\n+ if((lhsInput.getDataType() != Types.DataType.MATRIX && lhsInput.getDataType() != Types.DataType.FRAME) &&\n+ (rhsInput.getDataType() != Types.DataType.MATRIX && rhsInput.getDataType() != Types.DataType.FRAME))\n+ throw new DMLRuntimeException(\"Can index only on matrices, frames, and lists.\");\n+\n+ return new IndexingFEDInstruction(lhsInput, rhsInput, rl, ru, cl, cu, out, opcode, str);\n+ }\n+ else {\n+ throw new DMLRuntimeException(\"Invalid number of operands in instruction: \" + str);\n+ }\n}\nelse {\nthrow new DMLRuntimeException(\"Unknown opcode while parsing a MatrixIndexingFEDInstruction: \" + str);\n@@ -104,7 +124,10 @@ public final class IndexingFEDInstruction extends UnaryFEDInstruction {\n@Override\npublic void processInstruction(ExecutionContext ec) {\n+ if(getOpcode().equalsIgnoreCase(RightIndex.OPCODE))\nrightIndexing(ec);\n+ else\n+ leftIndexing(ec);\n}\nprivate void rightIndexing(ExecutionContext ec)\n@@ -140,11 +163,7 @@ public final class IndexingFEDInstruction extends UnaryFEDInstruction {\nlong[] newIx = new long[]{rsn, ren, csn, cen};\n// change 4 indices in instString\n- instStrings[i] = instString;\n- String[] instParts = instString.split(Lop.OPERAND_DELIMITOR);\n- for(int j = 3; j < 7; j++)\n- instParts[j] = InstructionUtils.createLiteralOperand(String.valueOf(newIx[j-3]+1), ValueType.INT64);\n- instStrings[i] = String.join(Lop.OPERAND_DELIMITOR, instParts);\n+ instStrings[i] = modifyIndices(newIx, 3, 7);\nif(input1.isFrame()) {\n//modify frame schema\n@@ -171,4 +190,112 @@ public final class IndexingFEDInstruction extends UnaryFEDInstruction {\nout.setFedMapping(fedMap.copyWithNewID(fr1[0].getID()));\n}\n}\n+\n+ private void leftIndexing(ExecutionContext ec)\n+ {\n+ //get input and requested index range\n+ CacheableData<?> in1 = ec.getCacheableData(input1);\n+ CacheableData<?> in2 = ec.getCacheableData(input2);\n+ IndexRange ixrange = getIndexRange(ec);\n+\n+ //check bounds\n+ if( ixrange.rowStart < 0 || ixrange.rowStart >= in1.getNumRows() || ixrange.rowEnd >= in1.getNumRows()\n+ || ixrange.colStart < 0 || ixrange.colStart >= in1.getNumColumns() || ixrange.colEnd >= in1.getNumColumns() ) {\n+ throw new DMLRuntimeException(\"Invalid values for matrix indexing: [\"+(ixrange.rowStart+1)+\":\"+(ixrange.rowEnd+1)+\",\"\n+ + (ixrange.colStart+1)+\":\"+(ixrange.colEnd+1)+\"] \" + \"must be within matrix dimensions [\"+in1.getNumRows()+\",\"+in1.getNumColumns()+\"].\");\n+ }\n+ if( (ixrange.rowEnd-ixrange.rowStart+1) != in2.getNumRows() || (ixrange.colEnd-ixrange.colStart+1) != in2.getNumColumns()) {\n+ throw new DMLRuntimeException(\"Invalid values for matrix indexing: \" +\n+ \"dimensions of the source matrix [\"+in2.getNumRows()+\"x\" + in2.getNumColumns() + \"] \" +\n+ \"do not match the shape of the matrix specified by indices [\" +\n+ (ixrange.rowStart+1) +\":\" + (ixrange.rowEnd+1) + \", \" + (ixrange.colStart+1) + \":\" + (ixrange.colEnd+1) + \"].\");\n+ }\n+\n+ FederationMap fedMap = in1.getFedMapping();\n+\n+ String[] instStrings = new String[fedMap.getSize()];\n+ int[][] sliceIxs = new int[fedMap.getSize()][];\n+ FederatedRange[] ranges = new FederatedRange[fedMap.getSize()];\n+\n+ // replace old reshape values for each worker\n+ int i = 0, prev = 0, from = fedMap.getSize();\n+ for(FederatedRange range : fedMap.getMap().keySet()) {\n+ long rs = range.getBeginDims()[0], re = range.getEndDims()[0],\n+ cs = range.getBeginDims()[1], ce = range.getEndDims()[1];\n+ long rsn = (ixrange.rowStart >= rs) ? (ixrange.rowStart - rs) : 0;\n+ long ren = (ixrange.rowEnd >= rs && ixrange.rowEnd < re) ? (ixrange.rowEnd - rs) : (re - rs - 1);\n+ long csn = (ixrange.colStart >= cs) ? (ixrange.colStart - cs) : 0;\n+ long cen = (ixrange.colEnd >= cs && ixrange.colEnd < ce) ? (ixrange.colEnd - cs) : (ce - cs - 1);\n+\n+ long[] newIx = new long[]{(int) rsn, (int) ren, (int) csn, (int) cen};\n+\n+ // find ranges where to apply leftIndex\n+ long to;\n+ if(in1.isFederated(FederationMap.FType.ROW) && (to = (prev + ren - rsn)) >= 0 &&\n+ to < in2.getNumRows() && ixrange.rowStart <= re) {\n+ sliceIxs[i] = new int[] { prev, (int) to, 0, (int) in2.getNumColumns()-1};\n+ prev = (int) (to + 1);\n+\n+ instStrings[i] = modifyIndices(newIx, 4, 8);\n+ ranges[i] = range;\n+ from = Math.min(i, from);\n+ }\n+ else if(in1.isFederated(FederationMap.FType.COL) && (to = (prev + cen - csn)) >= 0 &&\n+ to < in2.getNumColumns() && ixrange.colStart <= ce) {\n+ sliceIxs[i] = new int[] {0, (int) in2.getNumRows() - 1, prev, (int) to};\n+ prev = (int) (to + 1);\n+\n+ instStrings[i] = modifyIndices(newIx, 4, 8);\n+ ranges[i] = range;\n+ from = Math.min(i, from);\n+ }\n+ else\n+ // TODO shallow copy, add more advanced update in place for federated\n+ instStrings[i] = createCopyInstString();\n+\n+ i++;\n+ }\n+\n+ sliceIxs = Arrays.stream(sliceIxs).filter(Objects::nonNull).toArray(int[][] :: new);\n+\n+ FederatedRequest[] fr1 = fedMap.broadcastSliced(in2, input2.isFrame(), sliceIxs);\n+ FederatedRequest[] fr2 = FederationUtils.callInstruction(instStrings, output, new CPOperand[]{input1, input2},\n+ new long[]{fedMap.getID(), fr1[0].getID()});\n+ FederatedRequest fr3 = fedMap.cleanup(getTID(), fr1[0].getID());\n+\n+ //execute federated instruction and cleanup intermediates\n+ if(sliceIxs.length == fedMap.getSize())\n+ fedMap.execute(getTID(), true, fr2, fr1, fr3);\n+ else {\n+ // get index of cpvar request\n+ for(i = 0; i < fr2.length; i++)\n+ if(i < from || i >= from + sliceIxs.length)\n+ break;\n+ fedMap.execute(getTID(), true, ranges, (fr2[i]), Arrays.copyOfRange(fr2, from, from + sliceIxs.length), fr1, fr3);\n+ }\n+\n+ if(input1.isFrame()) {\n+ FrameObject out = ec.getFrameObject(output);\n+ out.setSchema(((FrameObject) in1).getSchema());\n+ out.getDataCharacteristics().set(in1.getDataCharacteristics());\n+ out.setFedMapping(fedMap.copyWithNewID(fr2[0].getID()));\n+ } else {\n+ MatrixObject out = ec.getMatrixObject(output);\n+ out.getDataCharacteristics().set(in1.getDataCharacteristics());;\n+ out.setFedMapping(fedMap.copyWithNewID(fr2[0].getID()));\n+ }\n+ }\n+\n+ private String modifyIndices(long[] newIx, int from, int to) {\n+ // change 4 indices in instString\n+ String[] instParts = instString.split(Lop.OPERAND_DELIMITOR);\n+ for(int j = from; j < to; j++)\n+ instParts[j] = InstructionUtils.createLiteralOperand(String.valueOf(newIx[j-from]+1), ValueType.INT64);\n+ return String.join(Lop.OPERAND_DELIMITOR, instParts);\n+ }\n+\n+ private String createCopyInstString() {\n+ String[] instParts = instString.split(Lop.OPERAND_DELIMITOR);\n+ return VariableCPInstruction.prepareCopyInstruction(instParts[2], instParts[8]).toString();\n+ }\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedLeftIndexTest.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.apache.sysds.test.functions.federated.primitives;\n+\n+import java.util.Arrays;\n+import java.util.Collection;\n+\n+import org.apache.sysds.api.DMLScript;\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.runtime.meta.MatrixCharacteristics;\n+import org.apache.sysds.runtime.util.HDFSTool;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+\n+@RunWith(value = Parameterized.class)\[email protected]\n+public class FederatedLeftIndexTest extends AutomatedTestBase {\n+\n+ private final static String TEST_NAME1 = \"FederatedLeftIndexFullTest\";\n+ private final static String TEST_NAME2 = \"FederatedLeftIndexFrameFullTest\";\n+\n+ private final static String TEST_DIR = \"functions/federated/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + FederatedLeftIndexTest.class.getSimpleName() + \"/\";\n+\n+ private final static int blocksize = 1024;\n+ @Parameterized.Parameter()\n+ public int rows1;\n+ @Parameterized.Parameter(1)\n+ public int cols1;\n+\n+ @Parameterized.Parameter(2)\n+ public int rows2;\n+ @Parameterized.Parameter(3)\n+ public int cols2;\n+\n+ @Parameterized.Parameter(4)\n+ public int from;\n+ @Parameterized.Parameter(5)\n+ public int to;\n+\n+ @Parameterized.Parameter(6)\n+ public int from2;\n+ @Parameterized.Parameter(7)\n+ public int to2;\n+\n+ @Parameterized.Parameter(8)\n+ public boolean rowPartitioned;\n+\n+ @Parameterized.Parameters\n+ public static Collection<Object[]> data() {\n+ return Arrays.asList(new Object[][] {\n+ {8, 2, 8, 1, 1, 8, 1, 1, true},\n+ {24, 12, 20, 8, 3, 22, 1, 8, true},\n+ {24, 12, 10, 8, 7, 16, 1, 8, true},\n+ {24, 12, 20, 11, 3, 22, 1, 11, false},\n+ {24, 12, 20, 8, 3, 22, 1, 8, false},\n+ {24, 12, 20, 8, 3, 22, 5, 12, false},\n+ });\n+ }\n+\n+ private enum DataType {\n+ MATRIX, FRAME\n+ }\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] {\"S\"}));\n+ addTestConfiguration(TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] {\"S\"}));\n+ }\n+\n+ @Test\n+ public void testLeftIndexFullDenseMatrixCP() {\n+ runAggregateOperationTest(DataType.MATRIX, ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ public void testLeftIndexFullDenseFrameCP() {\n+ runAggregateOperationTest(DataType.FRAME, ExecMode.SINGLE_NODE);\n+ }\n+\n+ private void runAggregateOperationTest(DataType dataType, ExecMode execMode) {\n+ setExecMode(execMode);\n+\n+ String TEST_NAME = null;\n+\n+ if(dataType == DataType.MATRIX)\n+ TEST_NAME = TEST_NAME1;\n+ else\n+ TEST_NAME = TEST_NAME2;\n+\n+\n+ getAndLoadTestConfiguration(TEST_NAME);\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+\n+ // write input matrices\n+ int r1 = rows1;\n+ int c1 = cols1 / 4;\n+ if(rowPartitioned) {\n+ r1 = rows1 / 4;\n+ c1 = cols1;\n+ }\n+\n+ double[][] X1 = getRandomMatrix(r1, c1, 1, 5, 1, 3);\n+ double[][] X2 = getRandomMatrix(r1, c1, 1, 5, 1, 7);\n+ double[][] X3 = getRandomMatrix(r1, c1, 1, 5, 1, 8);\n+ double[][] X4 = getRandomMatrix(r1, c1, 1, 5, 1, 9);\n+\n+ MatrixCharacteristics mc = new MatrixCharacteristics(r1, c1, blocksize, r1 * c1);\n+ writeInputMatrixWithMTD(\"X1\", X1, false, mc);\n+ writeInputMatrixWithMTD(\"X2\", X2, false, mc);\n+ writeInputMatrixWithMTD(\"X3\", X3, false, mc);\n+ writeInputMatrixWithMTD(\"X4\", X4, false, mc);\n+\n+ double[][] Y = getRandomMatrix(rows2, cols2, 1, 5, 1, 3);\n+\n+ MatrixCharacteristics mc2 = new MatrixCharacteristics(rows2, cols2, blocksize, rows2 * cols2);\n+ writeInputMatrixWithMTD(\"Y\", Y, false, mc2);\n+\n+ // empty script name because we don't execute any script, just start the worker\n+ fullDMLScriptName = \"\";\n+ int port1 = getRandomAvailablePort();\n+ int port2 = getRandomAvailablePort();\n+ int port3 = getRandomAvailablePort();\n+ int port4 = getRandomAvailablePort();\n+ Thread t1 = startLocalFedWorkerThread(port1, FED_WORKER_WAIT_S);\n+ Thread t2 = startLocalFedWorkerThread(port2, FED_WORKER_WAIT_S);\n+ Thread t3 = startLocalFedWorkerThread(port3, FED_WORKER_WAIT_S);\n+ Thread t4 = startLocalFedWorkerThread(port4);\n+\n+ rtplatform = execMode;\n+ if(rtplatform == ExecMode.SPARK) {\n+ System.out.println(7);\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+ }\n+ TestConfiguration config = availableTestConfigurations.get(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ if(from > to)\n+ from = to;\n+ if(from2 > to2)\n+ from2 = to2;\n+\n+ // Run reference dml script with normal matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-explain\", \"-args\", input(\"X1\"), input(\"X2\"), input(\"X3\"), input(\"X4\"),\n+ input(\"Y\"), String.valueOf(from), String.valueOf(to),\n+ String.valueOf(from2), String.valueOf(to2),\n+ Boolean.toString(rowPartitioned).toUpperCase(), expected(\"S\")};\n+ runTest(null);\n+ // Run actual dml script with federated matrix\n+\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-nvargs\",\n+ \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"X1\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"X2\")),\n+ \"in_X3=\" + TestUtils.federatedAddress(port3, input(\"X3\")),\n+ \"in_X4=\" + TestUtils.federatedAddress(port4, input(\"X4\")),\n+ \"in_Y=\" + input(\"Y\"), \"rows=\" + rows1, \"cols=\" + cols1,\n+ \"rows2=\" + rows2, \"cols2=\" + cols2,\n+ \"from=\" + from, \"to=\" + to,\"from2=\" + from2, \"to2=\" + to2,\n+ \"rP=\" + Boolean.toString(rowPartitioned).toUpperCase(), \"out_S=\" + output(\"S\")};\n+\n+ runTest(null);\n+\n+ // compare via files\n+ compareResults(1e-9);\n+\n+ Assert.assertTrue(heavyHittersContainsString(\"fed_leftIndex\"));\n+\n+ // check that federated input files are still existing\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X1\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X2\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X3\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X4\")));\n+\n+ TestUtils.shutdownThreads(t1, t2, t3, t4);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedLeftIndexFrameFullTest.dml", "diff": "+#-------------------------------------------------------------\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+from = $from;\n+to = $to;\n+from2 = $from2;\n+to2 = $to2;\n+\n+if ($rP) {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+} else {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows, $cols/4), list(0,$cols/4), list($rows, $cols/2),\n+ list(0,$cols/2), list($rows, 3*($cols/4)), list(0, 3*($cols/4)), list($rows, $cols)));\n+}\n+\n+B = read($in_Y)\n+\n+B = as.frame(B)\n+A = as.frame(A)\n+\n+A[from:to, from2:to2] = B;\n+write(A, $out_S);\n+\n+print(toString(A))\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedLeftIndexFrameFullTestReference.dml", "diff": "+#-------------------------------------------------------------\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+from = $6;\n+to = $7;\n+from2 = $8;\n+to2 = $9;\n+if($10) {\n+ A = rbind(read($1), read($2), read($3), read($4));\n+}\n+else {\n+ A = cbind(read($1), read($2), read($3), read($4));\n+}\n+\n+B = read($5)\n+\n+B = as.frame(B)\n+A = as.frame(A)\n+\n+A[from:to, from2:to2] = B;\n+write(A, $11);\n+\n+print(toString(A))\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedLeftIndexFullTest.dml", "diff": "+#-------------------------------------------------------------\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+from = $from;\n+to = $to;\n+from2 = $from2;\n+to2 = $to2;\n+\n+if ($rP) {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+} else {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows, $cols/4), list(0,$cols/4), list($rows, $cols/2),\n+ list(0,$cols/2), list($rows, 3*($cols/4)), list(0, 3*($cols/4)), list($rows, $cols)));\n+}\n+\n+B = read($in_Y)\n+\n+A[from:to, from2:to2] = B;\n+write(A, $out_S);\n+\n+print(toString(A))\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedLeftIndexFullTestReference.dml", "diff": "+#-------------------------------------------------------------\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+from = $6;\n+to = $7;\n+from2 = $8;\n+to2 = $9;\n+if($10) {\n+ A = rbind(read($1), read($2), read($3), read($4));\n+}\n+else {\n+ A = cbind(read($1), read($2), read($3), read($4));\n+}\n+\n+B = read($5)\n+\n+A[from:to, from2:to2] = B;\n+write(A, $11);\n+\n+print(toString(A))\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2925] Federated left indexing Closes #1219
49,706
27.04.2021 21:03:10
-7,200
c2492d7c6ae6b46d69f5b543de428fb30b8311a8
[MINOR] Add missing unary support federated Add missing support for log and sigmoid for unary operations federated. This check is a basic copy of the CP Unary operations, but if it is possible to execute locally that unary operation should be possible federated.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/UnaryCPInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/UnaryCPInstruction.java", "diff": "@@ -62,9 +62,10 @@ public abstract class UnaryCPInstruction extends ComputationCPInstruction {\nout.split(parts[2]);\nfunc = Builtin.getBuiltinFnObject(opcode);\n- if( Arrays.asList(new String[]{\"ucumk+\",\"ucum*\",\"ucumk+*\",\"ucummin\",\"ucummax\",\"exp\",\"log\",\"sigmoid\"}).contains(opcode) )\n- return new UnaryMatrixCPInstruction(new UnaryOperator(func,\n- Integer.parseInt(parts[3]),Boolean.parseBoolean(parts[4])), in, out, opcode, str);\n+ if( Arrays.asList(new String[]{\"ucumk+\",\"ucum*\",\"ucumk+*\",\"ucummin\",\"ucummax\",\"exp\",\"log\",\"sigmoid\"}).contains(opcode) ){\n+ UnaryOperator op = new UnaryOperator(func, Integer.parseInt(parts[3]),Boolean.parseBoolean(parts[4]));\n+ return new UnaryMatrixCPInstruction(op, in, out, opcode, str);\n+ }\nelse\nreturn new UnaryScalarCPInstruction(null, in, out, opcode, str);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/UnaryMatrixFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/UnaryMatrixFEDInstruction.java", "diff": "package org.apache.sysds.runtime.instructions.fed;\n+import java.util.Arrays;\nimport java.util.concurrent.Future;\nimport org.apache.sysds.common.Types.DataType;\n@@ -40,6 +41,7 @@ import org.apache.sysds.runtime.matrix.operators.Operator;\nimport org.apache.sysds.runtime.matrix.operators.UnaryOperator;\npublic class UnaryMatrixFEDInstruction extends UnaryFEDInstruction {\n+\nprotected UnaryMatrixFEDInstruction(Operator op, CPOperand in, CPOperand out, String opcode, String instr) {\nsuper(FEDType.Unary, op, in, out, opcode, instr);\n}\n@@ -53,14 +55,18 @@ public class UnaryMatrixFEDInstruction extends UnaryFEDInstruction {\nCPOperand out = new CPOperand(\"\", ValueType.UNKNOWN, DataType.UNKNOWN);\nString[] parts = InstructionUtils.getInstructionPartsWithValueType(str);\n- String opcode;\n- opcode = parts[0];\n- if( (opcode.equalsIgnoreCase(\"exp\") || opcode.startsWith(\"ucum\")) && parts.length == 5) {\n+ String opcode = parts[0];\n+\n+ if(parts.length == 5 && (opcode.equalsIgnoreCase(\"exp\") || opcode.equalsIgnoreCase(\"log\") || opcode.startsWith(\"ucum\"))) {\nin.split(parts[1]);\nout.split(parts[2]);\nValueFunction func = Builtin.getBuiltinFnObject(opcode);\n- return new UnaryMatrixFEDInstruction(new UnaryOperator(func,\n- Integer.parseInt(parts[3]),Boolean.parseBoolean(parts[4])), in, out, opcode, str);\n+ if( Arrays.asList(new String[]{\"ucumk+\",\"ucum*\",\"ucumk+*\",\"ucummin\",\"ucummax\",\"exp\",\"log\",\"sigmoid\"}).contains(opcode) ){\n+ UnaryOperator op = new UnaryOperator(func,Integer.parseInt(parts[3]),Boolean.parseBoolean(parts[4]));\n+ return new UnaryMatrixFEDInstruction(op, in, out, opcode, str);\n+ }\n+ else\n+ return new UnaryMatrixFEDInstruction(null, in, out, opcode, str);\n}\nopcode = parseUnaryInstruction(str, in, out);\nreturn new UnaryMatrixFEDInstruction(InstructionUtils.parseUnaryOperator(opcode), in, out, opcode, str);\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Add missing unary support federated Add missing support for log and sigmoid for unary operations federated. This check is a basic copy of the CP Unary operations, but if it is possible to execute locally that unary operation should be possible federated.
49,706
27.04.2021 15:39:01
-7,200
e5253fc6151dbb070a05369a4c38ff87edd7732c
logcosh loss function add new loss function to nn package called logcosh it is a loss function usually used in regression, calculating loss via: loss = log(cosh(pred - labels))
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/nn/layers/logcosh_loss.dml", "diff": "+#-------------------------------------------------------------\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+/*\n+ * Logarithm of the hyperbolic cosine of the prediction error.\n+ */\n+\n+forward = function(matrix[double] pred, matrix[double] y)\n+ return (double loss) {\n+ /*\n+ * Computes the forward pass for an logcos loss function. The inputs\n+ * consist of N examples, each with M dimensions to predict.\n+ *\n+ * ```\n+ * L = sum( log(cosh(p_i - y_i)) for i=1 to N) / N\n+ * ```\n+ *\n+ * Inputs:\n+ * - pred: Predictions, of shape (N, M).\n+ * - y: Targets, of shape (N, M).\n+ *\n+ * Outputs:\n+ * - loss: Average loss.\n+ */\n+ N = nrow(y)\n+ losses = log(cosh(pred - y))\n+ loss = sum(losses) / N\n+}\n+\n+backward = function(matrix[double] pred, matrix[double] y)\n+ return (matrix[double] dpred) {\n+ /*\n+ * Computes the backward pass for an logcosh loss function. The inputs\n+ * consist of N examples, each with M dimensions to predict.\n+ *\n+ * Inputs:\n+ * - pred: Predictions, of shape (N, M).\n+ * - y: Targets, of shape (N, M).\n+ *\n+ * Outputs:\n+ * - dpred: Gradient wrt `pred`, of shape (N, M).\n+ */\n+\n+ N = nrow(y)\n+ # the derivative of log(cosh(x)) is tanh(x)\n+ dpred = tanh(pred-y) / N\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/FunctionOp.java", "new_path": "src/main/java/org/apache/sysds/hops/FunctionOp.java", "diff": "@@ -384,4 +384,9 @@ public class FunctionOp extends Hop\npublic boolean compare(Hop that) {\nreturn false;\n}\n+\n+ @Override\n+ public String toString(){\n+ return getOpString();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/ipa/FunctionCallGraph.java", "new_path": "src/main/java/org/apache/sysds/hops/ipa/FunctionCallGraph.java", "diff": "@@ -29,6 +29,7 @@ import java.util.Set;\nimport java.util.Stack;\nimport java.util.stream.Collectors;\n+import org.apache.sysds.api.DMLException;\nimport org.apache.sysds.common.Types.OpOp1;\nimport org.apache.sysds.common.Types.OpOpData;\nimport org.apache.sysds.common.Types.OpOpN;\n@@ -451,6 +452,7 @@ public class FunctionCallGraph\n}\nprivate boolean addFunctionOpToGraph(FunctionOp fop, String fkey, StatementBlock sb, Stack<String> fstack, HashSet<String> lfset) {\n+ try{\nboolean ret = false;\nString lfkey = fop.getFunctionKey();\n//keep all function operators\n@@ -470,6 +472,7 @@ public class FunctionCallGraph\n//recursively construct function call dag\nif( !fstack.contains(lfkey) ) {\n+\nfstack.push(lfkey);\n_fGraph.get(fkey).add(lfkey);\nFunctionStatementBlock fsb = sb.getDMLProg()\n@@ -478,6 +481,7 @@ public class FunctionCallGraph\nfor( StatementBlock csb : fs.getBody() )\nret |= rConstructFunctionCallGraph(lfkey, csb, fstack, new HashSet<String>());\nfstack.pop();\n+\n}\n//recursive function call\nelse {\n@@ -494,6 +498,10 @@ public class FunctionCallGraph\nlfset.add( lfkey );\nreturn ret;\n}\n+ catch(Exception e){\n+ throw new DMLException(\"failed add function to graph \" + fop + \" \" + fkey , e );\n+ }\n+ }\nprivate boolean rAnalyzeSecondOrderCall(StatementBlock sb) {\nboolean ret = false;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixAgg.java", "new_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixAgg.java", "diff": "@@ -1143,7 +1143,7 @@ public class LibMatrixAgg\n}\nprivate static void aggregateBinaryMatrixLastRowDenseGeneric(MatrixBlock in, MatrixBlock aggVal) {\n- if( in.denseBlock==null || in.isEmptyBlock(false) )\n+ if( in.denseBlock==null || in.isEmptyBlock(false) || aggVal.isEmpty())\nreturn;\nfinal int m = in.rlen;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/applications/nn/NNComponentTest.java", "new_path": "src/test/java/org/apache/sysds/test/applications/nn/NNComponentTest.java", "diff": "@@ -108,6 +108,11 @@ public class NNComponentTest extends BaseTest {\nrun(\"transpose_NCHW_to_CNHW.dml\");\n}\n+ @Test\n+ public void logcosh(){\n+ run(\"logcosh.dml\");\n+ }\n+\n@Override\nprotected void run(String name) {\nsuper.run(\"component/\" + name);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/applications/nn/component/logcosh.dml", "diff": "+#-------------------------------------------------------------\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+source(\"scripts/nn/layers/logcosh_loss.dml\") as logcosh\n+\n+logcosh_test_1 = function(){\n+ X = rand(rows = 3, cols = 3, pdf = \"normal\")\n+ labels = X\n+ loss = logcosh::forward(X, labels)\n+ if( loss > 1e-10)\n+ print(\"ERROR: Loss of perfect predictions should be equal to 0 but was \" + loss)\n+}\n+\n+logcosh_test_2 = function(){\n+ X = rand(rows = 3, cols = 1, pdf = \"normal\")\n+ labels_1 = X + 1\n+ labels_2 = X - 1\n+ loss_1 = logcosh::forward(X, labels_1)\n+ loss_2 = logcosh::forward(X, labels_2)\n+ if( loss_1 - loss_2 > 1e-10)\n+ print(\"ERROR: Loss for values predicted above and below by same margin should be exactly the same loss \" + loss_1 + \" : \" + loss_2)\n+}\n+\n+logcosh_test_3 = function(){\n+ X = rand(rows = 6, cols = 2, pdf = \"normal\")\n+ labels_1 = X + 1\n+ labels_2 = X - 1\n+ gradient_1 = sum(logcosh::backward(X, labels_1))\n+ gradient_2 = sum(logcosh::backward(X, labels_2))\n+ if(gradient_1 > 0)\n+ print(\"ERROR: gradients should point negatively if prediction is to high\")\n+ if(gradient_2 < 0)\n+ print(\"ERROR: gradients should point positivly if prediction is to low\")\n+}\n+\n+logcosh_test_1()\n+logcosh_test_2()\n+logcosh_test_3()\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2952] logcosh loss function add new loss function to nn package called logcosh it is a loss function usually used in regression, calculating loss via: loss = log(cosh(pred - labels))
49,720
27.04.2021 20:29:54
-7,200
4e7c63ec3ec6ac4c40e42001d680713d627e71d1
[MINOR] Few minor fixes (Warning and string comparison in FrameBlock and formatting fixes in FrameMapTest.java)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/matrix/data/FrameBlock.java", "new_path": "src/main/java/org/apache/sysds/runtime/matrix/data/FrameBlock.java", "diff": "@@ -785,7 +785,7 @@ public class FrameBlock implements CacheBlock, Externalizable {\n}\n@Override\n- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {\n+ public void readExternal(ObjectInput in) throws IOException {\n//redirect deserialization to writable impl\nreadFields(in);\n}\n@@ -2051,8 +2051,10 @@ public class FrameBlock implements CacheBlock, Externalizable {\nValueType dataType = isType(dataValue);\n- if(!dataType.toString().contains(type) && !(dataType == ValueType.BOOLEAN && type == \"INT\") && !(dataType == ValueType.BOOLEAN && type == \"FP\")){\n- LOG.warn(\"Datatype detected: \" + dataType + \" where expected: \" + schemaString[i] + \" col: \" + (i+1) + \", row:\" +(j+1));\n+ if(!dataType.toString().contains(type) && !(dataType == ValueType.BOOLEAN && type.equals(\"INT\")) &&\n+ !(dataType == ValueType.BOOLEAN && type.equals(\"FP\"))){\n+ LOG.warn(\"Datatype detected: \" + dataType + \" where expected: \" + schemaString[i] + \" col: \" +\n+ (i+1) + \", row:\" +(j+1));\nthis.set(j,i,null);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/frame/FrameDropInvalidTypeTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/frame/FrameDropInvalidTypeTest.java", "diff": "@@ -62,7 +62,7 @@ public class FrameDropInvalidTypeTest extends AutomatedTestBase\nTestUtils.clearAssertionInformation();\naddTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {\"B\"}));\nif (TEST_CACHE_ENABLED) {\n- setOutAndExpectedDeletionDisabled(true);\n+// setOutAndExpectedDeletionDisabled(true);\n}\n}\n@@ -108,6 +108,12 @@ public class FrameDropInvalidTypeTest extends AutomatedTestBase\nrunIsCorrectTest(schemaStrings, rows, schemaStrings.length, 5, 4, LopProperties.ExecType.CP, true);\n}\n+ @Test\n+ public void testIntInBool() {\n+ // This test now verifies that changing from INT32 to INT64 is okay.\n+ runIsCorrectTest(schemaStrings, rows, schemaStrings.length, 5, 5, LopProperties.ExecType.CP, true);\n+ }\n+\n@Test\npublic void testLongInIntSpark() {\n// This test now verifies that changing from INT32 to INT64 is okay.\n@@ -179,6 +185,16 @@ public class FrameDropInvalidTypeTest extends AutomatedTestBase\nmeta[meta.length - 1] = \"INT32\";\nbreak;\n}\n+ case 5: { // int in bool\n+ String[] tmp1 = new String[rows];\n+ for (int i = 0; i < rows; i++)\n+ tmp1[i] = \"true\";\n+ for (int i = 0; i < badValues; i++)\n+ tmp1[i] = \"1\";\n+ frame1.appendColumn(tmp1);\n+ meta[meta.length - 1] = \"BOOLEAN\";\n+ break;\n+ }\n}\nwriter.writeFrameToHDFS(\nframe1.slice(0, rows - 1, 0, 1, new FrameBlock()),\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Few minor fixes (Warning and string comparison in FrameBlock and formatting fixes in FrameMapTest.java)
49,720
27.04.2021 22:17:04
-7,200
233f30d778249ea3b83010bb902da964d1955d43
[MINOR] Merging crossv.dml and frameRemoveEmpty.dml into utils.dml
[ { "change_type": "DELETE", "old_path": "scripts/pipelines/scripts/crossV.dml", "new_path": null, "diff": "-#-------------------------------------------------------------\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-classifyDirty = function(Matrix[Double] Xtrain, Matrix[Double] ytrain, Matrix[Double] opt,\n- Matrix[Double] mask, Boolean isWeighted = TRUE, Integer cv)\n- return (Double accuracy)\n-{\n- # classify without cleaning fill with edfault values 1\n- Xtrain = replace(target = Xtrain, pattern = NaN, replacement=1)\n-\n- dX_train = dummycoding(Xtrain, mask)\n-\n- accuracy = crossV(Xtrain, ytrain, cv, mask, opt, isWeighted)\n- accuracy = mean(accuracy)\n-\n- # # learn model\n- # B = multiLogReg(X=dX_train, Y=ytrain, icpt=2, reg=as.scalar(opt[1,1]), maxi = as.scalar(opt[1,2]), maxii= 0, verbose=FALSE);\n- # [M,pred,accuracy] = multiLogRegPredict(X=dX_test, B=B, Y=ytest, verbose=FALSE);\n-\n- # if(isWeighted)\n- # accuracy = getAccuracy(y=ytest, yhat=pred, isWeighted=isWeighted)\n- print(\"cross validated dirty accuracy \"+accuracy)\n-}\n-\n-\n-crossV = function(Matrix[double] X, Matrix[double] y, Integer k, Matrix[Double] mask,\n- Matrix[Double] MLhp, Boolean isWeighted)\n-return (Matrix[Double] accuracyMatrix)\n-{\n-\n- accuracyMatrix = matrix(0, k, 1)\n-\n- dataList = list()\n- testL = list()\n- data = order(target = cbind(y, X), by = 1, decreasing=FALSE, index.return=FALSE)\n- classes = table(data[, 1], 1)\n- ins_per_fold = classes/k\n- start_fold = matrix(1, rows=nrow(ins_per_fold), cols=1)\n- fold_idxes = cbind(start_fold, ins_per_fold)\n-\n- start_i = 0; end_i = 0; idx_fold = 1;;\n- for(i in 1:k)\n- {\n- fold_i = matrix(0, 0, ncol(data))\n- start=0; end=0;\n- for(j in 1:nrow(classes))\n- {\n- idx = as.scalar(classes[j, 1])\n- start = end + 1;\n- end = end + idx\n- class_j = data[start:end, ]\n-\n-\n- start_i = as.scalar(fold_idxes[j, 1]);\n- end_i = as.scalar(fold_idxes[j, 2])\n-\n- fold_i = rbind(fold_i, class_j[start_i:end_i, ])\n- }\n-\n- dataList = append(dataList, fold_i)\n- fold_idxes[, 1] = fold_idxes[, 2] + 1\n- fold_idxes[, 2] += ins_per_fold\n- while(FALSE){}\n- }\n-\n- for(i in seq(1,k))\n- {\n- [trainList, hold_out] = remove(dataList, i)\n- trainset = rbind(trainList)\n- testset = as.matrix(hold_out)\n- trainX = trainset[, 2:ncol(trainset)]\n- trainy = trainset[, 1]\n- testX = testset[, 2:ncol(testset)]\n- testy = testset[, 1]\n- beta = multiLogReg(X=trainX, Y=trainy, icpt=1, reg=as.scalar(MLhp[1,1]), tol= 1e-9,\n- maxi=as.scalar(MLhp[1,2]), maxii= 50, verbose=FALSE);\n- [prob, yhat, a] = multiLogRegPredict(testX, beta, testy, FALSE)\n- accuracy = getAccuracy(testy, yhat, isWeighted)\n- accuracyMatrix[i] = accuracy\n- }\n-\n-}\n-\n-\n-\n" }, { "change_type": "DELETE", "old_path": "scripts/pipelines/scripts/frameRemoveEmpty.dml", "new_path": null, "diff": "-#-------------------------------------------------------------\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-\n-\n-# remove empty wrapper for frames\n-frameRemoveEmpty = function(Frame[Unknown] target, String margin, Matrix[Double] select)\n-return (Frame[Unknown] frameblock)\n-{\n- idx = seq(1, ncol(target))\n- # get the indexes of columns for recode transformation\n- index = vectorToCsv(idx)\n- # recode logical pipelines for easy handling\n- jspecR = \"{ids:true, recode:[\"+index+\"]}\";\n- [X, M] = transformencode(target=target, spec=jspecR);\n- X = removeEmpty(target = X, margin = margin, select = select)\n- frameblock = transformdecode(target = X, spec = jspecR, meta = M)\n-}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/pipelines/testClassification.dml", "new_path": "src/test/scripts/functions/pipelines/testClassification.dml", "diff": "@@ -59,7 +59,7 @@ X = dropInvalidType(F, getSchema)\nif(sum(getMask) > 0)\n{\n# always recode the label\n- index = utils::vectorToCsv(getMask)\n+ index = vectorToCsv(getMask)\njspecR = \"{ids:true, recode:[\"+index+\"]}\"\n[eX, X_meta] = transformencode(target=X, spec=jspecR);\n# change the schema to reflect the encoded values\n@@ -88,7 +88,7 @@ allLgs = logical::transformLogical(lgSeed)\nd_accuracy = 0\n# 4. perform the sampling\n-[eX, eY] = utils::doSample(eX, eY, sample)\n+[eX, eY] = doSample(eX, eY, sample)\n# 5. get train test and validation set with balanced class distribution\n# [X_train, y_train, X_test, y_test] = splitBalanced(X=eX, Y=eY, splitRatio=0.7, verbose=FALSE)\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Merging crossv.dml and frameRemoveEmpty.dml into utils.dml
49,738
27.04.2021 22:28:07
-7,200
4fc8691aa6b8cb986cc8457eeec4ab6e5ba6da1a
Fix federated binary matrix-vector operators This patch fixes a special case of federated matrix-vector operators with row/column vector broadcasting of 1x1 vectors and adds a related test. Furthermore, this also includes a cleanup for various warnings and a fix for correct federated csv read (using the new metadata handling).
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/CompressedMatrixBlockFactory.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/CompressedMatrixBlockFactory.java", "diff": "@@ -232,11 +232,11 @@ public class CompressedMatrixBlockFactory {\nlogPhase();\n}\n- private AColGroup combineEmpty(List<AColGroup> e) {\n+ private static AColGroup combineEmpty(List<AColGroup> e) {\nreturn new ColGroupEmpty(combineColIndexes(e), e.get(0).getNumRows());\n}\n- private AColGroup combineConst(List<AColGroup> c) {\n+ private static AColGroup combineConst(List<AColGroup> c) {\nint[] resCols = combineColIndexes(c);\ndouble[] values = new double[resCols.length];\n@@ -257,7 +257,7 @@ public class CompressedMatrixBlockFactory {\nreturn new ColGroupConst(resCols, c.get(0).getNumRows(), dict);\n}\n- private int[] combineColIndexes(List<AColGroup> gs) {\n+ private static int[] combineColIndexes(List<AColGroup> gs) {\nint numCols = 0;\nfor(AColGroup g : gs)\nnumCols += g.getNumCols();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/cocode/PlanningCoCoder.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/cocode/PlanningCoCoder.java", "diff": "@@ -200,7 +200,7 @@ public class PlanningCoCoder {\nprivate int st1 = 0, st2 = 0, st3 = 0, st4 = 0;\npublic Memorizer() {\n- mem = new HashMap<ColIndexes, CompressedSizeInfoColGroup>();\n+ mem = new HashMap<>();\n}\npublic void put(CompressedSizeInfoColGroup g) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederatedWorkerHandler.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederatedWorkerHandler.java", "diff": "@@ -227,10 +227,8 @@ public class FederatedWorkerHandler extends ChannelInboundHandlerAdapter {\n// put meta data object in symbol table, read on first operation\ncd.setMetaData(new MetaDataFormat(mc, fmt));\n- // TODO send FileFormatProperties with request and use them for CSV, this is currently a workaround so reading\n- // of CSV files works\nif(fmt == FileFormat.CSV)\n- cd.setFileFormatProperties(new FileFormatPropertiesCSV(header, DataExpression.DEFAULT_DELIM_DELIMITER,\n+ cd.setFileFormatProperties(new FileFormatPropertiesCSV(header, delim,\nDataExpression.DEFAULT_DELIM_SPARSE));\ncd.enableCleanup(false); // guard against deletion\n_ecm.get(tid).setVariable(String.valueOf(id), cd);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/BinaryMatrixMatrixFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/BinaryMatrixMatrixFEDInstruction.java", "diff": "@@ -29,7 +29,6 @@ import org.apache.sysds.runtime.instructions.cp.CPOperand;\nimport org.apache.sysds.runtime.matrix.operators.BinaryOperator;\nimport org.apache.sysds.runtime.matrix.operators.Operator;\n-\npublic class BinaryMatrixMatrixFEDInstruction extends BinaryFEDInstruction\n{\nprotected BinaryMatrixMatrixFEDInstruction(Operator op,\n@@ -85,8 +84,8 @@ public class BinaryMatrixMatrixFEDInstruction extends BinaryFEDInstruction\nthrow new DMLRuntimeException(\"Matrix-matrix binary operations with a full partitioned federated input with multiple partitions are not supported yet.\");\n}\n}\n- else if((mo1.isFederated(FType.ROW) && mo2.getNumRows() == 1 && mo2.getNumColumns() > 1)\n- || (mo1.isFederated(FType.COL) && mo2.getNumRows() > 1 && mo2.getNumColumns() == 1)) {\n+ else if((mo1.isFederated(FType.ROW) && mo2.getNumRows() == 1) //matrix-rowVect\n+ || (mo1.isFederated(FType.COL) && mo2.getNumColumns() == 1)) { //matrix-colVect\n// MV row partitioned row vector, MV col partitioned col vector\nFederatedRequest fr1 = mo1.getFedMapping().broadcast(mo2);\nfr2 = FederationUtils.callInstruction(instString, output, new CPOperand[]{input1, input2},\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/CtableFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/CtableFEDInstruction.java", "diff": "@@ -50,16 +50,16 @@ import org.apache.sysds.runtime.matrix.operators.BinaryOperator;\npublic class CtableFEDInstruction extends ComputationFEDInstruction {\nprivate final CPOperand _outDim1;\nprivate final CPOperand _outDim2;\n- private final boolean _isExpand;\n- private final boolean _ignoreZeros;\n+ //private final boolean _isExpand;\n+ //private final boolean _ignoreZeros;\nprivate CtableFEDInstruction(CPOperand in1, CPOperand in2, CPOperand in3, CPOperand out, String outputDim1, boolean dim1Literal, String outputDim2, boolean dim2Literal, boolean isExpand,\nboolean ignoreZeros, String opcode, String istr) {\nsuper(FEDType.Ctable, null, in1, in2, in3, out, opcode, istr);\n_outDim1 = new CPOperand(outputDim1, ValueType.FP64, DataType.SCALAR, dim1Literal);\n_outDim2 = new CPOperand(outputDim2, ValueType.FP64, DataType.SCALAR, dim2Literal);\n- _isExpand = isExpand;\n- _ignoreZeros = ignoreZeros;\n+ //_isExpand = isExpand;\n+ //_ignoreZeros = ignoreZeros;\n}\npublic static CtableFEDInstruction parseInstruction(String inst) {\n@@ -199,7 +199,7 @@ public class CtableFEDInstruction extends ComputationFEDInstruction {\n}\n- private void setFedOutput(MatrixObject mo1, MatrixObject out, FederationMap fedMap, Long[] dims1, long outId) {\n+ private static void setFedOutput(MatrixObject mo1, MatrixObject out, FederationMap fedMap, Long[] dims1, long outId) {\nlong fedSize = Collections.max(Arrays.asList(dims1), Long::compare) / dims1.length;\nlong d1 = Collections.max(Arrays.asList(dims1), Long::compare);\n@@ -225,7 +225,7 @@ public class CtableFEDInstruction extends ComputationFEDInstruction {\n});\n}\n- private MatrixBlock aggResult(Future<FederatedResponse>[] ffr) {\n+ private static MatrixBlock aggResult(Future<FederatedResponse>[] ffr) {\nMatrixBlock resultBlock = new MatrixBlock(1, 1, 0);\nint dim1 = 0, dim2 = 0;\nfor(int i = 0; i < ffr.length; i++) {\n@@ -252,7 +252,7 @@ public class CtableFEDInstruction extends ComputationFEDInstruction {\nreturn resultBlock;\n}\n- private FederationMap modifyFedRanges(FederationMap fedMap, Long[] dims1, Long[] dims2) {\n+ private static FederationMap modifyFedRanges(FederationMap fedMap, Long[] dims1, Long[] dims2) {\nIntStream.range(0, fedMap.getFederatedRanges().length).forEach(i -> {\nfedMap.getFederatedRanges()[i]\n.setBeginDim(0, i == 0 ? 0 : fedMap.getFederatedRanges()[i - 1].getEndDims()[0]);\n@@ -291,7 +291,7 @@ public class CtableFEDInstruction extends ComputationFEDInstruction {\nreturn computeOutputDims(tmp);\n}\n- private Long[] computeOutputDims(Future<FederatedResponse>[] tmp) {\n+ private static Long[] computeOutputDims(Future<FederatedResponse>[] tmp) {\nLong[] fedDims = new Long[tmp.length];\nfor(int i = 0; i < tmp.length; i ++)\ntry {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/TernaryFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/TernaryFEDInstruction.java", "diff": "@@ -199,7 +199,7 @@ public class TernaryFEDInstruction extends ComputationFEDInstruction {\n* @param fedRequest1 federated request to occur after array\n* @return federated requests collected in a single array\n*/\n- private FederatedRequest[] collectRequests(FederatedRequest[] fedRequests, FederatedRequest fedRequest1){\n+ private static FederatedRequest[] collectRequests(FederatedRequest[] fedRequests, FederatedRequest fedRequest1){\nFederatedRequest[] allRequests = new FederatedRequest[fedRequests.length + 1];\nfor ( int i = 0; i < fedRequests.length; i++ )\nallRequests[i] = fedRequests[i];\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/meta/MetaDataAll.java", "new_path": "src/main/java/org/apache/sysds/runtime/meta/MetaDataAll.java", "diff": "@@ -139,6 +139,7 @@ public class MetaDataAll extends DataIdentifier {\nreturn retVal;\n}\n+ @SuppressWarnings(\"unchecked\")\nprivate void parseMetaDataParams()\n{\nfor( Object obj : _metaObj.entrySet() ){\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/AutomatedTestBase.java", "new_path": "src/test/java/org/apache/sysds/test/AutomatedTestBase.java", "diff": "@@ -87,7 +87,6 @@ import org.apache.sysds.runtime.util.HDFSTool;\nimport org.apache.sysds.utils.ParameterBuilder;\nimport org.apache.sysds.utils.Statistics;\nimport org.apache.wink.json4j.JSONException;\n-import org.apache.wink.json4j.JSONObject;\nimport org.junit.After;\nimport org.junit.Assert;\nimport org.junit.Before;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedBinaryVectorTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedBinaryVectorTest.java", "diff": "@@ -58,10 +58,8 @@ public class FederatedBinaryVectorTest extends AutomatedTestBase {\npublic static Collection<Object[]> data() {\n// rows have to be even and > 1\nreturn Arrays.asList(new Object[][] {\n- // {2, 1000},\n- // {10, 100},\n{100, 10},\n- // {1000, 1}, {10, 2000}, {2000, 10}\n+ {100, 1},\n});\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/privacy/ReadWriteTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/privacy/ReadWriteTest.java", "diff": "@@ -21,7 +21,6 @@ package org.apache.sysds.test.functions.privacy;\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertNotNull;\n-import static org.junit.Assert.assertTrue;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\n@@ -29,7 +28,6 @@ import java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\n-import org.apache.sysds.parser.DataExpression;\nimport org.apache.sysds.runtime.meta.MatrixCharacteristics;\nimport org.apache.sysds.runtime.meta.MetaDataAll;\nimport org.apache.sysds.runtime.privacy.PrivacyConstraint;\n@@ -39,7 +37,6 @@ import org.apache.sysds.runtime.privacy.finegrained.FineGrainedPrivacy;\nimport org.apache.sysds.runtime.privacy.finegrained.FineGrainedPrivacyList;\nimport org.apache.sysds.test.AutomatedTestBase;\nimport org.apache.sysds.test.TestConfiguration;\n-import org.apache.wink.json4j.JSONObject;\nimport org.junit.Assert;\nimport org.junit.Test;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/privacy/ScalarPropagationTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/privacy/ScalarPropagationTest.java", "diff": "@@ -33,7 +33,6 @@ import org.apache.sysds.runtime.privacy.PrivacyConstraint.PrivacyLevel;\nimport org.apache.sysds.test.AutomatedTestBase;\nimport org.apache.sysds.test.TestConfiguration;\nimport org.apache.sysds.test.TestUtils;\n-import org.apache.wink.json4j.JSONObject;\npublic class ScalarPropagationTest extends AutomatedTestBase\n{\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2955] Fix federated binary matrix-vector operators This patch fixes a special case of federated matrix-vector operators with row/column vector broadcasting of 1x1 vectors and adds a related test. Furthermore, this also includes a cleanup for various warnings and a fix for correct federated csv read (using the new metadata handling).
49,706
28.04.2021 10:41:10
-7,200
d663d2d1e28d657382bf2ffc2209940d807ede65
[MINOR] fix bug introduced in
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixAgg.java", "new_path": "src/main/java/org/apache/sysds/runtime/matrix/data/LibMatrixAgg.java", "diff": "@@ -1143,7 +1143,7 @@ public class LibMatrixAgg\n}\nprivate static void aggregateBinaryMatrixLastRowDenseGeneric(MatrixBlock in, MatrixBlock aggVal) {\n- if( in.denseBlock==null || in.isEmptyBlock(false) || aggVal.isEmpty())\n+ if( in.denseBlock==null || in.isEmptyBlock(false))\nreturn;\nfinal int m = in.rlen;\n@@ -1153,21 +1153,25 @@ public class LibMatrixAgg\ndouble[] a = in.getDenseBlockValues();\n- if(aggVal.isInSparseFormat()){\n- // If for some reason the agg Val is sparse then force it to dence, since the values that are going to be added\n+ if(aggVal.isEmpty()){\n+ aggVal.allocateDenseBlock();\n+ aggVal.setNonZeros(in.getNonZeros());\n+ }\n+ else if(aggVal.isInSparseFormat()){\n+ // If for some reason the agg Val is sparse then force it to dence,\n+ // since the values that are going to be added\n// will make it dense anyway.\naggVal.sparseToDense();\naggVal.setNonZeros(in.getNonZeros());\n- if(aggVal.denseBlock == null){\n+ if(aggVal.denseBlock == null)\naggVal.allocateDenseBlock();\n}\n- }\ndouble[] t = aggVal.getDenseBlockValues();\nKahanObject buffer = new KahanObject(0, 0);\nKahanPlus akplus = KahanPlus.getKahanPlusFnObject();\n- // Dont include nnz maintenence since this function most likely aggregate more than one matrixblock.\n+ // Don't include nnz maintenence since this function most likely aggregate more than one matrixblock.\n// j is the pointer to column.\n// c is the pointer to correction.\n@@ -1193,6 +1197,11 @@ public class LibMatrixAgg\nfinal int m = in.rlen;\nfinal int rlen = Math.min(a.numRows(), m);\n+ if(aggVal.isEmpty()){\n+ aggVal.allocateSparseRowsBlock();\n+ aggVal.setNonZeros(in.getNonZeros());\n+ }\n+\nfor( int i=0; i<rlen-1; i++ )\n{\nif( !a.isEmpty(i) )\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] fix bug introduced in SYSTEMDS-2952
49,706
28.04.2021 13:04:39
-7,200
15c2e812d9c1c113bb05392ea4ab32e518b6e859
Cleanup Move homes data to resources folder. generate algorithms again, to fix merge issue.
[ { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/algorithm/__init__.py", "new_path": "src/main/python/systemds/operator/algorithm/__init__.py", "diff": "@@ -41,6 +41,7 @@ from .builtin.dbscan import dbscan\nfrom .builtin.decisionTree import decisionTree\nfrom .builtin.discoverFD import discoverFD\nfrom .builtin.dist import dist\n+from .builtin.gaussianClassifier import gaussianClassifier\nfrom .builtin.getAccuracy import getAccuracy\nfrom .builtin.glm import glm\nfrom .builtin.gmm import gmm\n@@ -61,6 +62,7 @@ from .builtin.kmeans import kmeans\nfrom .builtin.kmeansPredict import kmeansPredict\nfrom .builtin.knnbf import knnbf\nfrom .builtin.l2svm import l2svm\n+from .builtin.l2svmPredict import l2svmPredict\nfrom .builtin.lasso import lasso\nfrom .builtin.lm import lm\nfrom .builtin.lmCG import lmCG\n@@ -93,6 +95,7 @@ from .builtin.splitBalanced import splitBalanced\nfrom .builtin.statsNA import statsNA\nfrom .builtin.steplm import steplm\nfrom .builtin.toOneHot import toOneHot\n+from .builtin.tomeklink import tomeklink\nfrom .builtin.univar import univar\nfrom .builtin.vectorToCsv import vectorToCsv\nfrom .builtin.winsorize import winsorize\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/python/tests/frame/__init__.py", "diff": "+# -------------------------------------------------------------\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" }, { "change_type": "DELETE", "old_path": "src/main/python/tests/frame/data/homes.csv", "new_path": null, "diff": "-zipcode,district,sqft,numbedrooms,numbathrooms,floors,view,saleprice,askingprice\n-95141,west,1373,7,1,3,FALSE,695,698\n-91312,south,3261,6,2,2,FALSE,902,906\n-94555,north,1835,3,3,3,TRUE,888,892\n-95141,east,2833,6,2.5,2,TRUE,927,932\n-96334,south,2742,6,2.5,2,FALSE,872,876\n-96334,north,2195,5,2.5,2,FALSE,799,803\n-98755,north,3469,7,2.5,2,FALSE,958,963\n-96334,west,1685,7,1.5,2,TRUE,757,760\n-95141,west,2238,4,3,3,FALSE,894,899\n-91312,west,1245,4,1,1,FALSE,547,549\n-98755,south,3702,7,3,1,FALSE,959,964\n-98755,north,1865,7,1,2,TRUE,742,745\n-94555,north,3837,3,1,1,FALSE,839,842\n-91312,west,2139,3,1,3,TRUE,820,824\n-95141,north,3824,4,3,1,FALSE,954,958\n-98755,east,2858,5,1.5,1,FALSE,759,762\n-91312,south,1827,7,3,1,FALSE,735,738\n-91312,south,3557,2,2.5,1,FALSE,888,892\n-91312,south,2553,2,2.5,2,TRUE,884,889\n-96334,west,1682,3,1.5,1,FALSE,625,628\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/tests/frame/test_transform_apply.py", "new_path": "src/main/python/tests/frame/test_transform_apply.py", "diff": "@@ -35,8 +35,9 @@ from systemds.matrix import Matrix\nclass TestTransformApply(unittest.TestCase):\nsds: SystemDSContext = None\n- HOMES_PATH = \"tests/frame/data/homes.csv\"\n+ HOMES_PATH = \"../../test/resources/datasets/homes/homes.csv\"\nHOMES_SCHEMA = '\"int,string,int,int,double,int,boolean,int,int\"'\n+ JSPEC_PATH = \"../../test/resources/datasets/homes/homes.tfspec_bin2.json\"\n@classmethod\ndef setUpClass(cls):\n@@ -50,8 +51,7 @@ class TestTransformApply(unittest.TestCase):\npass\ndef test_apply_recode_bin(self):\n- JSPEC_PATH = \"tests/frame/data/homes.tfspec_bin2.json\"\n- with open(JSPEC_PATH) as jspec_file:\n+ with open(self.JSPEC_PATH) as jspec_file:\nJSPEC = json.load(jspec_file)\nF1 = self.sds.read(\nself.HOMES_PATH,\n@@ -61,7 +61,7 @@ class TestTransformApply(unittest.TestCase):\nheader=True,\n)\npd_F1 = F1.compute()\n- jspec = self.sds.read(JSPEC_PATH, data_type=\"scalar\", value_type=\"string\")\n+ jspec = self.sds.read(self.JSPEC_PATH, data_type=\"scalar\", value_type=\"string\")\nX, M = F1.transform_encode(spec=jspec).compute()\nself.assertTrue(isinstance(X, np.ndarray))\nself.assertTrue(isinstance(M, pd.DataFrame))\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/tests/frame/test_transform_encode.py", "new_path": "src/main/python/tests/frame/test_transform_encode.py", "diff": "@@ -35,8 +35,9 @@ from systemds.matrix import Matrix\nclass TestTransformEncode(unittest.TestCase):\nsds: SystemDSContext = None\n- HOMES_PATH = \"tests/frame/data/homes.csv\"\n+ HOMES_PATH = \"../../test/resources/datasets/homes/homes.csv\"\nHOMES_SCHEMA = '\"int,string,int,int,double,int,boolean,int,int\"'\n+ JSPEC_PATH = \"../../test/resources/datasets/homes/homes.tfspec_recode2.json\"\n@classmethod\ndef setUpClass(cls):\n@@ -50,8 +51,7 @@ class TestTransformEncode(unittest.TestCase):\npass\ndef test_encode_recode(self):\n- JSPEC_PATH = \"tests/frame/data/homes.tfspec_recode2.json\"\n- with open(JSPEC_PATH) as jspec_file:\n+ with open(self.JSPEC_PATH) as jspec_file:\nJSPEC = json.load(jspec_file)\nF1 = self.sds.read(\nself.HOMES_PATH,\n@@ -61,7 +61,7 @@ class TestTransformEncode(unittest.TestCase):\nheader=True,\n)\npd_F1 = F1.compute()\n- jspec = self.sds.read(JSPEC_PATH, data_type=\"scalar\", value_type=\"string\")\n+ jspec = self.sds.read(self.JSPEC_PATH, data_type=\"scalar\", value_type=\"string\")\nX, M = F1.transform_encode(spec=jspec).compute()\nself.assertTrue(isinstance(X, np.ndarray))\nself.assertTrue(isinstance(M, pd.DataFrame))\n" }, { "change_type": "RENAME", "old_path": "src/main/python/tests/frame/data/homes.tfspec_bin2.json", "new_path": "src/test/resources/datasets/homes/homes.tfspec_bin2.json", "diff": "" }, { "change_type": "RENAME", "old_path": "src/main/python/tests/frame/data/homes.tfspec_recode2.json", "new_path": "src/test/resources/datasets/homes/homes.tfspec_recode2.json", "diff": "" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2882] Cleanup - Move homes data to resources folder. - generate algorithms again, to fix merge issue.
49,706
28.04.2021 13:54:02
-7,200
60bd6d7b956bebeadc092cd55211114d19b565f7
[MINOR] Disable Hyperband test if SYSTEMDS_ROOT not set
[ { "change_type": "MODIFY", "old_path": "src/main/python/tests/frame/test_hyperband.py", "new_path": "src/main/python/tests/frame/test_hyperband.py", "diff": "@@ -57,6 +57,7 @@ class TestHyperband(unittest.TestCase):\npass\ndef test_hyperband(self):\n+ if \"SYSTEMDS_ROOT\" in os.environ:\nx_train = Matrix(self.sds, self.X_train)\ny_train = Matrix(self.sds, self.y_train)\nx_val = Matrix(self.sds, self.X_val)\n@@ -80,6 +81,8 @@ class TestHyperband(unittest.TestCase):\nself.assertTrue(opt_hyper_params_df.shape[1] == 1)\nfor i, hyper_param in enumerate(opt_hyper_params_df.values.flatten().tolist()):\nself.assertTrue(self.min_max_params[i][0] <= hyper_param <= self.min_max_params[i][1])\n+ else:\n+ print(\"to enable hyperband tests, set SYSTEMDS_ROOT\")\nif __name__ == \"__main__\":\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Disable Hyperband test if SYSTEMDS_ROOT not set
49,706
29.04.2021 21:01:33
-7,200
686798f35d2e255fa446f80a427c9417300365ba
[MINOR] systemds binary singlenode default
[ { "change_type": "MODIFY", "old_path": "bin/systemds", "new_path": "bin/systemds", "diff": "@@ -39,9 +39,9 @@ if [ -z \"$SYSDS_QUIET\" ]; then\nSYSDS_QUIET=0\nfi\n-# if not set by env, set to hybrid execution by default\n+# if not set by env, set to singlenode execution by default\nif [[ -z \"$SYSDS_EXEC_MODE\" ]]; then\n- SYSDS_EXEC_MODE=hybrid\n+ SYSDS_EXEC_MODE=singlenode\nfi\n# an echo toggle\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] systemds binary singlenode default
49,706
30.04.2021 12:10:13
-7,200
5b22c4246cb88d7e63e99d7e1a463a255c0bc666
[MINOR] Force ytest argument in lmPredict This is not the ideal solution, but just to make the test pass the LMPredict now require ytest argument, The reason i simply because the python generators does not like default parameters on matrice arguments yet.
[ { "change_type": "MODIFY", "old_path": "docs/site/builtins-reference.md", "new_path": "docs/site/builtins-reference.md", "diff": "@@ -824,7 +824,7 @@ The `lmPredict`-function predicts the class of a feature vector.\n### Usage\n```r\n-lmPredict(X=X, B=w)\n+lmPredict(X=X, B=w, ytest= Y)\n```\n### Arguments\n@@ -833,7 +833,7 @@ lmPredict(X=X, B=w)\n| :------ | :------------- | -------- | :---------- |\n| X | Matrix[Double] | required | Matrix of feature vector(s). |\n| B | Matrix[Double] | required | 1-column matrix of weights. |\n-| ytest | Matrix[Double] | optional | Optional test labels, used only for verbose output. |\n+| ytest | Matrix[Double] | required | test labels, used only for verbose output. can be set to matrix(0,1,1) if verbose output is not wanted |\n| icpt | Integer | 0 | Intercept presence, shifting and rescaling of X ([Details](#icpt-argument))|\n| verbose | Boolean | FALSE | Print various statistics for evaluating accuracy. |\n@@ -850,7 +850,7 @@ lmPredict(X=X, B=w)\nX = rand (rows = 50, cols = 10)\ny = X %*% rand(rows = ncol(X), cols = 1)\nw = lm(X = X, y = y)\n-yp = lmPredict(X = X, B = w)\n+yp = lmPredict(X = X, B = w, ytest=matrix(0,1,1))\n```\n## `mice`-Function\n" }, { "change_type": "MODIFY", "old_path": "scripts/builtin/cvlm.dml", "new_path": "scripts/builtin/cvlm.dml", "diff": "@@ -42,7 +42,7 @@ m_cvlm = function(Matrix[Double] X, Matrix[Double] y, Integer k, Integer icpt =\n}\nbeta = lm(X=trainSet, y=trainRes, icpt=icpt, reg=reg);\n- pred = lmPredict(X=testSet, B=beta, icpt=icpt);\n+ pred = lmPredict(X=testSet, B=beta, ytest=matrix(0,1,1), icpt=icpt);\ny_predict[testS:testE,] = pred;\nallbeta[i,] = t(beta);\n}\n" }, { "change_type": "MODIFY", "old_path": "scripts/builtin/hyperband.dml", "new_path": "scripts/builtin/hyperband.dml", "diff": "@@ -104,7 +104,7 @@ m_hyperband = function(Matrix[Double] X_train, Matrix[Double] y_train,\ntol=as.scalar(args[1]), reg=as.scalar(args[2]), maxi=r_i, verbose=FALSE));\ncandidateWeights[curCandidate] = t(weights)\n- preds = lmPredict(X=X_val, B=weights);\n+ preds = lmPredict(X=X_val, B=weights, ytest= matrix(0,1,1));\nscoreboard[curCandidate,1] = as.matrix(sum((y_val - preds)^2));\n}\n" }, { "change_type": "MODIFY", "old_path": "scripts/builtin/mice.dml", "new_path": "scripts/builtin/mice.dml", "diff": "@@ -140,7 +140,7 @@ m_mice= function(Matrix[Double] X, Matrix[Double] cMask, Integer iter = 3,\n# learn a regression line\nbeta = lm(X=train_X, y=train_Y, verbose=FALSE, icpt=1, reg = 1e-7, tol = 1e-7);\n# predicting missing values\n- pred = lmPredict(X=test_X, B=beta, icpt=1)\n+ pred = lmPredict(X=test_X, B=beta, ytest= matrix(0,1,1), icpt=1)\n# imputing missing column values (assumes Mask_Filled being 0/1-matrix)\nR = removeEmpty(target=Mask_Filled[, in_c] * seq(1,n), margin=\"rows\");\n# TODO modify removeEmpty to return zero row and n columns\n" }, { "change_type": "MODIFY", "old_path": "scripts/builtin/outlierByArima.dml", "new_path": "scripts/builtin/outlierByArima.dml", "diff": "@@ -64,7 +64,7 @@ m_outlierByArima = function(Matrix[Double] X, Double k = 3, Integer repairMethod\n# TODO replace by ARIMA once fully supported, LM only emulated the AR part\nmodel = lm(X=features, y=X_adapted)\n- y_hat = lmPredict(X=features, B=model)\n+ y_hat = lmPredict(X=features, B=model, ytest=matrix(0,1,1))\nupperBound = sd(X) + k * y_hat\nlowerBound = sd(X) - k * y_hat\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/builtin/lmpredict.dml", "new_path": "src/test/scripts/functions/builtin/lmpredict.dml", "diff": "@@ -23,5 +23,5 @@ X = read($1) # Training data\ny = read($2) # response values\np = read($3) # random data to predict\nw = lmDS(X = X, y = y, icpt = 1, reg = 1e-12)\n-p = lmPredict(X = X, B = w, icpt = 1)\n+p = lmPredict(X = X, B = w, ytest=matrix(0,1,1), icpt = 1)\nwrite(p, $4)\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/lineage/LineageReuseAlg6.dml", "new_path": "src/test/scripts/functions/lineage/LineageReuseAlg6.dml", "diff": "@@ -89,7 +89,7 @@ Kc = floor(ncol(A) * 0.8);\nfor (i in 1:10) {\nnewA1 = PCA(A=A, K=Kc+i);\nbeta1 = lm(X=newA1, y=y, icpt=1, reg=0.0001, verbose=FALSE);\n- y_predict1 = lmPredict(X=newA1, B=beta1, icpt=1);\n+ y_predict1 = lmPredict(X=newA1, B=beta1, ytest=matrix(0,1,1), icpt=1);\nR2_ad1 = checkR2(newA1, y, y_predict1, beta1, 1);\nR[,i] = R2_ad1;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/recompile/IPAFunctionArgsFor.dml", "new_path": "src/test/scripts/functions/recompile/IPAFunctionArgsFor.dml", "diff": "@@ -92,7 +92,7 @@ Kc = floor(ncol(A) * 0.8);\nfor (i in 1:10) {\nnewA1 = PCA(A=A, K=Kc+i);\nbeta1 = lm(X=newA1, y=y, icpt=1, reg=0.0001, verbose=FALSE);\n- y_predict1 = lmPredict(X=newA1, B=beta1, icpt=1);\n+ y_predict1 = lmPredict(X=newA1, B=beta1, ytest=matrix(0,1,1), icpt=1);\nR2_ad1 = checkR2(newA1, y, y_predict1, beta1, 1);\nR[,i] = R2_ad1;\n}\n@@ -100,7 +100,7 @@ for (i in 1:10) {\nfor (i in 1:10) {\nnewA3 = PCA(A=A, K=Kc+5);\nbeta3 = lm(X=newA3, y=y, icpt=1, reg=0.001*i, verbose=FALSE);\n- y_predict3 = lmPredict(X=newA3, B=beta3, icpt=1);\n+ y_predict3 = lmPredict(X=newA3, B=beta3, ytest=matrix(0,1,1), icpt=1);\nR2_ad3 = checkR2(newA3, y, y_predict3, beta3, 1);\nR[,10+i] = R2_ad3;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/recompile/IPAFunctionArgsParfor.dml", "new_path": "src/test/scripts/functions/recompile/IPAFunctionArgsParfor.dml", "diff": "@@ -92,7 +92,7 @@ Kc = floor(ncol(A) * 0.8);\nfor (i in 1:10) {\nnewA1 = PCA(A=A, K=Kc+i);\nbeta1 = lm(X=newA1, y=y, icpt=1, reg=0.0001, verbose=FALSE);\n- y_predict1 = lmPredict(X=newA1, B=beta1, icpt=1);\n+ y_predict1 = lmPredict(X=newA1, B=beta1, ytest=matrix(0,1,1), icpt=1);\nR2_ad1 = checkR2(newA1, y, y_predict1, beta1, 1);\nR[,i] = R2_ad1;\n}\n@@ -100,7 +100,7 @@ for (i in 1:10) {\nparfor (i in 1:10) {\nnewA3 = PCA(A=A, K=Kc+5);\nbeta3 = lm(X=newA3, y=y, icpt=1, reg=0.001*i, verbose=FALSE);\n- y_predict3 = lmPredict(X=newA3, B=beta3, icpt=1);\n+ y_predict3 = lmPredict(X=newA3, B=beta3, ytest=matrix(0,1,1), icpt=1);\nR2_ad3 = checkR2(newA3, y, y_predict3, beta3, 1);\nR[,10+i] = R2_ad3;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Force ytest argument in lmPredict This is not the ideal solution, but just to make the test pass the LMPredict now require ytest argument, The reason i simply because the python generators does not like default parameters on matrice arguments yet.
49,686
01.05.2021 21:12:17
-7,200
624a61229f9f744958faa310a9e80a86518b3c44
Add a predict function for Naive Bayes Closes
[ { "change_type": "MODIFY", "old_path": "docs/site/builtins-reference.md", "new_path": "docs/site/builtins-reference.md", "diff": "@@ -61,7 +61,8 @@ limitations under the License.\n* [`gnmf`-Function](#gnmf-function)\n* [`mdedup`-Function](#mdedup-function)\n* [`msvm`-Function](#msvm-function)\n- * [`naivebayes`-Function](#naivebayes-function)\n+ * [`naiveBayes`-Function](#naiveBayes-function)\n+ * [`naiveBayesPredict`-Function](#naiveBayesPredict-function)\n* [`outlier`-Function](#outlier-function)\n* [`toOneHot`-Function](#toOneHOt-function)\n* [`winsorize`-Function](#winsorize-function)\n@@ -1341,14 +1342,14 @@ H = rand(rows = 2, cols = ncol(X), min = -0.05, max = 0.05);\ngnmf(X = X, rnk = 2, eps = 10^-8, maxi = 10)\n```\n-## `naivebayes`-Function\n+## `naiveBayes`-Function\n-The `naivebayes`-function computes the class conditional probabilities and class priors.\n+The `naiveBayes`-function computes the class conditional probabilities and class priors.\n### Usage\n```r\n-naivebayes(D, C, laplace, verbose)\n+naiveBayes(D, C, laplace, verbose)\n```\n### Arguments\n@@ -1372,7 +1373,38 @@ naivebayes(D, C, laplace, verbose)\n```r\nD=rand(rows=10,cols=1,min=10)\nC=rand(rows=10,cols=1,min=10)\n-[prior, classConditionals] = naivebayes(D, C, laplace = 1, verbose = TRUE)\n+[prior, classConditionals] = naiveBayes(D, C, laplace = 1, verbose = TRUE)\n+```\n+\n+## `naiveBaysePredict`-Function\n+\n+The `naiveBaysePredict`-function predicts the scoring with a naive Bayes model.\n+\n+### Usage\n+\n+```r\n+naiveBaysePredict(X=X, P=P, C=C)\n+```\n+\n+### Arguments\n+\n+| Name | Type | Default | Description |\n+| :------ | :------------- | -------- | :---------- |\n+| X | Matrix[Double] | required | Matrix of test data with N rows. |\n+| P | Matrix[Double] | required | Class priors, One dimensional column matrix with N rows. |\n+| C | Matrix[Double] | required | Class conditional probabilities, matrix with N rows. |\n+\n+### Returns\n+\n+| Type | Description |\n+| :------------- | :---------- |\n+| Matrix[Double] | A matrix containing the top-K item-ids with highest predicted ratings. |\n+| Matrix[Double] | A matrix containing predicted ratings. |\n+\n+### Example\n+\n+```r\n+[YRaw, Y] = naiveBaysePredict(X=data, P=model_prior, C=model_conditionals)\n```\n## `outlier`-Function\n" }, { "change_type": "RENAME", "old_path": "scripts/builtin/naivebayes.dml", "new_path": "scripts/builtin/naiveBayes.dml", "diff": "#\n#-------------------------------------------------------------\n-m_naivebayes = function(Matrix[Double] D, Matrix[Double] C, Double laplace = 1, Boolean verbose = TRUE)\n+m_naiveBayes = function(Matrix[Double] D, Matrix[Double] C, Double laplace = 1, Boolean verbose = TRUE)\nreturn (Matrix[Double] prior, Matrix[Double] classConditionals)\n{\nlaplaceCorrection = laplace;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/naiveBayesPredict.dml", "diff": "+#-------------------------------------------------------------\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+m_naiveBayesPredict = function(Matrix[Double] X, Matrix[Double] P, Matrix[Double] C)\n+ return (Matrix[Double] YRaw, Matrix[Double] Y)\n+{\n+ numRows = nrow(X)\n+ model = cbind(C, P)\n+\n+ ones = matrix(1, rows=numRows, cols=1);\n+ X_w_ones = cbind(X, ones);\n+ YRaw = X_w_ones %*% t(log(model));\n+ Y = rowIndexMax(YRaw);\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -181,7 +181,8 @@ public enum Builtins {\nNCOL(\"ncol\", false),\nNORMALIZE(\"normalize\", true),\nNROW(\"nrow\", false),\n- NAIVEBAYES(\"naivebayes\", true, false),\n+ NAIVEBAYES(\"naiveBayes\", true, false),\n+ NAIVEBAYESPREDICT(\"naiveBayesPredict\", true, false),\nOUTER(\"outer\", false),\nOUTLIER(\"outlier\", true, false), //TODO parameterize opposite\nOUTLIER_SD(\"outlierBySd\", true),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinNaiveBayesPredictTest.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.apache.sysds.test.functions.builtin;\n+\n+import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Test;\n+\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+public class BuiltinNaiveBayesPredictTest extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"NaiveBayesPredict\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + BuiltinNaiveBayesPredictTest.class.getSimpleName() + \"/\";\n+ private final static int numClasses = 10;\n+\n+ public double eps = 1e-7;\n+\n+ @Override public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {\"YRaw\", \"Y\"}));\n+ }\n+\n+ @Test public void testSmallDense() {\n+ testNaiveBayesPredict(100, 50, 0.7);\n+ }\n+\n+ @Test public void testLargeDense() {\n+ testNaiveBayesPredict(10000, 750, 0.7);\n+ }\n+\n+ @Test public void testSmallSparse() {\n+ testNaiveBayesPredict(100, 50, 0.01);\n+ }\n+\n+ @Test public void testLargeSparse() {\n+ testNaiveBayesPredict(10000, 750, 0.01);\n+ }\n+\n+ public void testNaiveBayesPredict(int rows, int cols, double sparsity) {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+\n+ int classes = numClasses;\n+ double laplace = 1;\n+\n+ List<String> proArgs = new ArrayList<>();\n+ proArgs.add(\"-args\");\n+ proArgs.add(input(\"D\"));\n+ proArgs.add(input(\"C\"));\n+ proArgs.add(String.valueOf(classes));\n+ proArgs.add(String.valueOf(laplace));\n+ proArgs.add(output(\"YRaw\"));\n+ proArgs.add(output(\"Y\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ rCmd = getRCmd(inputDir(), Integer.toString(classes), Double.toString(laplace), expectedDir());\n+\n+ double[][] D = getRandomMatrix(rows, cols, 0, 1, sparsity, -1);\n+ double[][] C = getRandomMatrix(rows, 1, 0, 1, 1, -1);\n+ for(int i = 0; i < rows; i++) {\n+ C[i][0] = (int) (C[i][0] * classes) + 1;\n+ C[i][0] = (C[i][0] > classes) ? classes : C[i][0];\n+ }\n+\n+ writeInputMatrixWithMTD(\"D\", D, true);\n+ writeInputMatrixWithMTD(\"C\", C, true);\n+\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ runRScript(true);\n+\n+ HashMap<CellIndex, Double> YRawR = readRMatrixFromExpectedDir(\"YRaw\");\n+ HashMap<CellIndex, Double> YR = readRMatrixFromExpectedDir(\"Y\");\n+ HashMap<CellIndex, Double> YRawSYSTEMDS = readDMLMatrixFromOutputDir(\"YRaw\");\n+ HashMap<CellIndex, Double> YSYSTEMDS = readDMLMatrixFromOutputDir(\"Y\");\n+ TestUtils.compareMatrices(YRawR, YRawSYSTEMDS, eps, \"YRawR\", \"YRawSYSTEMDS\");\n+ TestUtils.compareMatrices(YR, YSYSTEMDS, eps, \"YR\", \"YSYSTEMDS\");\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/builtin/NaiveBayes.dml", "new_path": "src/test/scripts/functions/builtin/NaiveBayes.dml", "diff": "X = read($1);\ny = read($2);\n-[prior, conditionals] = naivebayes(D=X, C=y, laplace=$4);\n+[prior, conditionals] = naiveBayes(D=X, C=y, laplace=$4);\nwrite(prior, $5);\nwrite(conditionals, $6);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/NaiveBayesPredict.R", "diff": "+#-------------------------------------------------------------\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+args <- commandArgs(TRUE)\n+\n+library(\"Matrix\")\n+library(\"naivebayes\")\n+\n+D = as.matrix(readMM(paste(args[1], \"D.mtx\", sep=\"\")))\n+C = as.matrix(readMM(paste(args[1], \"C.mtx\", sep=\"\")))\n+laplace <- as.numeric(args[3])\n+\n+# divide D into \"train\" and \"test\" data\n+numRows = nrow(D)\n+trainSize = numRows * 0.8\n+\n+trainData = D[1:trainSize, ]\n+testData = D[(trainSize+1):numRows, ]\n+y <- factor(C[1:trainSize])\n+\n+# The Naive Bayes Predict need to unique column name\n+features <- paste0(\"V\", seq_len(ncol(trainData)))\n+colnames(trainData) <- features\n+colnames(testData) <- features\n+\n+# Create model base on train data\n+model <- multinomial_naive_bayes(x = trainData, y = y, laplace = laplace)\n+\n+# The SystemDS DML scripts based on YRaw data\n+# and the \"naivebayes\" predict function in R\n+# return probabilities matrix\n+# Example: YRaw <- predict(model, newdata = testData, type = \"prob\")\n+\n+# We need to return \"Raw\" values\n+lev <- model$levels\n+prior <- model$prior\n+params <- t(model$params)\n+YRaw <- tcrossprod(testData, log(params))\n+\n+for (ith_class in seq_along(lev)) {\n+ YRaw[ ,ith_class] <- YRaw[ ,ith_class] + log(prior[ith_class])\n+}\n+\n+Y <- max.col(YRaw, ties.method=\"last\")\n+\n+# write out the predict\n+writeMM(as(YRaw, \"CsparseMatrix\"), paste(args[4], \"YRaw\", sep=\"\"))\n+writeMM(as(Y, \"CsparseMatrix\"), paste(args[4], \"Y\", sep=\"\"))\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/NaiveBayesPredict.dml", "diff": "+#-------------------------------------------------------------\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+D = read($1);\n+C = read($2);\n+\n+# divide data into \"train\" and \"test\" subsets\n+numRows = nrow(D);\n+trainSize = numRows * 0.8;\n+trainData = D[1:trainSize,];\n+testData = D[(trainSize+1):numRows,];\n+C = C[1:trainSize,];\n+\n+# calc \"prior\" and \"conditionals\" with naiveBayes build-in function\n+[prior, conditionals] = naiveBayes(D=trainData, C=C, laplace=$4, verbose=FALSE);\n+\n+# compute predict\n+[YRaw,Y] = naiveBayesPredict(X=testData, P=prior, C=conditionals);\n+\n+# write the results\n+write(YRaw, $5);\n+write(Y, $6);\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/installDependencies.R", "new_path": "src/test/scripts/installDependencies.R", "diff": "@@ -61,6 +61,7 @@ custom_install(\"imputeTS\");\ncustom_install(\"FNN\");\ncustom_install(\"class\");\ncustom_install(\"unbalanced\");\n+custom_install(\"naivebayes\");\nprint(\"Installation Done\")\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2959] Add a predict function for Naive Bayes Closes #1217
49,706
03.05.2021 12:22:02
-7,200
f15d5d7a3748aa82f3d6a64c56dd2c03392650d8
Docker Image from Ubuntu not R-base This change had to happen since the R-base images did not work correctly with installing all package parts. Now the image is based on ubuntu 20.04
[ { "change_type": "MODIFY", "old_path": "docker/testsysds.Dockerfile", "new_path": "docker/testsysds.Dockerfile", "diff": "#\n#-------------------------------------------------------------\n-# Use R official debian release\n-FROM r-base\n-\n-WORKDIR /usr/src/\n+FROM ubuntu:20.04\n# Install Maven\n# Credit https://github.com/Zenika/alpine-maven/blob/master/jdk8/Dockerfile\n+# InstallR Guide: https://cran.r-project.org/\n+WORKDIR /usr/src/\nENV MAVEN_VERSION 3.6.3\nENV MAVEN_HOME /usr/lib/mvn\nENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64\nENV PATH $JAVA_HOME/bin:$MAVEN_HOME/bin:$PATH\n+ENV LANGUAGE en_US:en\n+ENV LC_ALL en_US.UTF-8\n+ENV LANG en_US.UTF-8\n-RUN mkdir /usr/lib/jvm\n-RUN wget -qO- \\\n-https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/download/jdk8u282-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u282b08.tar.gz \\\n-| tar xzf -\n-RUN mv jdk8u282-b08 /usr/lib/jvm/java-8-openjdk-amd64\n-\n-RUN wget -qO- \\\n-http://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz | tar xzf -\n-RUN mv apache-maven-$MAVEN_VERSION /usr/lib/mvn\n+COPY ./src/test/scripts/installDependencies.R installDependencies.R\n+COPY ./docker/entrypoint.sh /entrypoint.sh\n-# Install Extras\n-RUN apt-get update -qq && \\\n- apt-get upgrade -y && \\\n- apt-get install libcurl4-openssl-dev -y && \\\n- apt-get install libxml2-dev -y && \\\n- apt-get install r-cran-xml -y\n+RUN apt-get update -qq \\\n+ && apt-get upgrade -y \\\n+ && apt-get install -y --no-install-recommends \\\n+ libcurl4-openssl-dev \\\n+ libxml2-dev \\\n+ locales \\\n+ software-properties-common \\\n+ dirmngr \\\n+ gnupg \\\n+ apt-transport-https \\\n+ wget \\\n+ ca-certificates \\\n+ && apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9 \\\n+ && add-apt-repository \"deb https://cloud.r-project.org/bin/linux/ubuntu $(lsb_release -cs)-cran40/\" \\\n+ && apt-get update -qq \\\n+ && apt-get upgrade -y\n-COPY ./src/test/scripts/installDependencies.R installDependencies.R\n+# Set language\n+RUN echo \"en_US.UTF-8 UTF-8\" >> /etc/locale.gen \\\n+ && locale-gen en_US.utf8 \\\n+ && /usr/sbin/update-locale LANG=en_US.UTF-8\n-# Install R + Dependencies\n-RUN Rscript installDependencies.R\n+# Maven and Java\n+RUN mkdir -p /usr/lib/jvm \\\n+ && wget -qO- \\\n+https://github.com/AdoptOpenJDK/openjdk8-binaries/releases/download/jdk8u282-b08/OpenJDK8U-jdk_x64_linux_hotspot_8u282b08.tar.gz | tar xzf - \\\n+ && mv jdk8u282-b08 /usr/lib/jvm/java-8-openjdk-amd64 \\\n+ && wget -qO- \\\n+http://archive.apache.org/dist/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz | tar xzf - \\\n+ && mv apache-maven-$MAVEN_VERSION /usr/lib/mvn\n-COPY ./docker/entrypoint.sh /entrypoint.sh\n+# R\n+RUN apt-get install -y --no-install-recommends \\\n+ r-base \\\n+ r-base-dev \\\n+ && Rscript installDependencies.R \\\n+ && rm -rf installDependencies.R \\\n+ && rm -rf /var/lib/apt/lists/*\nENTRYPOINT [\"/entrypoint.sh\"]\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/InstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/InstructionUtils.java", "diff": "@@ -225,9 +225,14 @@ public class InstructionUtils\n}\npublic static ExecType getExecType( String str ) {\n+ try{\nint ix = str.indexOf(Instruction.OPERAND_DELIM);\nreturn ExecType.valueOf(str.substring(0, ix));\n}\n+ catch(Exception e){\n+ throw new DMLRuntimeException(\"Unable to extract Execution type from \" + str, e);\n+ }\n+ }\npublic static String getOpCode( String str ) {\nint ix1 = str.indexOf(Instruction.OPERAND_DELIM);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/transform/TransformCSVFrameEncodeReadTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/transform/TransformCSVFrameEncodeReadTest.java", "diff": "package org.apache.sysds.test.functions.transform;\n+import static org.junit.Assert.assertEquals;\nimport org.apache.sysds.api.DMLScript;\nimport org.apache.sysds.common.Types.ExecMode;\nimport org.apache.sysds.runtime.io.FileFormatPropertiesCSV;\n@@ -32,6 +33,7 @@ import org.apache.sysds.test.TestConfiguration;\nimport org.apache.sysds.test.TestUtils;\nimport org.junit.Test;\n+\npublic class TransformCSVFrameEncodeReadTest extends AutomatedTestBase\n{\nprivate final static String TEST_NAME1 = \"TransformCSVFrameEncodeRead\";\n@@ -128,17 +130,21 @@ public class TransformCSVFrameEncodeReadTest extends AutomatedTestBase\nString HOME = SCRIPT_DIR + TEST_DIR;\nint nrows = subset ? 4 : 13;\nfullDMLScriptName = HOME + TEST_NAME1 + \".dml\";\n- programArgs = new String[]{\"-stats\",\"-args\",\n+ programArgs = new String[]{\"-args\",\nDATASET_DIR + DATASET, String.valueOf(nrows), output(\"R\") };\n- runTest(true, false, null, -1);\n+ String stdOut = runTest(null).toString();\n//read input/output and compare\nFrameReader reader2 = parRead ?\nnew FrameReaderTextCSVParallel( new FileFormatPropertiesCSV() ) :\nnew FrameReaderTextCSV( new FileFormatPropertiesCSV() );\nFrameBlock fb2 = reader2.readFrameFromHDFS(output(\"R\"), -1L, -1L);\n- System.out.println(DataConverter.toString(fb2));\n+ String[] fromDisk = DataConverter.toString(fb2).split(\"\\n\");\n+ String[] printed = stdOut.split(\"\\n\");\n+ for(int i = 0; i < fromDisk.length; i++)\n+ assertEquals(fromDisk[i], printed[i]);\n+\n}\ncatch(Exception ex) {\nthrow new RuntimeException(ex);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2967] Docker Image from Ubuntu not R-base This change had to happen since the R-base images did not work correctly with installing all package parts. Now the image is based on ubuntu 20.04
49,698
04.05.2021 13:14:53
-19,080
e9a38a0cb160ec6ae8463a5bdf2e677887eb6b3e
DML recipes for inverse lower triangular matrix * Divide and conquer approach * This decomposition is used more generally will be used for building more complex algorithms Closes
[ { "change_type": "MODIFY", "old_path": "docs/site/dml-vs-r-guide.md", "new_path": "docs/site/dml-vs-r-guide.md", "diff": "@@ -209,3 +209,87 @@ C_indicator = table (index_C, PCV [, 1], max (index_C), nrow (C));\n# 5. Perform aggregation, here sum values per category\nsum_V_per_C = C_indicator %*% V\n```\n+\n+### Invert lower triangular matrix\n+\n+In this example, we invert a lower triangular matrix using the following divide-and-conquer approach.\n+Given lower triangular matrix L, we compute its inverse X which is also lower triangular by splitting\n+both matrices in the middle into 4 blocks (in a 2x2 fashion), and multiplying them together to get\n+the identity matrix:\n+\n+\\begin{equation}\n+L \\text{ %*% } X = \\left(\\begin{matrix} L_1 & 0 \\\\ L_2 & L_3 \\end{matrix}\\right)\n+\\text{ %*% } \\left(\\begin{matrix} X_1 & 0 \\\\ X_2 & X_3 \\end{matrix}\\right)\n+= \\left(\\begin{matrix} L_1 X_1 & 0 \\\\ L_2 X_1 + L_3 X_2 & L_3 X_3 \\end{matrix}\\right)\n+= \\left(\\begin{matrix} I & 0 \\\\ 0 & I \\end{matrix}\\right)\n+\\nonumber\n+\\end{equation}\n+\n+If we multiply blockwise, we get three equations:\n+\n+$\n+\\begin{equation}\n+L1 \\text{ %*% } X1 = 1\\\\\n+L3 \\text{ %*% } X3 = 1\\\\\n+L2 \\text{ %*% } X1 + L3 \\text{ %*% } X2 = 0\\\\\n+\\end{equation}\n+$\n+\n+Solving these equation gives the following formulas for X:\n+\n+$\n+\\begin{equation}\n+X1 = inv(L1) \\\\\n+X3 = inv(L3) \\\\\n+X2 = - X3 \\text{ %*% } L2 \\text{ %*% } X1 \\\\\n+\\end{equation}\n+$\n+\n+If we already recursively inverted L1 and L3, we can invert L2. This suggests an algorithm\n+that starts at the diagonal and iterates away from the diagonal, involving bigger and bigger\n+blocks (of size 1, 2, 4, 8, etc.) There is a logarithmic number of steps, and inside each\n+step, the inversions can be performed in parallel using a parfor-loop.\n+\n+Function \"invert_lower_triangular\" occurs within more general inverse operations and matrix decompositions.\n+The divide-and-conquer idea allows to derive more efficient algorithms for other matrix decompositions.\n+\n+```dml\n+invert_lower_triangular = function (Matrix[double] LI)\n+ return (Matrix[double] LO)\n+{\n+ n = nrow (LI);\n+ LO = matrix (0, rows = n, cols = n);\n+ LO = LO + diag (1 / diag (LI));\n+\n+ k = 1;\n+ while (k < n)\n+ {\n+ LPF = matrix (0, rows = n, cols = n);\n+ parfor (p in 0:((n - 1) / (2 * k)), check = 0)\n+ {\n+ i = 2 * k * p;\n+ j = i + k;\n+ q = min (n, j + k);\n+ if (j + 1 <= q) {\n+ L1 = LO [i + 1:j, i + 1:j];\n+ L2 = LI [j + 1:q, i + 1:j];\n+ L3 = LO [j + 1:q, j + 1:q];\n+ LPF [j + 1:q, i + 1:j] = -L3 %*% L2 %*% L1;\n+ }\n+ }\n+ LO = LO + LPF;\n+ k = 2 * k;\n+ }\n+}\n+\n+# simple 10x10 test matrix\n+n = 10;\n+A = rand (rows = n, cols = n, min = -1, max = 1, pdf = \"uniform\", sparsity = 1.0)\n+Mask = cumsum (diag (matrix (1, rows = n, cols = 1)))\n+\n+# Generate L for stability of the inverse\n+L = (A %*% t(A)) * Mask\n+\n+X = invert_lower_triangular (L);\n+```\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2968] DML recipes for inverse lower triangular matrix * Divide and conquer approach * This decomposition is used more generally will be used for building more complex algorithms Closes #1252.
49,698
04.05.2021 13:29:18
-19,080
6807cca3c64682c88464aefb972e995a246871de
[MINOR][DOC] Fix latex format and header
[ { "change_type": "MODIFY", "old_path": "docs/_includes/header.html", "new_path": "docs/_includes/header.html", "diff": "@@ -47,6 +47,7 @@ limitations under the License.\n<li><b>Language Guides:</b></li>\n<li><a href=\".{% if page.path contains 'site' %}/..{% endif %}/site/dml-language-reference.html\">DML Language Reference</a></li>\n<li><a href=\".{% if page.path contains 'site' %}/..{% endif %}/site/builtins-reference.html\">Built-in Functions Reference</a></li>\n+ <li><a href=\".{% if page.path contains 'site' %}/..{% endif %}/site/dml-vs-r-guide.html\">DML vs R guide</a></li>\n<li class=\"divider\"></li>\n<li><b>ML Algorithms:</b></li>\n<li><a href=\".{% if page.path contains 'site' %}/..{% endif %}/site/algorithms-reference.html\">Algorithms Reference</a></li>\n" }, { "change_type": "MODIFY", "old_path": "docs/site/dml-vs-r-guide.md", "new_path": "docs/site/dml-vs-r-guide.md", "diff": "@@ -217,6 +217,7 @@ Given lower triangular matrix L, we compute its inverse X which is also lower tr\nboth matrices in the middle into 4 blocks (in a 2x2 fashion), and multiplying them together to get\nthe identity matrix:\n+$$\n\\begin{equation}\nL \\text{ %*% } X = \\left(\\begin{matrix} L_1 & 0 \\\\ L_2 & L_3 \\end{matrix}\\right)\n\\text{ %*% } \\left(\\begin{matrix} X_1 & 0 \\\\ X_2 & X_3 \\end{matrix}\\right)\n@@ -224,26 +225,27 @@ L \\text{ %*% } X = \\left(\\begin{matrix} L_1 & 0 \\\\ L_2 & L_3 \\end{matrix}\\right)\n= \\left(\\begin{matrix} I & 0 \\\\ 0 & I \\end{matrix}\\right)\n\\nonumber\n\\end{equation}\n+$$\nIf we multiply blockwise, we get three equations:\n-$\n+$$\n\\begin{equation}\nL1 \\text{ %*% } X1 = 1\\\\\nL3 \\text{ %*% } X3 = 1\\\\\nL2 \\text{ %*% } X1 + L3 \\text{ %*% } X2 = 0\\\\\n\\end{equation}\n-$\n+$$\nSolving these equation gives the following formulas for X:\n-$\n+$$\n\\begin{equation}\nX1 = inv(L1) \\\\\nX3 = inv(L3) \\\\\nX2 = - X3 \\text{ %*% } L2 \\text{ %*% } X1 \\\\\n\\end{equation}\n-$\n+$$\nIf we already recursively inverted L1 and L3, we can invert L2. This suggests an algorithm\nthat starts at the diagonal and iterates away from the diagonal, involving bigger and bigger\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR][DOC] Fix latex format and header
49,720
04.05.2021 11:16:40
-7,200
92cda3f811ccf0b1cbb326fa0f96fddf26a0d8e5
Initial implementation of Logical Pipelines optimizer Optimizer is based on evolutionary algorithm with constrained crossover and mutation this commit also contains some minor formatting cleanups in pipelines package Closes
[ { "change_type": "MODIFY", "old_path": "scripts/builtin/bandit.dml", "new_path": "scripts/builtin/bandit.dml", "diff": "@@ -25,6 +25,7 @@ m_bandit = function(Matrix[Double] X_train, Matrix[Double] Y_train, List[Unknown\n{\nprint(\"Starting optimizer\")\nNUM_FEATURES = 14\n+ HYPERPARAM_LENGTH = 110\nprint(\"null in data \"+sum(is.na(X_train)))\nbestPipeline = frame(\"\", rows=1, cols=1)\nbestHyperparams = as.matrix(0)\n@@ -36,7 +37,7 @@ m_bandit = function(Matrix[Double] X_train, Matrix[Double] Y_train, List[Unknown\nB = (s_max + 1) * R;\n# initialize output variables\n- hparam = matrix(0, rows=k*(s_max+1), cols=100)\n+ hparam = matrix(0, rows=k*(s_max+1), cols=HYPERPARAM_LENGTH)\npipeline = frame(0, rows=k*(s_max+1), cols=ncol(lp)+1)\nstartOut=0; endOut=0;\nfeaFrameOuter = frame(data=[\"#MissingValues\", \"MinVla\", \"MaxVal\", \"AverageMin\", \"AverageMax\",\n@@ -46,7 +47,7 @@ m_bandit = function(Matrix[Double] X_train, Matrix[Double] Y_train, List[Unknown\nfor(s in s_max:0) {\n# result variables\n- bracket_hp = matrix(0, rows=k*(s+1)+k, cols=100)\n+ bracket_hp = matrix(0, rows=k*(s+1)+k, cols=HYPERPARAM_LENGTH)\nbracket_pipel = matrix(0, rows=k*(s+1)+k, cols=3)\nstart=1; end=0;\n@@ -90,8 +91,8 @@ m_bandit = function(Matrix[Double] X_train, Matrix[Double] Y_train, List[Unknown\nbracket_hp[start:end, 1:ncol(b)] = b[1:rowIndex,]\nstart = end + 1\n- # sort the configurations fro successive halving\n- avergae_perf = getMaxPerConf(outPip)\n+ # sort the configurations for successive halving\n+ avergae_perf = getMaxPerConf(outPip, nrow(configurations))\nconfigurations = frameSort(cbind(avergae_perf, configurations))\nconfigurations = configurations[, 2:ncol(configurations)]\n}\n@@ -201,7 +202,7 @@ run_with_hyperparam = function(Frame[Unknown] ph_pip, Integer r_i, Matrix[Double\nList[Unknown] targetList, Frame[Unknown] param, Frame[Unknown] featureFrameOuter, Boolean verbose)\nreturn (Matrix[Double] output_operator, Matrix[Double] output_hyperparam, Frame[Unknown] featureFrameOuter) {\n- output_hp = matrix(0, nrow(ph_pip)*r_i, 60)\n+ output_hp = matrix(0, nrow(ph_pip)*r_i, 100)\noutput_accuracy = matrix(0, nrow(ph_pip)*r_i, 1)\noutput_pipelines = matrix(0, nrow(ph_pip)*r_i, 2)\n@@ -218,6 +219,7 @@ run_with_hyperparam = function(Frame[Unknown] ph_pip, Integer r_i, Matrix[Double\n{\n# execute configurations with r resources\n[hp, no_of_res, no_of_flag_vars] = getHyperparam(ph_pip[i], param, r_i)\n+ if(ncol(featureFrameOuter) > 1)\nfeaFrame = frame(\"\", rows = no_of_res, cols = ncol(featureFrameOuter))\npip_toString = pipToString(ph_pip[i])\nfor(r in 1:no_of_res)\n@@ -239,19 +241,23 @@ run_with_hyperparam = function(Frame[Unknown] ph_pip, Integer r_i, Matrix[Double\nhp_vec = cbind(matrix_width, matrix(hp_matrix, rows=1, cols=nrow(hp_matrix)*ncol(hp_matrix), byrow=TRUE))\noutput_accuracy[index, 1] = accuracy\noutput_hp[index, 1:ncol(hp_vec)] = hp_vec\n- output_pipelines[index, ] = cbind(as.matrix(i), id[i,1])\n+ output_pipelines[index, ] = cbind(as.matrix(index), id[i,1])\nX = clone_X\nY = clone_Y\nindex = index + 1\n+\n+ if(ncol(featureFrameOuter) > 1) {\nfeaFrame[r, 1:ncol(feaVec)] = as.frame(feaVec)\nfeaFrame[r, (ncol(feaVec)+1)] = pip_toString\nfeaFrame[r, (ncol(feaVec)+2)] = accuracy\nfeaFrame[r, (ncol(feaVec)+3)] = T\nfeaFrame[r, (ncol(feaVec)+4)] = accT\n}\n+ }\nX = clone_X\nY = clone_Y\n+ if(ncol(featureFrameOuter) > 1)\nfeatureFrameOuter = rbind(featureFrameOuter, feaFrame)\n}\noutput_hyperparam = removeEmpty(target=cbind(output_accuracy, output_hp), margin=\"rows\")\n@@ -317,22 +323,25 @@ getHyperparam = function(Frame[Unknown] pipeline, Frame[Unknown] hpList, Intege\nif(type == \"FP\") {\nval = rand(rows=no_of_res, cols=1, min=minVal,max=maxVal, pdf=\"uniform\");\nOpParam[, j] = val;\n- } else if(type == \"INT\") {\n+ }\n+ else if(type == \"INT\") {\nval = sample(maxVal, no_of_res, TRUE);\nless_than_min = val < minVal;\nval = (less_than_min * minVal) + val;\n- OpParam[, j] = val\n- } else if(type == \"BOOL\") {\n+ OpParam[, j] = val;\n+ }\n+ else if(type == \"BOOL\") {\nif(maxVal == 1) {\ns = sample(2, no_of_res, TRUE);\nb = s - 1;\nOpParam[, j] = b;\n- } else\n+ }\n+ else\nOpParam[, j] = matrix(0, rows=no_of_res, cols=1)\n- } else {\n- # TODO handle string set something like {,,}\n- print(\"invalid data type\")\n}\n+ else\n+ print(\"invalid data type\") # TODO handle string set something like {,,}\n+\nparamIdx = paramIdx + 2\ntypeIdx = typeIdx + 1\n}\n@@ -434,11 +443,11 @@ extractBracketWinners = function(Matrix[Double] pipeline, Matrix[Double] hyperpa\n###########################################################################\n# The function will return the max performance by each individual pipeline\n############################################################################\n-getMaxPerConf = function(Matrix[Double] pipelines)\n+getMaxPerConf = function(Matrix[Double] pipelines, Double size)\nreturn (Frame[Unknown] maxperconf)\n{\ntab = removeEmpty(target=table(pipelines[, 2], pipelines[, 3], pipelines[, 1]), margin=\"cols\")\n- maxperconf = frame(0, rows=max(pipelines[, 2]), cols=1)\n+ maxperconf = frame(0, rows=size, cols=1)\nmaxperconf[1:ncol(tab),] = as.frame(t(colMaxs(tab)))\n}\n@@ -457,9 +466,7 @@ fclassify = function(Matrix[Double] X, Matrix[Double] Y, Matrix[Double] mask, Ma\nelse {\nprint(\"STARTING \"+cv+\" CROSS VALIDATIONS\")\n# do the k = 3 cross validations\n- t1 = time()\n- accuracyMatrix = crossV(X, Y, cv, mask, MLhp, isWeighted)\n- T = floor((time() - t1) / 1e+6)\n+ [accuracyMatrix, T] = crossV(X, Y, cv, mask, MLhp, isWeighted)\naccuracyMatrix = removeEmpty(target=accuracyMatrix, margin=\"rows\")\nacc = colMeans(accuracyMatrix)\naccuracy = as.scalar(acc[1,1])\n@@ -477,8 +484,9 @@ fclassify = function(Matrix[Double] X, Matrix[Double] Y, Matrix[Double] mask, Ma\ncrossV = function(Matrix[double] X, Matrix[double] y, Integer k, Matrix[Double] mask,\nMatrix[Double] MLhp, Boolean isWeighted)\n-return (Matrix[Double] accuracyMatrix)\n+return (Matrix[Double] accuracyMatrix, Double T)\n{\n+ t1 = time()\naccuracyMatrix = matrix(0, k, 1)\ndataList = list()\ntestL = list()\n@@ -523,6 +531,7 @@ return (Matrix[Double] accuracyMatrix)\naccuracy = getAccuracy(testy, yhat, isWeighted)\naccuracyMatrix[i] = accuracy\n}\n+ T = floor((time() - t1) / 1e+6)\n}\n@@ -603,7 +612,7 @@ return (Double precision, Double T)\nmatch = (abs(cleanX - fixedX) < 0.001) * correctionsRequired\nprint(\"total matches \"+sum(match))\n# print(\"total matches \\n\"+toString(match))\n- precision = max(0.001, sum(match) / correctionsMade)\n+ precision = max(0.001, sum(match) / max(1, correctionsMade))\nT = floor((time() - t1) / 1e+6)\nprint(\"Precision: \"+toString(precision) + \" in \"+T+\" ms\")\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/pipelines/scripts/enumerateLogical.dml", "diff": "+#-------------------------------------------------------------\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+# Generate the logical pipelines using basic evolutionary algorithm,\n+# population -> logical Pipeline, chromosome -> physical pipeline, gene -> hp\n+# input :\n+# 1. Dataset X\n+# 2. population, different logical seed pipelines format = [number of operators, op1, op2, op3 ..., opn]\n+# 3. number of iterations\n+# 4. pipLength, length of pipeline, number of operator in each pipeline\n+# 5. meta data list i.e., schema, mask, fdmask\n+# 6. target list i.e, target application, cv value etc.\n+# 7. primitives, physical operator list\n+# 8. param, physical operator hyperparameters\n+# 9. num_inst value, number of physical instances for each logical to be executed\n+# 10. num_exec, how many times each physical pipeline should be executed\n+# 11. n_pop, children created in each generation\n+# output: best logical pipeline and evaluation time in ms\n+\n+\n+# idea is to get the initial set of logical pipelines, as population, then get the num_inst physical pipelines foreach\n+# logical pipeline in population. Then execute these physical pipelines num_exec time were in each execution a random set of\n+# hyperparameters is used to execute operators. The compute a score vector by storing the best score foreach logical pipeline in\n+# population. Sort the pipelines by score and take n_pop pipelines as parents for generating new population.\n+# from the selected pipelines take a pair in each iteration as parent and generate a pair of children by doing crossover and mutation.\n+# In crossover make a child by taking some operation from p1 and some operations from p2 and in mutation randomly swap the\n+# operators in children. There new children will be the population in next iteration. Repeat the process max_iter time.\n+# Converge in between if the best_score of previous generation is better then best_score of new generation.\n+\n+source(\"scripts/builtin/bandit.dml\") as bandit;\n+source(\"scripts/pipelines/scripts/utils.dml\") as utils;\n+\n+enumerateLogical = function(Matrix[Double] X, Matrix[Double] y, Frame[Unknown] population, Integer max_iter=10,\n+ Integer pipLength, List[Unknown] metaList, List[Unknown] targetList, Frame[Unknown] primitives, Frame[Unknown] param,\n+ Integer num_inst, Integer num_exec, Integer n_pop, Boolean verbose)\n+return (Frame[Unknown] bestLg, Double pre_best, Double T)\n+{\n+\n+ t1 = time()\n+ bestLg = as.frame(\"\")\n+ best_score = 0\n+ pre_best = 0\n+ feaFrameOuter = as.frame(\"NULL\")\n+ iter = 1\n+ convergedOuter = FALSE\n+ while(iter <= max_iter & !convergedOuter)\n+ {\n+ physicalPipList = list()\n+ # # # get the physical instances from logical ones\n+ for(i in 1:nrow(population))\n+ {\n+ lv = as.integer(as.scalar(population[i, 1])) + 1\n+ lp = population[i, 2:lv]\n+ physicalConf = bandit::get_physical_configurations(lp, num_inst, primitives)\n+ physicalPipList = append(physicalPipList, physicalConf)\n+ }\n+\n+ scores = matrix(0, rows=length(physicalPipList), cols=1)\n+\n+ # # # execute the physical pipelines\n+ for(i in 1:length(physicalPipList))\n+ {\n+ physicalConf = as.frame(physicalPipList[i])\n+ # # append configuration keys for extracting the pipeline later on\n+ id = seq(1, nrow(physicalConf))\n+ physicalConf = cbind(as.frame(id), physicalConf)\n+ # # execute the physical instances and store the minimum scores, each pipeline is executed num_exec times\n+ [outPip,outHp, feaFrameOuter] = bandit::run_with_hyperparam(physicalConf, num_exec, X, y, metaList,\n+ targetList, param, as.frame(\"\"), verbose)\n+ # # sort the configurations groupwise\n+ max_perf = bandit::getMaxPerConf(outPip, nrow(physicalConf))\n+ scores[i] = as.matrix(max_perf[1, 1])\n+ }\n+\n+ # # select parents and best score\n+ selected = order(target = scores, by = 1, decreasing=TRUE, index.return=TRUE)\n+ idxR = as.scalar(selected[1, 1])\n+ best_score = as.scalar(scores[idxR])\n+ if(verbose)\n+ {\n+ print(\"best score \"+best_score)\n+ print(\"previous score \"+pre_best)\n+ }\n+\n+ converge = ifelse(pre_best > best_score, TRUE, FALSE)\n+ if(converge) {\n+ convergedOuter = TRUE\n+ print(\"----------- converged after \"+iter+\" iteration-------------\")\n+ print(\"best score \"+pre_best)\n+ print(\"best pipeline \"+toString(bestLg))\n+ }\n+ else\n+ {\n+ pre_best = best_score\n+ idxC = as.integer(as.scalar(population[idxR, 1])) + 1\n+ bestLg = population[idxR, 2:idxC]\n+ }\n+\n+ # # # if new best is not better than pre_best then no need od generating new population\n+ children = frame(0, rows=n_pop, cols=pipLength+1)\n+ CROSS_OVER_RATE = 2\n+ i = 1\n+ while(i <= n_pop & !converge)\n+ {\n+ p1 = population[as.scalar(selected[i]), ]\n+ p2 = population[as.scalar(selected[i+1]), ]\n+ lengthp1 = as.integer(as.scalar(p1[1, 1]))\n+ lengthp2 = as.integer(as.scalar(p2[1, 1]))\n+ p1 = p1[, 2:(lengthp1+1)]\n+ p2 = p2[, 2:(lengthp2+1)]\n+ # # # cross over, this constrained crossover will only add first operator from each parent to child\n+\n+ if(lengthp1 >= 5 & (lengthp1 + CROSS_OVER_RATE) < pipLength) #check if pipeline is less than 5 operation only crossover one\n+ c1 = cbind(p1[1,1:CROSS_OVER_RATE], p2) # operator so the probability of swapping pca and dummycoding is\n+ else if ((lengthp1 + 1) < pipLength) # low and the crossover all should not exceed pipeline total length\n+ c1 = cbind(p1[1,1], p2)\n+\n+ if(lengthp2 >= 5 & (lengthp2 + CROSS_OVER_RATE) < pipLength)\n+ c2 = cbind(p2[1,1:CROSS_OVER_RATE], p1)\n+ else if ((lengthp2 + 1) < pipLength)\n+ c2 = cbind(p2[1,1], p1)\n+\n+ # # # mutation swap the operators at random positions if the length is greater than 5\n+ if(ncol(c1) >= 5)\n+ {\n+ r = sample(3, 2)\n+ r1 = as.scalar(r[1,1])\n+ r2 = as.scalar(r[2,1])\n+ temp = c1[1, r1]\n+ c1[1, r1] = c1[1, r2]\n+ c1[1, r2] = temp\n+ }\n+ if(ncol(c2) >= 5)\n+ {\n+ r = sample(3, 2)\n+ r1 = as.scalar(r[1,1])\n+ r2 = as.scalar(r[2,1])\n+ temp = c2[1, r1]\n+ c2[1, r1] = c2[1, r2]\n+ c2[1, r2] = temp\n+ }\n+ # # # append length of pipeline and pipeline in frame\n+ children[i, 1] = ncol(c1)\n+ children[i, 2:(ncol(c1) + 1)] = c1\n+ children[i+1, 1] = ncol(c2)\n+ children[i+1, 2:(ncol(c2) + 1)] = c2\n+\n+ i = i + 2\n+ }\n+ population = children\n+ }\n+ T = floor((time() - t1) / 1e+6)\n+ print(\"time \"+T+\" ms\")\n+}\n+\n" }, { "change_type": "MODIFY", "old_path": "scripts/pipelines/scripts/logicalFunc.dml", "new_path": "scripts/pipelines/scripts/logicalFunc.dml", "diff": "@@ -105,9 +105,9 @@ return(Frame[Unknown] transformLogical) {\n}\ntransformLogical[1, 1:ncol(seed)] = seed\ntransformLogical = map(transformLogical, \"var -> var.replace(\\\"0\\\", \\\"\\\")\")\n- transformLogical = utils::frameRemoveEmpty(target=transformLogical, margin=\"cols\", select=as.matrix(0))\n+ transformLogical = utils::frameRemoveEmpty(target=transformLogical, marginParam=\"cols\", select=as.matrix(0))\nif(nrow(transformLogical) > 1)\n- transformLogical = utils::frameRemoveEmpty(target=transformLogical, margin=\"rows\", select=as.matrix(0))\n+ transformLogical = utils::frameRemoveEmpty(target=transformLogical, marginParam=\"rows\", select=as.matrix(0))\n}\n" }, { "change_type": "MODIFY", "old_path": "scripts/pipelines/scripts/utils.dml", "new_path": "scripts/pipelines/scripts/utils.dml", "diff": "@@ -22,7 +22,7 @@ source(\"scripts/builtin/bandit.dml\") as bandit;\n# remove empty wrapper for frames\n-frameRemoveEmpty = function(Frame[Unknown] target, String margin, Matrix[Double] select)\n+frameRemoveEmpty = function(Frame[Unknown] target, String marginParam, Matrix[Double] select)\nreturn (Frame[Unknown] frameblock)\n{\nidx = seq(1, ncol(target))\n@@ -32,11 +32,19 @@ return (Frame[Unknown] frameblock)\njspecR = \"{ids:true, recode:[\"+index+\"]}\";\n[Xd, M] = transformencode(target=target, spec=jspecR);\nX = replace(target=Xd, pattern = NaN, replacement=0)\n- if(nrow(select) > 1)\n- X = removeEmpty(target = X, margin = margin, select = select)\n+ if(nrow(select) > 1 ) {\n+ # TODO fix removeEmpty Spark instruction to accept margin as a variable for now only support literal\n+ if(marginParam == \"rows\")\n+ X = removeEmpty(target = X, margin = \"rows\", select = select)\nelse\n- X = removeEmpty(target = X, margin = margin)\n-\n+ X = removeEmpty(target = X, margin = \"cols\", select = select)\n+ }\n+ else {\n+ if(marginParam == \"rows\")\n+ X = removeEmpty(target = X, margin = \"rows\")\n+ else\n+ X = removeEmpty(target = X, margin = \"cols\")\n+ }\nframeblock = transformdecode(target = Xd, spec = jspecR, meta = M)\nframeblock = frameblock[1:nrow(X), 1:ncol(X)]\n}\n@@ -115,7 +123,7 @@ classifyDirty = function(Matrix[Double] Xtrain, Matrix[Double] ytrain, Matrix[Do\n# # classify without cleaning fill with edfault values 1\nXtrain = replace(target = Xtrain, pattern = NaN, replacement=0)\ndX_train = dummycoding(Xtrain, mask)\n- accuracy = bandit::crossV(Xtrain, ytrain, cv, mask, opt, isWeighted)\n+ [accuracy, T] = bandit::crossV(Xtrain, ytrain, cv, mask, opt, isWeighted)\naccuracy = mean(accuracy)\nprint(\"cross validated dirty accuracy \"+accuracy)\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestClassification.java", "new_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestClassification.java", "diff": "@@ -32,15 +32,15 @@ public class CleaningTestClassification extends AutomatedTestBase {\nprivate final static String TEST_NAME2 = \"compareAccuracy\";\nprivate final static String TEST_CLASS_DIR = SCRIPT_DIR + CleaningTestClassification.class.getSimpleName() + \"/\";\n- protected static final String RESOURCE = SCRIPT_DIR+\"functions/pipelines/\";\n- protected static final String DATA_DIR = DATASET_DIR+ \"pipelines/\";\n+ private static final String RESOURCE = SCRIPT_DIR+\"functions/pipelines/\";\n+ private static final String DATA_DIR = DATASET_DIR+ \"pipelines/\";\nprivate final static String DIRTY = DATA_DIR+ \"dirty.csv\";\nprivate final static String CLEAN = DATA_DIR+ \"clean.csv\";\nprivate final static String META = RESOURCE+ \"meta/meta_census.csv\";\nprivate final static String OUTPUT = RESOURCE+\"intermediates/\";\n- protected static final String PARAM_DIR = \"./scripts/pipelines/properties/\";\n+ private static final String PARAM_DIR = \"./scripts/pipelines/properties/\";\nprivate final static String PARAM = PARAM_DIR + \"param.csv\";\nprivate final static String PRIMITIVES = PARAM_DIR + \"primitives.csv\";\n@@ -51,13 +51,13 @@ public class CleaningTestClassification extends AutomatedTestBase {\n}\n@Ignore\n- public void testCP1() {\n+ public void testFindBestPipeline() {\nrunFindPipelineTest(0.1, 5,10, 2,\ntrue, \"classification\", Types.ExecMode.SINGLE_NODE);\n}\n@Test\n- public void testCP2() {\n+ public void testCompareRepairs() {\nrunCleanAndCompareTest( Types.ExecMode.SINGLE_NODE);\n}\n@@ -70,11 +70,10 @@ public class CleaningTestClassification extends AutomatedTestBase {\ntry {\nloadTestConfiguration(getTestConfiguration(TEST_NAME1));\nfullDMLScriptName = HOME + TEST_NAME1 + \".dml\";\n- programArgs = new String[] {\"-stats\", \"-exec\", \"singlenode\", \"-nvargs\", \"dirtyData=\"+DIRTY, \"metaData=\"+META,\n- \"primitives=\"+PRIMITIVES, \"parameters=\"+PARAM, \"sampleSize=\"+String.valueOf(sample),\n- \"topk=\"+String.valueOf(topk), \"rv=\"+String.valueOf(resources), \"cv=\"+String.valueOf(crossfold),\n- \"weighted=\"+ String.valueOf(weightedAccuracy), \"output=\"+OUTPUT, \"target=\"+target, \"cleanData=\"+CLEAN,\n- \"O=\"+output(\"O\")};\n+ programArgs = new String[] {\"-stats\", \"-exec\", \"singlenode\", \"-nvargs\", \"dirtyData=\"+DIRTY,\n+ \"metaData=\"+META, \"primitives=\"+PRIMITIVES, \"parameters=\"+PARAM, \"sampleSize=\"+ sample,\n+ \"topk=\"+ topk, \"rv=\"+ resources, \"cv=\"+ crossfold, \"weighted=\"+ weightedAccuracy,\n+ \"output=\"+OUTPUT, \"target=\"+target, \"cleanData=\"+CLEAN, \"O=\"+output(\"O\")};\nrunTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestCompare.java", "new_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestCompare.java", "diff": "@@ -46,7 +46,6 @@ public class CleaningTestCompare extends AutomatedTestBase {\naddTestConfiguration(TEST_NAME1,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1,new String[]{\"R\"}));\n}\n-\n@Test\npublic void testCP1() {\nrunFindPipelineTest(5,10, 2,\n@@ -62,8 +61,8 @@ public class CleaningTestCompare extends AutomatedTestBase {\ntry {\nloadTestConfiguration(getTestConfiguration(TEST_NAME1));\nfullDMLScriptName = HOME + TEST_NAME1 + \".dml\";\n- programArgs = new String[] {\"-stats\", \"-exec\", \"singlenode\", \"-nvargs\", \"dirtyData=\"+DIRTY, \"metaData=\"+META,\n- \"primitives=\"+PRIMITIVES, \"parameters=\"+PARAM, \"topk=\"+String.valueOf(topk), \"rv=\"+String.valueOf(resources),\n+ programArgs = new String[] {\"-stats\", \"-exec\", \"singlenode\", \"-nvargs\", \"dirtyData=\"+DIRTY,\n+ \"metaData=\"+META, \"primitives=\"+PRIMITIVES, \"parameters=\"+PARAM, \"topk=\"+ topk, \"rv=\"+ resources,\n\"output=\"+OUTPUT, \"target=\"+target, \"cleanData=\"+CLEAN, \"O=\"+output(\"O\")};\nrunTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/pipelines/CleaningTestLogical.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.apache.sysds.test.functions.pipelines;\n+\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.Ignore;\n+import org.junit.Test;\n+\n+public class CleaningTestLogical extends AutomatedTestBase {\n+ private final static String TEST_NAME = \"testLogical\";\n+ private final static String TEST_CLASS_DIR = SCRIPT_DIR + CleaningTestLogical.class.getSimpleName() + \"/\";\n+\n+ private static final String RESOURCE = SCRIPT_DIR+\"functions/pipelines/\";\n+ private static final String DATA_DIR = DATASET_DIR+ \"pipelines/\";\n+\n+ private final static String DIRTY = DATA_DIR+ \"dirty.csv\";\n+ private final static String CLEAN = DATA_DIR+ \"clean.csv\";\n+ private final static String META = RESOURCE+ \"meta/meta_census.csv\";\n+\n+ private static final String PARAM_DIR = \"./scripts/pipelines/properties/\";\n+ private final static String PARAM = PARAM_DIR + \"param.csv\";\n+ private final static String PRIMITIVES = PARAM_DIR + \"primitives.csv\";\n+\n+ @Override\n+ public void setUp() {\n+ addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{\"R\"}));\n+ }\n+\n+ @Test\n+ public void testLogical1() {\n+ runTestLogical(2, 10, 2, 2, 2, 2,\n+ \"classification\", Types.ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Ignore\n+ public void testLogicalSP() {\n+ runTestLogical(3, 10, 3, 2, 2, 4,\n+ \"classification\", Types.ExecMode.SPARK);\n+ }\n+\n+ private void runTestLogical(int max_iter, int pipelineLength, int crossfold,\n+ int num_inst, int num_exec, int n_pop, String target, Types.ExecMode et) {\n+\n+ // setOutputBuffering(true);\n+ String HOME = SCRIPT_DIR+\"functions/pipelines/\" ;\n+ Types.ExecMode modeOld = setExecMode(et);\n+ try {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"-exec\", \"singlenode\", \"-nvargs\", \"dirtyData=\"+DIRTY,\n+ \"metaData=\"+META, \"primitives=\"+PRIMITIVES, \"parameters=\"+PARAM, \"max_iter=\"+ max_iter,\n+ \"pipLength=\"+ pipelineLength, \"cv=\"+ crossfold, \"num_inst=\"+ num_inst, \"num_exec=\"+ num_exec,\n+ \"n_pop=\"+ n_pop,\"target=\"+target, \"cleanData=\"+CLEAN, \"O=\"+output(\"O\")};\n+\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ //expected loss smaller than default invocation\n+ Assert.assertTrue(TestUtils.readDMLBoolean(output(\"O\")));\n+ }\n+ finally {\n+ resetExecMode(modeOld);\n+ }\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/pipelines/testLogical.dml", "diff": "+#-------------------------------------------------------------\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+# Generate the logical pipelines for data cleaning\n+\n+source(\"scripts/pipelines/scripts/utils.dml\") as utils;\n+source(\"scripts/pipelines/scripts/logicalFunc.dml\") as logical;\n+source(\"scripts/pipelines/scripts/gridsearchMLR.dml\") as gs;\n+source(\"scripts/pipelines/scripts/enumerateLogical.dml\") as lg;\n+\n+\n+# read the inputs\n+X = read($dirtyData, data_type=\"frame\", format=\"csv\", header=TRUE,\n+ naStrings= [\"NA\", \"null\",\" \",\"NaN\", \"nan\", \"\", \"?\", \"99999\"]);\n+\n+metaInfo = read($metaData, data_type=\"frame\", format=\"csv\", header=FALSE);\n+primitives = read($primitives, data_type = \"frame\", format=\"csv\", header= TRUE)\n+param = read($parameters, data_type = \"frame\", format=\"csv\", header= TRUE)\n+weightedAccuracy = FALSE # accuracy flag\n+targetApplicaton = $target # accuracy flag\n+\n+max_iter = $max_iter\n+num_inst = $num_inst\n+num_exec = $num_exec\n+n_pop=$n_pop\n+pipLength = $pipLength\n+crossValidations = $cv\n+\n+\n+getSchema = metaInfo[1, 2:ncol(metaInfo)]\n+getMask = as.matrix(metaInfo[2, 2:ncol(metaInfo)])\n+getFdMask = as.matrix(metaInfo[3, 2:ncol(metaInfo)]) # columns of interest for FD computation\n+\n+\n+# encode the categorical data\n+if(sum(getMask) > 0)\n+{\n+ # always recode the label\n+ index = vectorToCsv(getMask)\n+ jspecR = \"{ids:true, recode:[\"+index+\"]}\"\n+ [eX, X_meta] = transformencode(target=X, spec=jspecR);\n+ # change the schema to reflect the encoded values\n+ getSchema = map(getSchema, \"x->x.replace(\\\"STRING\\\", \\\"INT64\\\")\")\n+ getSchema = map(getSchema, \"x->x.replace(\\\"BOOLEAN\\\", \\\"INT64\\\")\")\n+\n+}\n+# if no categorical value exist then just cast the frame into matrix\n+else\n+ eX = as.matrix(X)\n+\n+# extract the class label\n+eY = eX[, ncol(eX)]\n+eX = eX[, 1:ncol(eX) - 1]\n+\n+getMask = getMask[, 1:ncol(getMask) - 1] # strip the mask of class label\n+getFdMask = getFdMask[, 1:ncol(getFdMask) - 1] # strip the mask of class label\n+getSchema = getSchema[, 1:ncol(getSchema) - 1] # strip the mask of class label\n+# hyperparam for classifier\n+opt = matrix(\"0 100\", rows=1, cols=2)\n+\n+# get the cross validated accuracy on dirty dataset (only on training set)\n+d_accuracy = 0\n+d_accuracy = utils::classifyDirty(eX, eY, opt, getMask, weightedAccuracy, crossValidations)\n+\n+# get FD for IC operations\n+FD = discoverFD(X=replace(target=eX, pattern=NaN, replacement=1), Mask=getFdMask, threshold=0.8)\n+FD = (diag(matrix(1, rows=nrow(FD), cols=1)) ==0) * FD\n+FD = FD > 0\n+\n+metaList = list(mask=getMask, schema=getSchema, fd=FD)\n+targetClassification = list(target=targetApplicaton, cv=crossValidations, wAccuracy=weightedAccuracy,\n+ dirAcc = d_accuracy, mlHp = opt, cleanData = as.matrix(0))\n+\n+# # initialize output variables\n+pip = as.frame(\"NULL\"); hp = matrix(0,0,0); acc = matrix(0,0,0); features = as.frame(\"NULL\")\n+\n+\n+logical1 = frame([\"4\", \"MVI\", \"SCALE\", \"DUMMY\", \"DIM\", \"0\", \"0\", \"0\"], rows=1, cols=8)\n+# logical2 = frame([\"2\", \"MVI\", \"DUMMY\", \"0\", \"0\", \"0\", \"0\", \"0\"], rows=1, cols=8)\n+logical3 = frame([\"3\", \"MVI\", \"SCALE\", \"DUMMY\", \"0\", \"0\", \"0\", \"0\"], rows=1, cols=8)\n+logical4 = frame([\"6\", \"MVI\", \"OTLR\", \"CI\", \"SCALE\", \"DUMMY\", \"DIM\", \"0\"], rows=1, cols=8)\n+logical5 = frame([\"7\", \"MVI\", \"OTLR\", \"MVI\", \"CI\", \"SCALE\", \"DUMMY\", \"DIM\"], rows=1, cols=8)\n+logical6 = frame([\"6\", \"OTLR\", \"MVI\", \"CI\", \"SCALE\", \"DUMMY\", \"DIM\", \"0\"], rows=1, cols=8)\n+\n+# log = rbind(logical1, logical2)\n+log = rbind(logical1, logical3)\n+log = rbind(log, logical4)\n+log = rbind(log, logical5)\n+log = rbind(log, logical6)\n+\n+[logicalEnum, score, T] = lg::enumerateLogical(X=eX, y=eY, population=log, max_iter=max_iter, pipLength=pipLength, metaList=metaList,\n+ targetList=targetClassification, primitives=primitives, param=param, num_inst=num_inst, num_exec=num_exec, n_pop=n_pop, verbose=FALSE)\n+# [logicalEnum, score, T] = lg::enumerateLogical(X=eX, y=eY, population=log, max_iter=3, pipLength=10, metaList=metaList,\n+ # targetList=targetClassification, primitives=primitives, param=param, num_inst=4, num_exec=2, n_pop=4, verbose=FALSE)\n+\n+print(\"score of pipeline: \"+toString(score)+\" in \"+(T/60000)+\" mins\")\n+print(\"logicalENum \"+toString(logicalEnum))\n+\n+result = d_accuracy < score\n+print(\"result satisfied ------------\"+result)\n+\n+write(result , $O)\n+\n+\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2962] Initial implementation of Logical Pipelines optimizer Optimizer is based on evolutionary algorithm with constrained crossover and mutation this commit also contains some minor formatting cleanups in pipelines package Closes #1249.
49,722
12.04.2021 18:45:54
-7,200
c14198b75dcee7c77b4f68ca88807cb00d7ffe97
Federated rowProds, colProds Added fed col and row prod newlines and formatting Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederationUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/federated/FederationUtils.java", "diff": "@@ -203,6 +203,32 @@ public class FederationUtils {\n}\n}\n+ public static MatrixBlock aggProd(Future<FederatedResponse>[] ffr, FederationMap fedMap, AggregateUnaryOperator aop) {\n+ try {\n+ boolean rowFed = fedMap.getType() == FederationMap.FType.ROW;\n+ MatrixBlock ret = rowFed ?\n+ new MatrixBlock(ffr.length, (int) fedMap.getFederatedRanges()[0].getEndDims()[1], 1.0) :\n+ new MatrixBlock((int) fedMap.getFederatedRanges()[0].getEndDims()[0], ffr.length, 1.0);\n+ MatrixBlock res = rowFed ?\n+ new MatrixBlock(1, (int) fedMap.getFederatedRanges()[0].getEndDims()[1], 1.0) :\n+ new MatrixBlock((int) fedMap.getFederatedRanges()[0].getEndDims()[0], 1, 1.0);\n+\n+ for(int i = 0; i < ffr.length; i++) {\n+ MatrixBlock tmp = (MatrixBlock) ffr[i].get().getData()[0];\n+ if(rowFed)\n+ ret.copy(i, i, 0, ret.getNumColumns()-1, tmp, true);\n+ else\n+ ret.copy(0, ret.getNumRows()-1, i, i, tmp, true);\n+ }\n+\n+ LibMatrixAgg.aggregateUnaryMatrix(ret, res, aop);\n+ return res;\n+ }\n+ catch (Exception ex) {\n+ throw new DMLRuntimeException(ex);\n+ }\n+ }\n+\npublic static MatrixBlock aggMinMaxIndex(Future<FederatedResponse>[] ffr, boolean isMin, FederationMap map) {\ntry {\nMatrixBlock prev = (MatrixBlock) ffr[0].get().getData()[0];\n@@ -410,6 +436,8 @@ public class FederationUtils {\nreturn aggAdd(ffr);\nelse if( aop.aggOp.increOp.fn instanceof Mean )\nreturn aggMean(ffr, map);\n+ else if(aop.aggOp.increOp.fn instanceof Multiply)\n+ return aggProd(ffr, map, aop);\nelse if (aop.aggOp.increOp.fn instanceof Builtin) {\nif ((((Builtin) aop.aggOp.increOp.fn).getBuiltinCode() == BuiltinCode.MIN ||\n((Builtin) aop.aggOp.increOp.fn).getBuiltinCode() == BuiltinCode.MAX)) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedColAggregateTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedColAggregateTest.java", "diff": "@@ -41,6 +41,7 @@ public class FederatedColAggregateTest extends AutomatedTestBase {\nprivate final static String TEST_NAME2 = \"FederatedColMeanTest\";\nprivate final static String TEST_NAME3 = \"FederatedColMaxTest\";\nprivate final static String TEST_NAME4 = \"FederatedColMinTest\";\n+ private final static String TEST_NAME5 = \"FederatedColProdTest\";\nprivate final static String TEST_NAME10 = \"FederatedColVarTest\";\nprivate final static String TEST_DIR = \"functions/federated/aggregate/\";\n@@ -58,13 +59,13 @@ public class FederatedColAggregateTest extends AutomatedTestBase {\npublic static Collection<Object[]> data() {\nreturn Arrays.asList(\nnew Object[][] {\n- {10, 1000, false},\n+// {10, 1000, false},\n{1000, 40, true},\n});\n}\nprivate enum OpType {\n- SUM, MEAN, MAX, MIN, VAR\n+ SUM, MEAN, MAX, MIN, VAR, PROD\n}\n@Override\n@@ -75,6 +76,7 @@ public class FederatedColAggregateTest extends AutomatedTestBase {\naddTestConfiguration(TEST_NAME3, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME3, new String[] {\"S\"}));\naddTestConfiguration(TEST_NAME4, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME4, new String[] {\"S\"}));\naddTestConfiguration(TEST_NAME10, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME10, new String[] {\"S\"}));\n+ addTestConfiguration(TEST_NAME5, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME5, new String[] {\"S\"}));\n}\n@Test\n@@ -103,6 +105,11 @@ public class FederatedColAggregateTest extends AutomatedTestBase {\nrunAggregateOperationTest(OpType.VAR, ExecMode.SINGLE_NODE);\n}\n+ @Test\n+ public void testColProdDenseMatrixCP() {\n+ runAggregateOperationTest(OpType.PROD, ExecMode.SINGLE_NODE);\n+ }\n+\nprivate void runAggregateOperationTest(OpType type, ExecMode execMode) {\nboolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\nExecMode platformOld = rtplatform;\n@@ -127,6 +134,9 @@ public class FederatedColAggregateTest extends AutomatedTestBase {\ncase VAR:\nTEST_NAME = TEST_NAME10;\nbreak;\n+ case PROD:\n+ TEST_NAME = TEST_NAME5;\n+ break;\n}\ngetAndLoadTestConfiguration(TEST_NAME);\n@@ -140,16 +150,16 @@ public class FederatedColAggregateTest extends AutomatedTestBase {\nc = cols;\n}\n- double[][] X1 = getRandomMatrix(r, c, 1, 3, 1, 3);\n- double[][] X2 = getRandomMatrix(r, c, 1, 3, 1, 7);\n- double[][] X3 = getRandomMatrix(r, c, 1, 3, 1, 8);\n- double[][] X4 = getRandomMatrix(r, c, 1, 3, 1, 9);\n+ double[][] X1 = getRandomMatrix(r, c, 3, 3, 1, 3);\n+ double[][] X2 = getRandomMatrix(r, c, 3, 3, 1, 7);\n+ double[][] X3 = getRandomMatrix(r, c, 3, 3, 1, 8);\n+ double[][] X4 = getRandomMatrix(r, c, 3, 3, 1, 9);\nMatrixCharacteristics mc = new MatrixCharacteristics(r, c, blocksize, r * c);\n- writeInputMatrixWithMTD(\"X1\", X1, false, mc);\n- writeInputMatrixWithMTD(\"X2\", X2, false, mc);\n- writeInputMatrixWithMTD(\"X3\", X3, false, mc);\n- writeInputMatrixWithMTD(\"X4\", X4, false, mc);\n+ writeInputMatrixWithMTD(\"X1\", X1, true, mc);\n+ writeInputMatrixWithMTD(\"X2\", X2, true, mc);\n+ writeInputMatrixWithMTD(\"X3\", X3, true, mc);\n+ writeInputMatrixWithMTD(\"X4\", X4, true, mc);\n// empty script name because we don't execute any script, just start the worker\nfullDMLScriptName = \"\";\n@@ -189,7 +199,7 @@ public class FederatedColAggregateTest extends AutomatedTestBase {\nrunTest(true, false, null, -1);\n// compare via files\n- compareResults(type == FederatedColAggregateTest.OpType.VAR ? 1e-2 : 1e-9);\n+ compareResults((type == FederatedColAggregateTest.OpType.VAR) || (type == OpType.PROD) ? 1e-2 : 1e-9);\nString fedInst = \"fed_uac\";\n@@ -209,6 +219,9 @@ public class FederatedColAggregateTest extends AutomatedTestBase {\ncase VAR:\nAssert.assertTrue(heavyHittersContainsString(fedInst.concat(\"var\")));\nbreak;\n+ case PROD:\n+ Assert.assertTrue(heavyHittersContainsString(fedInst.concat(\"*\")));\n+ break;\n}\n// check that federated input files are still existing\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedRowAggregateTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedRowAggregateTest.java", "diff": "@@ -42,6 +42,7 @@ public class FederatedRowAggregateTest extends AutomatedTestBase {\nprivate final static String TEST_NAME7 = \"FederatedRowMaxTest\";\nprivate final static String TEST_NAME8 = \"FederatedRowMinTest\";\nprivate final static String TEST_NAME9 = \"FederatedRowVarTest\";\n+ private final static String TEST_NAME10 = \"FederatedRowProdTest\";\nprivate final static String TEST_DIR = \"functions/federated/aggregate/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + FederatedRowAggregateTest.class.getSimpleName() + \"/\";\n@@ -64,7 +65,7 @@ public class FederatedRowAggregateTest extends AutomatedTestBase {\n}\nprivate enum OpType {\n- SUM, MEAN, MAX, MIN, VAR\n+ SUM, MEAN, MAX, MIN, VAR, PROD\n}\n@Override\n@@ -75,6 +76,7 @@ public class FederatedRowAggregateTest extends AutomatedTestBase {\naddTestConfiguration(TEST_NAME7, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME7, new String[] {\"S\"}));\naddTestConfiguration(TEST_NAME8, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME8, new String[] {\"S\"}));\naddTestConfiguration(TEST_NAME9, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME9, new String[] {\"S\"}));\n+ addTestConfiguration(TEST_NAME10, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME10, new String[] {\"S\"}));\n}\n@Test\n@@ -102,6 +104,11 @@ public class FederatedRowAggregateTest extends AutomatedTestBase {\nrunAggregateOperationTest(OpType.VAR, ExecMode.SINGLE_NODE);\n}\n+ @Test\n+ public void testRowProdDenseMatrixCP() {\n+ runAggregateOperationTest(OpType.PROD, ExecMode.SINGLE_NODE);\n+ }\n+\nprivate void runAggregateOperationTest(OpType type, ExecMode execMode) {\nboolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\nExecMode platformOld = rtplatform;\n@@ -126,6 +133,9 @@ public class FederatedRowAggregateTest extends AutomatedTestBase {\ncase VAR:\nTEST_NAME = TEST_NAME9;\nbreak;\n+ case PROD:\n+ TEST_NAME = TEST_NAME10;\n+ break;\n}\ngetAndLoadTestConfiguration(TEST_NAME);\n@@ -139,10 +149,10 @@ public class FederatedRowAggregateTest extends AutomatedTestBase {\nc = cols;\n}\n- double[][] X1 = getRandomMatrix(r, c, 1, 3, 1, 3);\n- double[][] X2 = getRandomMatrix(r, c, 1, 3, 1, 7);\n- double[][] X3 = getRandomMatrix(r, c, 1, 3, 1, 8);\n- double[][] X4 = getRandomMatrix(r, c, 1, 3, 1, 9);\n+ double[][] X1 = getRandomMatrix(r, c, 3, 3, 1, 3);\n+ double[][] X2 = getRandomMatrix(r, c, 3, 3, 1, 7);\n+ double[][] X3 = getRandomMatrix(r, c, 3, 3, 1, 8);\n+ double[][] X4 = getRandomMatrix(r, c, 3, 3, 1, 9);\nMatrixCharacteristics mc = new MatrixCharacteristics(r, c, blocksize, r * c);\nwriteInputMatrixWithMTD(\"X1\", X1, false, mc);\n@@ -208,6 +218,9 @@ public class FederatedRowAggregateTest extends AutomatedTestBase {\ncase VAR:\nAssert.assertTrue(heavyHittersContainsString(fedInst.concat(\"var\")));\nbreak;\n+ case PROD:\n+ Assert.assertTrue(heavyHittersContainsString(fedInst.concat(\"*\")));\n+ break;\n}\n// check that federated input files are still existing\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/aggregate/FederatedColProdTest.R", "diff": "+#-------------------------------------------------------------\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+args<-commandArgs(TRUE)\n+options(digits=22)\n+library(\"Matrix\")\n+library(\"matrixStats\")\n+\n+X1 = as.matrix(readMM(paste(args[1], \"X1.mtx\", sep=\"\")));\n+X2 = as.matrix(readMM(paste(args[1], \"X2.mtx\", sep=\"\")));\n+X3 = as.matrix(readMM(paste(args[1], \"X3.mtx\", sep=\"\")));\n+X4 = as.matrix(readMM(paste(args[1], \"X4.mtx\", sep=\"\")));\n+X = rbind(X1, X2, X3, X4)\n+R = colProds(X)\n+writeMM(as(R, \"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/aggregate/FederatedColProdTest.dml", "diff": "+#-------------------------------------------------------------\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+\n+if ($rP) {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+} else {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows, $cols/4), list(0,$cols/4), list($rows, $cols/2),\n+ list(0,$cols/2), list($rows, 3*($cols/4)), list(0, 3*($cols/4)), list($rows, $cols)));\n+}\n+\n+s = colProds(A);\n+write(s, $out_S);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/aggregate/FederatedColProdTestReference.dml", "diff": "+#-------------------------------------------------------------\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+if($6) { A = rbind(read($1), read($2), read($3), read($4)); }\n+else { A = cbind(read($1), read($2), read($3), read($4)); }\n+\n+s = colProds(A);\n+write(s, $5);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/aggregate/FederatedRowProdTest.dml", "diff": "+#-------------------------------------------------------------\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+\n+if ($rP) {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+} else {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows, $cols/4), list(0,$cols/4), list($rows, $cols/2),\n+ list(0,$cols/2), list($rows, 3*($cols/4)), list(0, 3*($cols/4)), list($rows, $cols)));\n+}\n+\n+s = rowProds(A);\n+write(s, $out_S);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/aggregate/FederatedRowProdTestReference.dml", "diff": "+#-------------------------------------------------------------\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+if($6) { A = rbind(read($1), read($2), read($3), read($4)); }\n+else { A = cbind(read($1), read($2), read($3), read($4)); }\n+\n+s = rowProds(A);\n+write(s, $5);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2542] Federated rowProds, colProds - Added fed col and row prod - newlines and formatting Closes #1248
49,706
04.05.2021 17:58:51
-7,200
5af203a001229a6f4608040ed7e558f59ffe937c
[MINOR] CLA add empty check Add a check for empty colum groups in case of only null columns in compression factory. Add edge case tests for empty and const colGroups Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupCompressed.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupCompressed.java", "diff": "@@ -90,7 +90,9 @@ public abstract class ColGroupCompressed extends AColGroup {\nprotected abstract boolean sameIndexStructure(ColGroupCompressed that);\npublic void leftMultByMatrix(MatrixBlock matrix, double[] result, int numCols, int rl, int ru) {\n- if(matrix.isInSparseFormat())\n+ if(matrix.isEmpty())\n+ return;\n+ else if(matrix.isInSparseFormat())\nleftMultBySparseMatrix(matrix.getSparseBlock(), result, matrix.getNumRows(), numCols, rl, ru);\nelse {\nleftMultByMatrix(matrix.getDenseBlockValues(), result, matrix.getNumRows(), numCols, rl, ru);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupFactory.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupFactory.java", "diff": "@@ -161,11 +161,6 @@ public class ColGroupFactory {\nfor(int col : colIndexes)\nif(sb.isEmpty(col))\nreturn compressColGroupAndExtractEmptyColumns(in, colIndexes, compSettings);\n-\n- // return (compRatios == null) ? compressColGroupForced(in,\n- // colIndexes,\n- // compSettings) : compressColGroupCorrecting(in, compRatios, colIndexes,\n- // compSettings);\nreturn Collections.singletonList(compressColGroupForced(in, colIndexes, compSettings));\n}\nelse\n@@ -185,9 +180,14 @@ public class ColGroupFactory {\nv.appendValue(col);\n}\nAColGroup empty = compressColGroupForced(in, e.extractValues(true), compSettings);\n+ if(v.size() > 0) {\nAColGroup colGroup = compressColGroupForced(in, v.extractValues(true), compSettings);\nreturn Arrays.asList(empty, colGroup);\n}\n+ else {\n+ return Collections.singletonList(empty);\n+ }\n+ }\nprivate static AColGroup compressColGroupForced(MatrixBlock in, int[] colIndexes,\nCompressionSettings compSettings) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupUncompressed.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/colgroup/ColGroupUncompressed.java", "diff": "@@ -163,7 +163,9 @@ public class ColGroupUncompressed extends AColGroup {\nfinal int nCol = _colIndexes.length;\nfinal int tCol = target.getNumColumns();\nlong nnz = 0;\n- if(_data.isInSparseFormat()) {\n+ if(_data.isEmpty())\n+ return;\n+ else if(_data.isInSparseFormat()) {\nSparseBlock sb = _data.getSparseBlock();\nfor(int row = rl; row < ru; row++, offT += tCol) {\nif(!sb.isEmpty(row)) {\n@@ -539,10 +541,17 @@ public class ColGroupUncompressed extends AColGroup {\npublic void tsmm(double[] result, int numColumns) {\nMatrixBlock tmp = new MatrixBlock(_colIndexes.length, _colIndexes.length, true);\nLibMatrixMult.matrixMultTransposeSelf(_data, tmp, true, false);\n+ if(tmp.getDenseBlock() == null && tmp.getSparseBlock() == null)\n+ return;\n+ else if(tmp.isInSparseFormat()) {\n+ throw new NotImplementedException(\"not Implemented sparse output of tsmm in compressed ColGroup.\");\n+ }\n+ else {\ndouble[] tmpV = tmp.getDenseBlockValues();\nfor(int i = 0, offD = 0, offT = 0; i < numColumns; i++, offD += numColumns, offT += _colIndexes.length)\nfor(int j = i; j < numColumns; j++)\nresult[offD + _colIndexes[j]] += tmpV[offT + j];\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/component/compress/CompressedTestBase.java", "new_path": "src/test/java/org/apache/sysds/test/component/compress/CompressedTestBase.java", "diff": "@@ -75,29 +75,17 @@ import org.junit.runners.Parameterized.Parameters;\npublic abstract class CompressedTestBase extends TestBase {\nprotected static final Log LOG = LogFactory.getLog(CompressedTestBase.class.getName());\n- protected static SparsityType[] usedSparsityTypes = new SparsityType[] {SparsityType.FULL,\n- // SparsityType.DENSE,\n- SparsityType.SPARSE,\n- // SparsityType.ULTRA_SPARSE,\n- // SparsityType.EMPTY\n- };\n+ protected static SparsityType[] usedSparsityTypes = new SparsityType[] {SparsityType.FULL, SparsityType.SPARSE,};\n- protected static ValueType[] usedValueTypes = new ValueType[] {\n- // ValueType.RAND,\n- // ValueType.CONST,\n- ValueType.RAND_ROUND, ValueType.OLE_COMPRESSIBLE, ValueType.RLE_COMPRESSIBLE,};\n+ protected static ValueType[] usedValueTypes = new ValueType[] {ValueType.RAND_ROUND, ValueType.OLE_COMPRESSIBLE,\n+ ValueType.RLE_COMPRESSIBLE,};\nprotected static ValueRange[] usedValueRanges = new ValueRange[] {ValueRange.SMALL, ValueRange.NEGATIVE,\n- // ValueRange.LARGE,\n- ValueRange.BYTE,\n- // ValueRange.BOOLEAN,\n- };\n+ ValueRange.BYTE};\nprotected static OverLapping[] overLapping = new OverLapping[] {\n// OverLapping.COL,\n- OverLapping.PLUS,\n- OverLapping.MATRIX,\n- OverLapping.NONE,\n+ OverLapping.PLUS, OverLapping.MATRIX, OverLapping.NONE,\n// OverLapping.MATRIX_PLUS,\n// OverLapping.SQUASH,\n// OverLapping.MATRIX_MULT_NEGATIVE\n@@ -129,14 +117,17 @@ public abstract class CompressedTestBase extends TestBase {\n.setInvestigateEstimate(true),\nnew CompressionSettingsBuilder().setSamplingRatio(0.1).setSeed(compressionSeed).setTransposeInput(\"true\")\n.setColumnPartitioner(PartitionerType.BIN_PACKING).setInvestigateEstimate(true),\n+ new CompressionSettingsBuilder().setSamplingRatio(0.1).setSeed(compressionSeed).setTransposeInput(\"true\")\n+ .setColumnPartitioner(PartitionerType.STATIC).setInvestigateEstimate(true),\n+ // Forced Uncompressed tests\nnew CompressionSettingsBuilder().setValidCompressions(EnumSet.of(CompressionType.UNCOMPRESSED)),\n// new CompressionSettingsBuilder().setSamplingRatio(0.1).setSeed(compressionSeed).setInvestigateEstimate(true),\n// new CompressionSettingsBuilder().setSamplingRatio(1.0).setSeed(compressionSeed).setInvestigateEstimate(true)\n// .setAllowSharedDictionary(false).setmaxStaticColGroupCoCode(1),\n- // // // // LOSSY TESTS!\n+ // LOSSY TESTS!\n// new CompressionSettingsBuilder().setSamplingRatio(0.1).setSeed(compressionSeed)\n// .setValidCompressions(EnumSet.of(CompressionType.DDC)).setInvestigateEstimate(true).setLossy(true).create(),\n@@ -176,8 +167,6 @@ public abstract class CompressedTestBase extends TestBase {\nprotected CompressionStatistics cmbStats;\n// Decompressed Result\n- // protected MatrixBlock cmbDeCompressed;\n- // protected double[][] deCompressed;\n/** number of threads used for the operation */\nprotected final int _k;\n@@ -296,6 +285,12 @@ public abstract class CompressedTestBase extends TestBase {\nfor(MatrixTypology mt : usedMatrixTypology)\nfor(OverLapping ov : overLapping)\ntests.add(new Object[] {st, vt, vr, cs, mt, ov});\n+ for(CompressionSettingsBuilder cs : usedCompressionSettings)\n+ for(MatrixTypology mt : usedMatrixTypology)\n+ for(OverLapping ov : overLapping) {\n+ tests.add(new Object[] {SparsityType.EMPTY, ValueType.RAND, ValueRange.BOOLEAN, cs, mt, ov});\n+ tests.add(new Object[] {SparsityType.FULL, ValueType.CONST, ValueRange.LARGE, cs, mt, ov});\n+ }\nreturn tests;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] CLA add empty check - Add a check for empty colum groups in case of only null columns in compression factory. - Add edge case tests for empty and const colGroups Closes #1253
49,698
05.05.2021 22:06:10
-19,080
947ec2ab534f664662e94cd719ca3b12ef9f8337
Preliminary instruction to run an example spark job
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/staging/google-cloud/README.md", "diff": "+<!--\n+{% comment %}\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+## Create a dataproc cluster\n+\n+Create a cluster name\n+```sh\n+CLUSTERNAME=dp-systemds\n+```\n+\n+Set Dataproc cluster region\n+```sh\n+gcloud config set dataproc/region us-central1\n+```\n+\n+Now, create a new cluster\n+\n+[`gcloud dataproc clusters create` reference](https://cloud.google.com/sdk/gcloud/reference/dataproc/clusters/create)\n+```sh\n+gcloud dataproc clusters create ${CLUSTERNAME} \\\n+ --scopes=cloud-platform \\\n+ --tags systemds \\\n+ --zone=us-central1-c \\\n+ --worker-machine-type n1-standard-2 \\\n+ --worker-boot-disk-size 500 \\\n+ --master-machine-type n1-standard-2 \\\n+ --master-boot-disk-size 500 \\\n+ --image-version 2.0\n+```\n+\n+## Submit a Spark job to the cluster\n+\n+Jobs can be submitted via a Cloud Dataproc API\n+[`jobs.submit`](https://cloud.google.com/dataproc/docs/reference/rest/v1/projects.regions.jobs/submit) request\n+\n+Submit an example job using `gcloud` tool from the Cloud Shell command line\n+\n+```sh\n+gcloud dataproc jobs submit spark --cluster ${CLUSTER_NAME} \\\n+ --class org.apache.spark.examples.SparkPi \\\n+ --jars file:///usr/lib/spark/examples/jars/spark-examples.jar -- 1000\n+```\n" } ]
Java
Apache License 2.0
apache/systemds
Preliminary instruction to run an example spark job
49,698
05.05.2021 22:54:17
-19,080
c2d7f9b5df11cee71b551fbefa945265248f535f
Cluster resizing, ssh and tags usage
[ { "change_type": "MODIFY", "old_path": "scripts/staging/google-cloud/README.md", "new_path": "scripts/staging/google-cloud/README.md", "diff": "@@ -56,3 +56,67 @@ gcloud dataproc jobs submit spark --cluster ${CLUSTER_NAME} \\\n--class org.apache.spark.examples.SparkPi \\\n--jars file:///usr/lib/spark/examples/jars/spark-examples.jar -- 1000\n```\n+\n+\n+### Job info and connect\n+\n+List all the jobs:\n+\n+```sh\n+gcloud dataproc jobs list --cluster ${CLUSTERNAME}\n+```\n+\n+To get output of a specific job note `jobID` and in the below command\n+replace `jobID`.\n+\n+```sh\n+gcloud dataproc jobs wait jobID\n+```\n+\n+### Resizing the cluster\n+\n+For intensive computations, to add more nodes to the cluster either to speed up.\n+\n+Existing cluster configuration\n+\n+```sh\n+gcloud dataproc clusters describe ${CLUSTERNAME}\n+```\n+\n+Add preemptible nodes to increase cluster size:\n+\n+```sh\n+gcloud dataproc clusters update ${CLUSTERNAME} --num-preemptible-workers=1\n+```\n+\n+Note: `workerConfig` and `secondaryWorkerConfig` will be present.\n+\n+### SSH into the cluster\n+\n+SSH into the cluster (master node) would provide fine grained control of the cluster.\n+\n+```sh\n+gcloud compute ssh ${CLUSTERNAME}-m --zone=us-central1-c\n+```\n+\n+Note: For the first time, we run `ssh` command on Cloud Shell, it will generate SSH keys\n+for your account.\n+\n+The `--scopes=cloud-platform` would allow us to run gcloud inside the cluster too.\n+For example,\n+\n+```sh\n+gcloud dataproc clusters list --region=us-central1\n+```\n+\n+to exit the cluster master instance\n+\n+```sh\n+logout\n+```\n+\n+### Tags\n+\n+A `--tags` option allows us to add a tag to each node in the cluster. Firewall rules\n+can be applied to each node with conditionally adding flags.\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2971] Cluster resizing, ssh and tags usage
49,698
06.05.2021 01:55:25
-19,080
28da55fea4c8c1c45ba215ccb4fc29a7d4014025
[SYSTEMDS-2869][DOC] Built-in functions KNN and KNNBF
[ { "change_type": "MODIFY", "old_path": "docs/site/builtins-reference.md", "new_path": "docs/site/builtins-reference.md", "diff": "@@ -43,6 +43,7 @@ limitations under the License.\n* [`imputeByFD`-Function](#imputeByFD-function)\n* [`intersect`-Function](#intersect-function)\n* [`KMeans`-Function](#KMeans-function)\n+ * [`KNN`-function](#KNN-function)\n* [`lm`-Function](#lm-function)\n* [`lmDS`-Function](#lmds-function)\n* [`lmCG`-Function](#lmcg-function)\n@@ -677,6 +678,55 @@ X = rand (rows = 3972, cols = 972)\nkmeans(X = X, k = 20, runs = 10, max_iter = 5000, eps = 0.000001, is_verbose = FALSE, avg_sample_size_per_centroid = 50, seed = -1)\n```\n+## `KNN`-Function\n+\n+The knn() implements the KNN (K Nearest Neighbor) algorithm.\n+\n+### Usage\n+\n+```r\n+[NNR, PR, FI] = knn(Train, Test, CL, k_value)\n+```\n+\n+### Arguments\n+\n+| Name | Type | Default | Description |\n+| :--------- | :-------------- | :--------- | :---------- |\n+| Train | Matrix | required | The input matrix as features |\n+| Test | Matrix | required | Number of centroids |\n+| CL | Matrix | Optional | The input matrix as target |\n+| CL_T | Integer | `0` | The target type of matrix CL whether columns in CL are continuous ( =1 ) or categorical ( =2 ) or not specified ( =0 ) |\n+| trans_continuous | Boolean | `FALSE` | Whether to transform continuous features to [-1,1] |\n+| k_value | int | `5` | k value for KNN, ignore if select_k enable |\n+| select_k | Boolean | `FALSE` | Use k selection algorithm to estimate k ( TRUE means yes ) |\n+| k_min | int | `1`| Min k value( available if select_k = 1 ) |\n+| k_max | int | `100` | Max k value( available if select_k = 1 ) |\n+| select_feature | Boolean | `FALSE` | Use feature selection algorithm to select feature ( TRUE means yes ) |\n+| feature_max | int | `10` | Max feature selection |\n+| interval | int | `1000` | Interval value for K selecting ( available if select_k = 1 ) |\n+| feature_importance | Boolean | `FALSE` | Use feature importance algorithm to estimate each feature ( TRUE means yes ) |\n+| predict_con_tg | int | `0` | Continuous target predict function: mean(=0) or median(=1) |\n+| START_SELECTED | Matrix | Optional | feature selection initial value |\n+\n+### Returns\n+\n+| Type | Description |\n+| :----- | :---------- |\n+| Matrix | NNR |\n+| Matrix | PR |\n+| Matrix | Feature importance value |\n+\n+### Example\n+\n+```r\n+X = rand(rows = 100, cols = 20)\n+T = rand(rows= 3, cols = 20) # query rows, and columns\n+CL = matrix(seq(1,100), 100, 1)\n+k = 3\n+[NNR, PR, FI] = knn(Train=X, Test=T, CL=CL, k_value=k, predict_con_tg=1)\n+```\n+\n+\n## `lm`-Function\nThe `lm`-function solves linear regression using either the **direct solve method** or the **conjugate gradient algorithm**\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2869][DOC] Built-in functions KNN and KNNBF (#1255)
49,698
07.05.2021 01:17:45
-19,080
95e8a2852e7084567cf08cda1df98fe83a9368f6
[SYSTEMDS-2891][DOC] Gaussian classifier builtin
[ { "change_type": "MODIFY", "old_path": "docs/site/builtins-reference.md", "new_path": "docs/site/builtins-reference.md", "diff": "@@ -34,6 +34,7 @@ limitations under the License.\n* [`dist`-Function](#dist-function)\n* [`dmv`-Function](#dmv-function)\n* [`ema`-Function](#ema-function)\n+ * [`gaussianClassifier`-Function](#gaussianClassifier-function)\n* [`glm`-Function](#glm-function)\n* [`gridSearch`-Function](#gridSearch-function)\n* [`hyperband`-Function](#hyperband-function)\n@@ -341,7 +342,48 @@ Z = dmv(X=A, threshold=0.9)\nZ = dmv(X=A, threshold=0.9, replace=\"NaN\")\n```\n+## `gaussianClassifier`-Function\n+The `gaussianClassifier`-function computes prior probabilities, means, determinants, and inverse\n+covariance matrix per class.\n+\n+Classification is as per $$ p(C=c | x) = p(x | c) * p(c) $$\n+Where $$p(x | c)$$ is the (multivariate) Gaussian P.D.F. for class $$c$$, and $$p(c)$$ is the\n+prior probability for class $$c$$.\n+\n+### Usage\n+\n+```r\n+[prior, means, covs, det] = gaussianClassifier(D, C, varSmoothing)\n+```\n+\n+### Arguments\n+\n+| Name | Type | Default | Description |\n+| :--- | :------------- | :------- | :---------- |\n+| D | Matrix[Double] | required | Input matrix (training set |\n+| C | Matrix[Double] | required | Target vector |\n+| varSmoothing | Double | `1e-9` | Smoothing factor for variances |\n+| verbose | Boolean | `TRUE` | Print accuracy of the training set |\n+\n+### Returns\n+\n+| Name | Type | Description |\n+| :--- | :------------- | :--------------- |\n+| classPriors | Matrix[Double] | Vector storing the class prior probabilities |\n+| classMeans | Matrix[Double] | Matrix storing the means of the classes |\n+| classInvCovariances | List[Unknown] | List of inverse covariance matrices |\n+| determinants | Matrix[Double] | Vector storing the determinants of the classes |\n+\n+### Example\n+\n+```r\n+\n+X = rand (rows = 200, cols = 50 )\n+y = X %*% rand(rows = ncol(X), cols = 1)\n+\n+[prior, means, covs, det] = gaussianClassifier(D=X, C=y, varSmoothing=1e-9)\n+```\n## `glm`-Function\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2891][DOC] Gaussian classifier builtin (#1263)
49,698
07.05.2021 11:30:05
-19,080
caa0ca94ebb5d2f3504ba59fe44616a425ed11df
[SYSTEMDS-2842][DOC] cspline builtin doc cspline builtin has two modes CG, DS - correspondingly named as `csplineCG` and `csplineDS`.
[ { "change_type": "MODIFY", "old_path": "docs/site/builtins-reference.md", "new_path": "docs/site/builtins-reference.md", "diff": "@@ -28,6 +28,9 @@ limitations under the License.\n* [`tensor`-Function](#tensor-function)\n* [DML-Bodied Built-In functions](#dml-bodied-built-in-functions)\n* [`confusionMatrix`-Function](#confusionmatrix-function)\n+ * [`cspline`-Function](#cspline-function)\n+ * [`csplineCG`-Function](#csplineCG-function)\n+ * [`csplineDS`-Function](#csplineDS-function)\n* [`cvlm`-Function](#cvlm-function)\n* [`DBSCAN`-Function](#DBSCAN-function)\n* [`discoverFD`-Function](#discoverFD-function)\n@@ -187,6 +190,122 @@ y = toOneHot(X, numClasses)\n[ConfusionSum, ConfusionAvg] = confusionMatrix(P=z, Y=y)\n```\n+## `cspline`-Function\n+\n+This `cspline`-function solves Cubic spline interpolation. The function usages natural spline with $$ q_1''(x_0) == q_n''(x_n) == 0.0 $$.\n+By default, it calculates via `csplineDS`-function.\n+\n+Algorithm reference: https://en.wikipedia.org/wiki/Spline_interpolation#Algorithm_to_find_the_interpolating_cubic_spline\n+\n+### Usage\n+```r\n+[result, K] = cspline(X, Y, inp_x, tol, maxi)\n+```\n+\n+### Arguments\n+\n+| Name | Type | Default | Description |\n+| :--- | :------------- | :------ | :---------- |\n+| X | Matrix[Double] | --- | 1-column matrix of x values knots. It is assumed that x values are monotonically increasing and there is no duplicate points in X |\n+| Y | Matrix[Double] | --- | 1-column matrix of corresponding y values knots |\n+| inp_x | Double | --- | the given input x, for which the cspline will find predicted y |\n+| mode | String | `DS` | Specifies that method for cspline (DS - Direct Solve, CG - Conjugate Gradient) |\n+| tol | Double | `-1.0` | Tolerance (epsilon); conjugate gradient procedure terminates early if L2 norm of the beta-residual is less than tolerance * its initial norm |\n+| maxi | Integer | `-1` | Maximum number of conjugate gradient iterations, 0 = no maximum |\n+\n+### Returns\n+\n+| Name | Type | Description |\n+| :----------- | :------------- | :---------- |\n+| pred_Y | Matrix[Double] | Predicted values |\n+| K | Matrix[Double] | Matrix of k parameters |\n+\n+### Example\n+\n+```r\n+num_rec = 100 # Num of records\n+X = matrix(seq(1,num_rec), num_rec, 1)\n+Y = round(rand(rows = 100, cols = 1, min = 1, max = 5))\n+inp_x = 4.5\n+tolerance = 0.000001\n+max_iter = num_rec\n+[result, K] = cspline(X=X, Y=Y, inp_x=inp_x, tol=tolerance, maxi=max_iter)\n+```\n+\n+## `csplineCG`-Function\n+\n+This `csplineCG`-function solves Cubic spline interpolation with conjugate gradient method. Usage will be same as `cspline`-function.\n+\n+### Usage\n+```r\n+[result, K] = csplineCG(X, Y, inp_x, tol, maxi)\n+```\n+\n+### Arguments\n+\n+| Name | Type | Default | Description |\n+| :--- | :------------- | :------ | :---------- |\n+| X | Matrix[Double] | --- | 1-column matrix of x values knots. It is assumed that x values are monotonically increasing and there is no duplicate points in X |\n+| Y | Matrix[Double] | --- | 1-column matrix of corresponding y values knots |\n+| inp_x | Double | --- | the given input x, for which the cspline will find predicted y |\n+| tol | Double | `-1.0` | Tolerance (epsilon); conjugate gradient procedure terminates early if L2 norm of the beta-residual is less than tolerance * its initial norm |\n+| maxi | Integer | `-1` | Maximum number of conjugate gradient iterations, 0 = no maximum |\n+\n+### Returns\n+\n+| Name | Type | Description |\n+| :----------- | :------------- | :---------- |\n+| pred_Y | Matrix[Double] | Predicted values |\n+| K | Matrix[Double] | Matrix of k parameters |\n+\n+### Example\n+\n+```r\n+num_rec = 100 # Num of records\n+X = matrix(seq(1,num_rec), num_rec, 1)\n+Y = round(rand(rows = 100, cols = 1, min = 1, max = 5))\n+inp_x = 4.5\n+tolerance = 0.000001\n+max_iter = num_rec\n+[result, K] = csplineCG(X=X, Y=Y, inp_x=inp_x, tol=tolerance, maxi=max_iter)\n+```\n+\n+## `csplineDS`-Function\n+\n+This `csplineDS`-function solves Cubic spline interpolation with direct solver method.\n+\n+### Usage\n+```r\n+[result, K] = csplineDS(X, Y, inp_x)\n+```\n+\n+### Arguments\n+\n+| Name | Type | Default | Description |\n+| :--- | :------------- | :------ | :---------- |\n+| X | Matrix[Double] | --- | 1-column matrix of x values knots. It is assumed that x values are monotonically increasing and there is no duplicate points in X |\n+| Y | Matrix[Double] | --- | 1-column matrix of corresponding y values knots |\n+| inp_x | Double | --- | the given input x, for which the cspline will find predicted y |\n+\n+### Returns\n+\n+| Name | Type | Description |\n+| :----------- | :------------- | :---------- |\n+| pred_Y | Matrix[Double] | Predicted values |\n+| K | Matrix[Double] | Matrix of k parameters |\n+\n+### Example\n+\n+```r\n+num_rec = 100 # Num of records\n+X = matrix(seq(1,num_rec), num_rec, 1)\n+Y = round(rand(rows = 100, cols = 1, min = 1, max = 5))\n+inp_x = 4.5\n+\n+[result, K] = csplineDS(X=X, Y=Y, inp_x=inp_x)\n+```\n+\n+\n## `cvlm`-Function\nThe `cvlm`-function is used for cross-validation of the provided data model. This function follows a non-exhaustive\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2842][DOC] cspline builtin doc (#1265) cspline builtin has two modes CG, DS - correspondingly named as `csplineCG` and `csplineDS`.
49,698
08.05.2021 07:07:17
-19,080
1cfbfef9675ccad567b641e417d1829179a41cb6
[MINOR] Update spark runtime version in databricks notebook make sure setup instructions are up-to-date and relevant
[ { "change_type": "MODIFY", "old_path": "notebooks/databricks/MLContext.scala", "new_path": "notebooks/databricks/MLContext.scala", "diff": "+// Databricks notebook source\n/*\n* Licensed to the Apache Software Foundation (ASF) under one\n* or more contributor license agreements. See the NOTICE file\n* under the License.\n*/\n-// Databricks notebook source\n+\n+// COMMAND ----------\n+\n// MAGIC %md # Apache SystemDS on Databricks in 5 minutes\n// COMMAND ----------\n// MAGIC 1. In the sidebar, right-click the **Clusters** button and open the link in a new window.\n// MAGIC 1. On the Clusters page, click **Create Cluster**.\n// MAGIC 1. Name the cluster **Quickstart**.\n-// MAGIC 1. In the Databricks Runtime Version drop-down, select **6.3 (Scala 2.11, Spark 2.4.4)**.\n+// MAGIC 1. In the Databricks Runtime Version drop-down, select **6.4 (Scala 2.11, Spark 2.4.5)**.\n// MAGIC 1. Click **Create Cluster**.\n// MAGIC 1. Attach `SystemDS.jar` file to the libraries\n" }, { "change_type": "MODIFY", "old_path": "notebooks/databricks/README.md", "new_path": "notebooks/databricks/README.md", "diff": "-#### Setup SystemDS on Databricks platform\n+#### Setup Apache SystemDS on Databricks platform\n1. Create a new account at [databricks cloud](https://community.cloud.databricks.com/)\n2. In left-side navbar select **Clusters** > **`+ Create Cluster`** > Name the cluster! > **`Create Cluster`**\n3. Navigate to the created cluster configuration.\n- a. Select **Libraries**\n- b. Select **Install New** > **Library Source [`Upload`]** and **Library Type [`Jar`]**\n- c. Upload the `SystemDS.jar` file! > **`Install`**\n+ 1. Select **Libraries**\n+ 2. Select **Install New** > **Library Source [`Upload`]** and **Library Type [`Jar`]**\n+ 3. Upload the `SystemDS.jar` file! > **`Install`**\n4. Attach a notebook to the cluster above.\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Update spark runtime version in databricks notebook (#1267) make sure setup instructions are up-to-date and relevant
49,698
10.05.2021 05:09:40
-19,080
ee4b19c5497ae9c3cb58057ed4d948ecc12a5dc3
[MINOR] Add PTX JIT option instructions for sm_*
[ { "change_type": "MODIFY", "old_path": "docs/site/gpu.md", "new_path": "docs/site/gpu.md", "diff": "@@ -43,7 +43,16 @@ The following GPUs are supported:\nFor CUDA enabled gpu cards at [CUDA GPUs](https://developer.nvidia.com/cuda-gpus)\n* For GPUs with unsupported CUDA architectures, or to avoid JIT compilation from PTX, or to\nuse difference versions of the NVIDIA libraries, build on Linux from source code.\n-* Release artifacts contain PTX code for the latest supported CUDA architecture.\n+* Release artifacts contain PTX code for the latest supported CUDA architecture. In case your\n+architecture specific PTX is not available enable JIT PTX with instructions compiler driver `nvcc`\n+[GPU Compilation](https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#gpu-compilation).\n+\n+ > For example, with `--gpu-code` use actual gpu names, `--gpu-architecture` is the name of virtual\n+ > compute architecture\n+ >\n+ > ```sh\n+ > nvcc SystemDS.cu --gpu-architecture=compute_50 --gpu-code=sm_50,sm_52\n+ > ```\n### Software\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Add PTX JIT option instructions for sm_*
49,738
12.05.2021 18:29:27
-7,200
070667d7793a5df47617bc72ec526f23662955d1
[MINOR] Fix local libsvm write (no output file in pread-pwrite case)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/ParameterizedBuiltinCPInstruction.java", "diff": "@@ -341,7 +341,6 @@ public class ParameterizedBuiltinCPInstruction extends ComputationCPInstruction\nint decimal = (getParam(\"decimal\") != null) ? Integer.parseInt(getParam(\"decimal\")) : TOSTRING_DECIMAL;\nboolean sparse = (getParam(\"sparse\") != null) ? Boolean.parseBoolean(getParam(\"sparse\")) : TOSTRING_SPARSE;\nString separator = (getParam(\"sep\") != null) ? getParam(\"sep\") : TOSTRING_SEPARATOR;\n- String indexSeparator = (getParam(\"indSep\") != null) ? getParam(\"indSep\") : TOSTRING_SEPARATOR;\nString lineSeparator = (getParam(\"linesep\") != null) ? getParam(\"linesep\") : TOSTRING_LINESEPARATOR;\n// get input matrix/frame and convert to string\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/VariableCPInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/VariableCPInstruction.java", "diff": "@@ -54,7 +54,6 @@ import org.apache.sysds.runtime.io.FileFormatPropertiesLIBSVM;\nimport org.apache.sysds.runtime.io.IOUtilFunctions;\nimport org.apache.sysds.runtime.io.WriterMatrixMarket;\nimport org.apache.sysds.runtime.io.WriterTextCSV;\n-import org.apache.sysds.runtime.io.WriterTextLIBSVM;\nimport org.apache.sysds.runtime.lineage.LineageItem;\nimport org.apache.sysds.runtime.lineage.LineageItemUtils;\nimport org.apache.sysds.runtime.lineage.LineageTraceable;\n@@ -1072,8 +1071,8 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\nelse {\nmo.exportData(fname, outFmt, _formatProperties);\n}\n- HDFSTool.writeMetaDataFile(fname + \".mtd\", mo.getValueType(), dc, FileFormat.CSV, _formatProperties,\n- mo.getPrivacyConstraint());\n+ HDFSTool.writeMetaDataFile(fname + \".mtd\", mo.getValueType(),\n+ dc, FileFormat.CSV, _formatProperties, mo.getPrivacyConstraint());\n}\ncatch(IOException e) {\nthrow new DMLRuntimeException(e);\n@@ -1098,15 +1097,9 @@ public class VariableCPInstruction extends CPInstruction implements LineageTrace\n}\nelse {\ntry {\n- FileFormat fmt = ((MetaDataFormat) mo.getMetaData()).getFileFormat();\n- DataCharacteristics dc = (mo.getMetaData()).getDataCharacteristics();\n- if(fmt == FileFormat.LIBSVM && !getInput1().getName().startsWith(org.apache.sysds.lops.Data.PREAD_PREFIX)) {\n- WriterTextLIBSVM writer = new WriterTextLIBSVM((FileFormatPropertiesLIBSVM) _formatProperties);\n- }\n- else {\nmo.exportData(fname, outFmt, _formatProperties);\n- }\n- HDFSTool.writeMetaDataFile(fname + \".mtd\", mo.getValueType(), dc, FileFormat.LIBSVM, _formatProperties,\n+ HDFSTool.writeMetaDataFile(fname + \".mtd\", mo.getValueType(),\n+ mo.getMetaData().getDataCharacteristics(), FileFormat.LIBSVM, _formatProperties,\nmo.getPrivacyConstraint());\n}\ncatch (IOException e) {\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix local libsvm write (no output file in pread-pwrite case)
49,698
13.05.2021 16:58:51
-19,080
dadc15453d0de8956a1ac3097c2d47ae1f0547d2
[SYSTEMDS-2870][DOC] Builtin Decision Tree Reference commit:
[ { "change_type": "MODIFY", "old_path": "docs/site/builtins-reference.md", "new_path": "docs/site/builtins-reference.md", "diff": "@@ -33,6 +33,7 @@ limitations under the License.\n* [`csplineDS`-Function](#csplineDS-function)\n* [`cvlm`-Function](#cvlm-function)\n* [`DBSCAN`-Function](#DBSCAN-function)\n+ * [`decisionTree`-Function](#decisiontree-function)\n* [`discoverFD`-Function](#discoverFD-function)\n* [`dist`-Function](#dist-function)\n* [`dmv`-Function](#dmv-function)\n@@ -374,6 +375,52 @@ X = rand(rows=1780, cols=180, min=1, max=20)\ndbscan(X = X, eps = 2.5, minPts = 360)\n```\n+## `decisionTree`-Function\n+\n+The `decisionTree()` implements the classification tree with both scale and categorical\n+features.\n+\n+### Usage\n+\n+```r\n+M = decisionTree(X, Y, R);\n+```\n+\n+### Arguments\n+\n+| Name | Type | Default | Description |\n+| :--------- | :-------------- | :--------- | :---------- |\n+| X | Matrix[Double] | required | Feature matrix X; note that X needs to be both recoded and dummy coded |\n+| Y | Matrix[Double] | required | Label matrix Y; note that Y needs to be both recoded and dummy coded |\n+| R | Matrix[Double] | \" \" | Matrix R which for each feature in X contains the following information <br> - R[1,]: Row Vector which indicates if feature vector is scalar or categorical. 1 indicates <br> a scalar feature vector, other positive Integers indicate the number of categories <br> If R is not provided by default all variables are assumed to be scale |\n+| bins | Integer | `20` | Number of equiheight bins per scale feature to choose thresholds |\n+| depth | Integer | `25` | Maximum depth of the learned tree |\n+| verbose | Boolean | `FALSE` | boolean specifying if the algorithm should print information while executing |\n+\n+### Returns\n+\n+| Name | Type | Description |\n+| :--- | :-----------| :---------- |\n+| M | Matrix[Double] | Each column of the matrix corresponds to a node in the learned tree |\n+\n+### Example\n+\n+```r\n+X = matrix(\"4.5 4.0 3.0 2.8 3.5\n+ 1.9 2.4 1.0 3.4 2.9\n+ 2.0 1.1 1.0 4.9 3.4\n+ 2.3 5.0 2.0 1.4 1.8\n+ 2.1 1.1 3.0 1.0 1.9\", rows=5, cols=5)\n+Y = matrix(\"1.0\n+ 0.0\n+ 0.0\n+ 1.0\n+ 0.0\", rows=5, cols=1)\n+R = matrix(\"1.0 1.0 3.0 1.0 1.0\", rows=1, cols=5)\n+M = decisionTree(X = X, Y = Y, R = R)\n+```\n+\n+\n## `discoverFD`-Function\nThe `discoverFD`-function finds the functional dependencies.\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2870][DOC] Builtin Decision Tree (#1272) Reference commit: 44e42945
49,698
13.05.2021 18:42:22
-19,080
ccb6a96082f68e6fe6a907773fea37982c04b908
[MINOR][DOC] update preexisting java command to openjdk8
[ { "change_type": "MODIFY", "old_path": "docs/site/install.md", "new_path": "docs/site/install.md", "diff": "@@ -44,6 +44,11 @@ sudo apt install openjdk-8-jdk-headless\nsudo apt install maven\n```\n+Note: To update the `java` command to `openjdk-8` run:\n+```sh\n+update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java\n+```\n+\nVerify the install with:\n```bash\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR][DOC] update preexisting java command to openjdk8 (#1273)
49,738
13.05.2021 15:35:20
-7,200
05b872ecb44a18499d53d63cfe157ef928501805
Support for namespaces in eval 2nd-order function calls So far, we only supported eval function calls of functions in default or builtin namespaces. This patch now extends that to all user namespacesm but similar to paramserv only by the physical namespace name.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/parser/dml/DmlSyntacticValidator.java", "new_path": "src/main/java/org/apache/sysds/parser/dml/DmlSyntacticValidator.java", "diff": "@@ -1116,7 +1116,9 @@ public class DmlSyntacticValidator implements DmlListener {\n//NOTE: the use of File.separator would lead to OS-specific inconsistencies,\n//which is problematic for second order functions such as eval or paramserv.\n//Since this is unnecessary, we now use \"/\" independent of the use OS.\n- return !new File(filePath).isAbsolute() ? workingDir + \"/\" + filePath : filePath;\n+ String prefix = workingDir + \"/\";\n+ return new File(filePath).isAbsolute() | filePath.startsWith(prefix) ?\n+ filePath : prefix + filePath;\n}\npublic String getNamespaceSafe(Token ns) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/EvalNaryCPInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/EvalNaryCPInstruction.java", "diff": "@@ -62,9 +62,11 @@ public class EvalNaryCPInstruction extends BuiltinNaryCPInstruction {\n//1. get the namespace and func\nString funcName = ec.getScalarInput(inputs[0]).getStringValue();\nString nsName = null; //default namespace\n- if( funcName.contains(Program.KEY_DELIM) )\n- throw new DMLRuntimeException(\"Eval calls to '\"+funcName+\"', i.e., a function outside \"\n- + \"the default \"+ \"namespace, are not supported yet. Please call the function directly.\");\n+ if( funcName.contains(Program.KEY_DELIM) ) {\n+ String[] parts = DMLProgram.splitFunctionKey(funcName);\n+ funcName = parts[1];\n+ nsName = parts[0];\n+ }\n// bound the inputs to avoiding being deleted after the function call\nCPOperand[] boundInputs = Arrays.copyOfRange(inputs, 1, inputs.length);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/misc/FunctionPotpourriTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/misc/FunctionPotpourriTest.java", "diff": "@@ -54,6 +54,7 @@ public class FunctionPotpourriTest extends AutomatedTestBase\n\"FunPotpourriEvalPred\",\n\"FunPotpourriEvalList1Arg\",\n\"FunPotpourriEvalList2Arg\",\n+ \"FunPotpourriEvalNamespace\",\n};\nprivate final static String TEST_DIR = \"functions/misc/\";\n@@ -186,6 +187,11 @@ public class FunctionPotpourriTest extends AutomatedTestBase\nrunFunctionTest( TEST_NAMES[23], null );\n}\n+ @Test\n+ public void testFunctionEvalNamespace() {\n+ runFunctionTest( TEST_NAMES[24], null );\n+ }\n+\nprivate void runFunctionTest(String testName, Class<?> error) {\nTestConfiguration config = getTestConfiguration(testName);\nloadTestConfiguration(config);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/misc/FunPotpourriEvalNamespace.dml", "diff": "+#-------------------------------------------------------------\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+source(\"./src/test/scripts/functions/misc/FunPotpourriEvalNamespaceFuns.dml\") as fns1\n+\n+ns = \"./src/test/scripts/functions/misc/FunPotpourriEvalNamespaceFuns.dml\"\n+X = rand(rows=100, cols=100)\n+s = eval(ns+\"::foo\", list(X, TRUE))\n+print(toString(s))\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/misc/FunPotpourriEvalNamespaceFuns.dml", "diff": "+#-------------------------------------------------------------\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+foo = function(Matrix[Double] X, Boolean verbose) return (Matrix[Double] s) {\n+ s = as.matrix(5)\n+ for(i in 1:ncol(X))\n+ if(verbose)\n+ print(\"this is i \" +i)\n+}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2924] Support for namespaces in eval 2nd-order function calls So far, we only supported eval function calls of functions in default or builtin namespaces. This patch now extends that to all user namespacesm but similar to paramserv only by the physical namespace name.
49,697
14.05.2021 15:25:05
-7,200
706ee13c4d0f2a5bbb02781b589c27cf1c77030b
Fix codegen binary template for element-wise ops Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNodeBinary.java", "new_path": "src/main/java/org/apache/sysds/hops/codegen/cplan/CNodeBinary.java", "diff": "@@ -76,6 +76,10 @@ public class CNodeBinary extends CNode {\nreturn ssComm || vsComm || vvComm;\n}\n+ public boolean isElementwise() {\n+ return this != DOT_PRODUCT && this != VECT_MATRIXMULT && this != VECT_OUTERMULT_ADD;\n+ }\n+\npublic boolean isVectorPrimitive() {\nreturn isVectorScalarPrimitive()\n|| isVectorVectorPrimitive()\n@@ -184,7 +188,8 @@ public class CNodeBinary extends CNode {\n//replace start position of main input\ntmp = tmp.replace(\"%POS\"+(j+1)+\"%\", (_inputs.get(j) instanceof CNodeData\n&& _inputs.get(j).getDataType().isMatrix()) ? (!varj.startsWith(\"b\")) ? varj+\"i\" :\n- (TemplateUtils.isMatrix(_inputs.get(j)) && _type!=BinType.VECT_MATRIXMULT) ?\n+ ((TemplateUtils.isMatrix(_inputs.get(j)) || (_type.isElementwise()\n+ && TemplateUtils.isColVector(_inputs.get(j)))) && _type!=BinType.VECT_MATRIXMULT) ?\nvarj + \".pos(rix)\" : \"0\" : \"0\");\n}\n//replace length information (e.g., after matrix mult)\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2960] Fix codegen binary template for element-wise ops Closes #1245.
49,698
18.05.2021 23:11:37
-19,080
c3485c6f751a70dc2adb5edfc36d5d01d0d7e5ca
[MINOR] Add file encoding and file type for README.md Metadata: Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM discussion: Closes
[ { "change_type": "MODIFY", "old_path": "src/main/python/setup.py", "new_path": "src/main/python/setup.py", "diff": "@@ -50,7 +50,8 @@ setup(\nname=ARTIFACT_NAME,\nversion=ARTIFACT_VERSION_SHORT,\ndescription='SystemDS is a distributed and declarative machine learning platform.',\n- long_description=open('README.md').read(),\n+ long_description=open('README.md', encoding='utf-8').read(),\n+ long_description_content_type='text/markdown',\nurl='https://github.com/apache/systemds',\nauthor='SystemDS',\nauthor_email='[email protected]',\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Add file encoding and file type for README.md https://packaging.python.org/specifications/core-metadata/#description-content-type Metadata: Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM discussion: https://github.com/j143/systemds/issues/68 Closes #1281.
49,697
18.05.2021 20:44:38
-7,200
7325220d6581b37b5fd94bba7f782f2898e078e4
Federated codegen multi-aggregate operations Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "diff": "package org.apache.sysds.runtime.instructions.fed;\nimport org.apache.sysds.runtime.codegen.SpoofCellwise;\n+import org.apache.sysds.runtime.codegen.SpoofMultiAggregate;\nimport org.apache.sysds.runtime.codegen.SpoofRowwise;\nimport org.apache.sysds.runtime.controlprogram.caching.CacheableData;\nimport org.apache.sysds.runtime.controlprogram.caching.FrameObject;\n@@ -228,7 +229,8 @@ public class FEDInstructionUtils {\nelse if(inst instanceof SpoofCPInstruction) {\nSpoofCPInstruction instruction = (SpoofCPInstruction) inst;\nClass<?> scla = instruction.getOperatorClass().getSuperclass();\n- if( (scla == SpoofCellwise.class && instruction.isFederated(ec))\n+ if(((scla == SpoofCellwise.class || scla == SpoofMultiAggregate.class)\n+ && instruction.isFederated(ec))\n|| (scla == SpoofRowwise.class && instruction.isFederated(ec, FType.ROW))) {\nfedinst = SpoofFEDInstruction.parseInstruction(instruction.getInstructionString());\n}\n@@ -337,7 +339,8 @@ public class FEDInstructionUtils {\nelse if(inst instanceof SpoofSPInstruction) {\nSpoofSPInstruction instruction = (SpoofSPInstruction) inst;\nClass<?> scla = instruction.getOperatorClass().getSuperclass();\n- if( (scla == SpoofCellwise.class && instruction.isFederated(ec))\n+ if(((scla == SpoofCellwise.class || scla == SpoofMultiAggregate.class)\n+ && instruction.isFederated(ec))\n|| (scla == SpoofRowwise.class && instruction.isFederated(ec, FType.ROW))) {\nfedinst = SpoofFEDInstruction.parseInstruction(inst.getInstructionString());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/SpoofFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/SpoofFEDInstruction.java", "diff": "@@ -26,6 +26,7 @@ import org.apache.sysds.runtime.codegen.SpoofCellwise.AggOp;\nimport org.apache.sysds.runtime.codegen.SpoofCellwise.CellType;\nimport org.apache.sysds.runtime.codegen.SpoofRowwise;\nimport org.apache.sysds.runtime.codegen.SpoofRowwise.RowType;\n+import org.apache.sysds.runtime.codegen.SpoofMultiAggregate;\nimport org.apache.sysds.runtime.codegen.SpoofOperator;\nimport org.apache.sysds.runtime.controlprogram.caching.MatrixObject;\nimport org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\n@@ -40,6 +41,7 @@ import org.apache.sysds.runtime.instructions.cp.CPOperand;\nimport org.apache.sysds.runtime.instructions.cp.Data;\nimport org.apache.sysds.runtime.instructions.cp.ScalarObject;\nimport org.apache.sysds.runtime.instructions.InstructionUtils;\n+import org.apache.sysds.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysds.runtime.matrix.operators.AggregateUnaryOperator;\nimport java.util.ArrayList;\n@@ -153,11 +155,17 @@ public class SpoofFEDInstruction extends FEDInstruction\nsetOutputCellwise(ec, response, fedMap);\nelse if(_op.getClass().getSuperclass() == SpoofRowwise.class)\nsetOutputRowwise(ec, response, fedMap);\n+\n+ else if(_op.getClass().getSuperclass() == SpoofMultiAggregate.class)\n+ setOutputMultiAgg(ec, response, fedMap);\nelse\n- throw new DMLRuntimeException(\"Federated code generation only supported for cellwise and rowwise templates.\");\n+ throw new DMLRuntimeException(\"Federated code generation only supported for cellwise, rowwise, and multiaggregate templates.\");\n}\nprivate static boolean needsBroadcastSliced(FederationMap fedMap, long rowNum, long colNum) {\n+ if(rowNum == fedMap.getMaxIndexInRange(0) && colNum == fedMap.getMaxIndexInRange(1))\n+ return true;\n+\nif(fedMap.getType() == FType.ROW) {\nreturn (rowNum == fedMap.getMaxIndexInRange(0) && (colNum == 1 || colNum == fedMap.getSize()))\n|| (colNum > 1 && rowNum == fedMap.getSize());\n@@ -291,4 +299,15 @@ public class SpoofFEDInstruction extends FEDInstruction\nthrow new DMLRuntimeException(\"AggregationType not supported yet.\");\n}\n}\n+\n+ private void setOutputMultiAgg(ExecutionContext ec, Future<FederatedResponse>[] response, FederationMap fedMap)\n+ {\n+ MatrixBlock[] partRes = FederationUtils.getResults(response);\n+ SpoofCellwise.AggOp[] aggOps = ((SpoofMultiAggregate)_op).getAggOps();\n+ for(int counter = 1; counter < partRes.length; counter++) {\n+ SpoofMultiAggregate.aggregatePartialResults(aggOps, partRes[0], partRes[counter]);\n+ }\n+ ec.setMatrixOutput(_output.getName(), partRes[0]);\n+ }\n+\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/federated/codegen/FederatedCellwiseTmplTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/federated/codegen/FederatedCellwiseTmplTest.java", "diff": "@@ -29,6 +29,7 @@ import org.apache.sysds.test.TestConfiguration;\nimport org.apache.sysds.test.TestUtils;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\n+import org.junit.Ignore;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.Test;\n@@ -114,15 +115,17 @@ public class FederatedCellwiseTmplTest extends AutomatedTestBase\nTestUtils.clearDirectory(TEST_DATA_DIR + TEST_CLASS_DIR);\n}\n-// @Test\n-// public void federatedCodegenCellwiseSingleNode() {\n-// testFederatedCodegen(ExecMode.SINGLE_NODE);\n-// }\n-//\n-// @Test\n-// public void federatedCodegenCellwiseSpark() {\n-// testFederatedCodegen(ExecMode.SPARK);\n-// }\n+ @Test\n+ @Ignore\n+ public void federatedCodegenCellwiseSingleNode() {\n+ testFederatedCodegen(ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ @Ignore\n+ public void federatedCodegenCellwiseSpark() {\n+ testFederatedCodegen(ExecMode.SPARK);\n+ }\n@Test\npublic void federatedCodegenCellwiseHybrid() {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/federated/codegen/FederatedMultiAggTmplTest.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.apache.sysds.test.functions.federated.codegen;\n+\n+import java.io.File;\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysds.runtime.meta.MatrixCharacteristics;\n+import org.apache.sysds.runtime.util.HDFSTool;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.BeforeClass;\n+import org.junit.Ignore;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+import org.junit.Test;\n+\n+import java.util.Arrays;\n+import java.util.Collection;\n+import java.util.HashMap;\n+\n+@RunWith(value = Parameterized.class)\[email protected]\n+public class FederatedMultiAggTmplTest extends AutomatedTestBase\n+{\n+ private final static String TEST_NAME = \"FederatedMultiAggTmplTest\";\n+\n+ private final static String TEST_DIR = \"functions/federated/codegen/\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + FederatedMultiAggTmplTest.class.getSimpleName() + \"/\";\n+\n+ private final static String TEST_CONF = \"SystemDS-config-codegen.xml\";\n+\n+ private final static String OUTPUT_NAME = \"Z\";\n+ private final static double TOLERANCE = 1e-14;\n+ private final static int BLOCKSIZE = 1024;\n+\n+ @Parameterized.Parameter()\n+ public int test_num;\n+ @Parameterized.Parameter(1)\n+ public int rows;\n+ @Parameterized.Parameter(2)\n+ public int cols;\n+ @Parameterized.Parameter(3)\n+ public boolean row_partitioned;\n+\n+ @Override\n+ public void setUp() {\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[]{OUTPUT_NAME}));\n+ }\n+\n+ @Parameterized.Parameters\n+ public static Collection<Object[]> data() {\n+ // rows must be even for row partitioned X\n+ // cols must be even for col partitioned X\n+ return Arrays.asList(new Object[][] {\n+ // {test_num, rows, cols, row_partitioned}\n+\n+ // row partitioned\n+ {1, 6, 4, true},\n+ // {2, 6, 4, true},\n+ {3, 6, 4, true},\n+ // {4, 6, 4, true},\n+ {5, 6, 4, true},\n+ {6, 6, 4, true},\n+ {7, 20, 1, true},\n+\n+ // column partitioned\n+ {1, 6, 4, false},\n+ {2, 6, 4, false},\n+ // {3, 6, 4, false},\n+ {4, 6, 4, false},\n+ // {5, 6, 4, false},\n+ {6, 6, 4, false},\n+ });\n+ }\n+\n+ @BeforeClass\n+ public static void init() {\n+ TestUtils.clearDirectory(TEST_DATA_DIR + TEST_CLASS_DIR);\n+ }\n+\n+ @Test\n+ @Ignore\n+ public void federatedCodegenMultiAggSingleNode() {\n+ testFederatedCodegenMultiAgg(ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ @Ignore\n+ public void federatedCodegenMultiAggSpark() {\n+ testFederatedCodegenMultiAgg(ExecMode.SPARK);\n+ }\n+\n+ @Test\n+ public void federatedCodegenMultiAggHybrid() {\n+ testFederatedCodegenMultiAgg(ExecMode.HYBRID);\n+ }\n+\n+ private void testFederatedCodegenMultiAgg(ExecMode exec_mode) {\n+ // store the previous platform config to restore it after the test\n+ ExecMode platform_old = setExecMode(exec_mode);\n+\n+ getAndLoadTestConfiguration(TEST_NAME);\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+\n+ int fed_rows = rows;\n+ int fed_cols = cols;\n+ if(row_partitioned)\n+ fed_rows /= 2;\n+ else\n+ fed_cols /= 2;\n+\n+ // generate dataset\n+ // matrix handled by two federated workers\n+ double[][] X1 = getRandomMatrix(fed_rows, fed_cols, 0, 1, 1, 3);\n+ double[][] X2 = getRandomMatrix(fed_rows, fed_cols, 0, 1, 1, 7);\n+\n+ writeInputMatrixWithMTD(\"X1\", X1, false, new MatrixCharacteristics(fed_rows, fed_cols, BLOCKSIZE, fed_rows * fed_cols));\n+ writeInputMatrixWithMTD(\"X2\", X2, false, new MatrixCharacteristics(fed_rows, fed_cols, BLOCKSIZE, fed_rows * fed_cols));\n+\n+ // empty script name because we don't execute any script, just start the worker\n+ fullDMLScriptName = \"\";\n+ int port1 = getRandomAvailablePort();\n+ int port2 = getRandomAvailablePort();\n+ Thread thread1 = startLocalFedWorkerThread(port1, FED_WORKER_WAIT_S);\n+ Thread thread2 = startLocalFedWorkerThread(port2);\n+\n+ getAndLoadTestConfiguration(TEST_NAME);\n+\n+ // Run reference dml script with normal matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-stats\", \"-nvargs\",\n+ \"in_X1=\" + input(\"X1\"), \"in_X2=\" + input(\"X2\"),\n+ \"in_rp=\" + Boolean.toString(row_partitioned).toUpperCase(),\n+ \"in_test_num=\" + Integer.toString(test_num),\n+ \"out_Z=\" + expected(OUTPUT_NAME)};\n+ runTest(true, false, null, -1);\n+\n+ // Run actual dml script with federated matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"-nvargs\",\n+ \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"X1\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"X2\")),\n+ \"in_rp=\" + Boolean.toString(row_partitioned).toUpperCase(),\n+ \"in_test_num=\" + Integer.toString(test_num),\n+ \"rows=\" + rows, \"cols=\" + cols,\n+ \"out_Z=\" + output(OUTPUT_NAME)};\n+ runTest(true, false, null, -1);\n+\n+ // compare the results via files\n+ HashMap<CellIndex, Double> refResults = readDMLMatrixFromExpectedDir(OUTPUT_NAME);\n+ HashMap<CellIndex, Double> fedResults = readDMLMatrixFromOutputDir(OUTPUT_NAME);\n+ TestUtils.compareMatrices(fedResults, refResults, TOLERANCE, \"Fed\", \"Ref\");\n+\n+ TestUtils.shutdownThreads(thread1, thread2);\n+\n+ // check for federated operations\n+ Assert.assertTrue(heavyHittersContainsSubString(\"fed_spoofMA\"));\n+\n+ // check that federated input files are still existing\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X1\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X2\")));\n+ resetExecMode(platform_old);\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+ File TEST_CONF_FILE = new File(SCRIPT_DIR + TEST_DIR, TEST_CONF);\n+ return TEST_CONF_FILE;\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/federated/codegen/FederatedRowwiseTmplTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/federated/codegen/FederatedRowwiseTmplTest.java", "diff": "@@ -29,6 +29,7 @@ import org.apache.sysds.test.TestConfiguration;\nimport org.apache.sysds.test.TestUtils;\nimport org.junit.Assert;\nimport org.junit.BeforeClass;\n+import org.junit.Ignore;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.Test;\n@@ -103,15 +104,17 @@ public class FederatedRowwiseTmplTest extends AutomatedTestBase\nTestUtils.clearDirectory(TEST_DATA_DIR + TEST_CLASS_DIR);\n}\n- // @Test\n- // public void federatedCodegenRowwiseSingleNode() {\n- // testFederatedCodegenRowwise(ExecMode.SINGLE_NODE);\n- // }\n- //\n- // @Test\n- // public void federatedCodegenRowwiseSpark() {\n- // testFederatedCodegenRowwise(ExecMode.SPARK);\n- // }\n+ @Test\n+ @Ignore\n+ public void federatedCodegenRowwiseSingleNode() {\n+ testFederatedCodegenRowwise(ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ @Ignore\n+ public void federatedCodegenRowwiseSpark() {\n+ testFederatedCodegenRowwise(ExecMode.SPARK);\n+ }\n@Test\npublic void federatedCodegenCellwiseHybrid() {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/codegen/FederatedMultiAggTmplTest.dml", "diff": "+#-------------------------------------------------------------\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+test_num = $in_test_num;\n+row_part = $in_rp;\n+\n+if(row_part) {\n+ X = federated(addresses=list($in_X1, $in_X2),\n+ ranges=list(list(0, 0), list($rows / 2, $cols), list($rows / 2, 0), list($rows, $cols)));\n+}\n+else {\n+ X = federated(addresses=list($in_X1, $in_X2),\n+ ranges=list(list(0, 0), list($rows, $cols / 2), list(0, $cols / 2), list($rows, $cols)));\n+}\n+\n+if(test_num == 1) {\n+ # X ... 6x4 matrix\n+ r1 = min(X > 0.5);\n+ r2 = max(X > 0.5);\n+ Z = as.matrix(r1 + r2);\n+}\n+else if(test_num == 2) {\n+ # X ... 6x4 matrix\n+ r1 = sum(X > 0.5);\n+ r2 = sum((X > 0.5)^2);\n+ Z = as.matrix(r1 + r2);\n+}\n+else if(test_num == 3) {\n+ # X ... 6x4 matrix\n+\n+ #disjoint partitions with shared read\n+ r1 = sum(X == 0.7)\n+ r2 = sum(X == 0.3)\n+ Z = as.matrix(r1 + r2);\n+}\n+else if(test_num == 4) {\n+ # X ... 6x4 matrix\n+ Y = matrix(seq(2,25), rows=6, cols=4);\n+\n+ #disjoint partitions with partial shared reads\n+ r1 = sum(X * Y);\n+ r2 = sum(X ^ 2);\n+ r3 = sum(Y ^ 2);\n+ Z = as.matrix(r1 + r2 + r3);\n+}\n+else if(test_num == 5) {\n+ # X ... 6x4 matrix\n+ U = matrix(seq(0,23), rows=6, cols=4);\n+ V = matrix(seq(2,25), rows=6, cols=4);\n+ W = matrix(seq(3,26), rows=6, cols=4);\n+\n+ #disjoint partitions with transitive partial shared reads\n+ r1 = sum(X * U);\n+ r2 = sum(V * W);\n+ r3 = sum(X * V * W);\n+ Z = as.matrix(r1 + r2 + r3);\n+}\n+else if(test_num == 6) {\n+ # X ... 6x4 matrix\n+\n+ r1 = min(X);\n+ r2 = max(X);\n+ r3 = sum(X);\n+ Z = as.matrix(r1 + r2 + r3);\n+}\n+else if(test_num == 7) {\n+ # X ... 20x1 vector\n+ Y = seq(2,21);\n+ while(FALSE){}\n+\n+ r1 = t(X) %*% X;\n+ r2 = t(X) %*% Y;\n+ r3 = t(Y) %*% Y;\n+ Z = r1 + r2 + r3;\n+}\n+\n+write(Z, $out_Z);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/codegen/FederatedMultiAggTmplTestReference.dml", "diff": "+#-------------------------------------------------------------\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+test_num = $in_test_num;\n+row_part = $in_rp;\n+\n+if(row_part) {\n+ X = rbind(read($in_X1), read($in_X2));\n+}\n+else {\n+ X = cbind(read($in_X1), read($in_X2));\n+}\n+\n+if(test_num == 1) {\n+ # X ... 6x4 matrix\n+ r1 = min(X > 0.5);\n+ r2 = max(X > 0.5);\n+ Z = as.matrix(r1 + r2);\n+}\n+else if(test_num == 2) {\n+ # X ... 6x4 matrix\n+ r1 = sum(X > 0.5);\n+ r2 = sum((X > 0.5)^2);\n+ Z = as.matrix(r1 + r2);\n+}\n+else if(test_num == 3) {\n+ # X ... 6x4 matrix\n+\n+ #disjoint partitions with shared read\n+ r1 = sum(X == 0.7)\n+ r2 = sum(X == 0.3)\n+ Z = as.matrix(r1 + r2);\n+}\n+else if(test_num == 4) {\n+ # X ... 6x4 matrix\n+ Y = matrix(seq(2,25), rows=6, cols=4);\n+\n+ #disjoint partitions with partial shared reads\n+ r1 = sum(X * Y);\n+ r2 = sum(X ^ 2);\n+ r3 = sum(Y ^ 2);\n+ Z = as.matrix(r1 + r2 + r3);\n+}\n+else if(test_num == 5) {\n+ # X ... 6x4 matrix\n+ U = matrix(seq(0,23), rows=6, cols=4);\n+ V = matrix(seq(2,25), rows=6, cols=4);\n+ W = matrix(seq(3,26), rows=6, cols=4);\n+\n+ #disjoint partitions with transitive partial shared reads\n+ r1 = sum(X * U);\n+ r2 = sum(V * W);\n+ r3 = sum(X * V * W);\n+ Z = as.matrix(r1 + r2 + r3);\n+}\n+else if(test_num == 6) {\n+ # X ... 6x4 matrix\n+\n+ r1 = min(X);\n+ r2 = max(X);\n+ r3 = sum(X);\n+ Z = as.matrix(r1 + r2 + r3);\n+}\n+else if(test_num == 7) {\n+ # X ... 20x1 vector\n+ Y = seq(2,21);\n+ while(FALSE){}\n+\n+ r1 = t(X) %*% X;\n+ r2 = t(X) %*% Y;\n+ r3 = t(Y) %*% Y;\n+ Z = r1 + r2 + r3;\n+}\n+\n+write(Z, $out_Z);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2922] Federated codegen multi-aggregate operations Closes #1277.
49,700
19.05.2021 10:45:09
-7,200
7fea8bf4ebc505f0fb8ed5532eeaebf12bc8e27b
[MINOR] Add Documentation Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/lops/Unary.java", "new_path": "src/main/java/org/apache/sysds/lops/Unary.java", "diff": "@@ -53,6 +53,7 @@ public class Unary extends Lop\n* @param dt data type\n* @param vt value type\n* @param et execution type\n+ * @param numThreads number of threads for execution\n*/\npublic Unary(Lop input1, Lop input2, OpOp1 op, DataType dt, ValueType vt, ExecType et, int numThreads) {\nsuper(Lop.Type.UNARY, dt, vt);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/InstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/InstructionUtils.java", "diff": "@@ -1098,7 +1098,7 @@ public class InstructionUtils\n* @param id new output operand (always a number)\n* @param varOldIn current input operand (to be replaced)\n* @param varNewIn new input operand names (always numbers)\n- * @param federatedOutput federated output flag\n+ * @param rmFederatedOutput remove federated output flag\n* @return instruction string prepared for federated request\n*/\npublic static String instructionStringFEDPrepare(String inst, CPOperand varOldOut, long id, CPOperand[] varOldIn, long[] varNewIn, boolean rmFederatedOutput){\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Add Documentation Closes #1282.
49,757
19.05.2021 11:06:26
-7,200
2ae0f818d9fc5092408df6ff3fe75539a5117e40
Builtin for Stable Marriage Algorithm Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "scripts/builtin/stableMarriage.dml", "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+# THIS SCRIPT COMPUTES A SOLUTION FOR THE STABLE MARRIAGE PROBLEM\n+#\n+# INPUT PARAMETERS:\n+# --------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# --------------------------------------------------------------------------------------------\n+# P Matrix --- proposer matrix P.\n+# It must be a square matrix with no zeros.\n+#\n+# A Matrix --- acceptor matrix A.\n+# It must be a square matrix with no zeros.\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+# i.e. the leftmost value in a row in P is the preference value for the acceptor with\n+# index 1 and vice-versa (higher is better).\n+# OUTPUT PARAMETERS:\n+# --------------------------------------------------------------------------------------------\n+# NAME TYPE DEFAULT MEANING\n+# --------------------------------------------------------------------------------------------\n+#result_matrix Matrix --- Result Matrix\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+#\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+m_stableMarriage = function(Matrix[Double] P, Matrix[Double] A, Boolean ordered = TRUE, Boolean verbose = FALSE)\n+ return (Matrix[Double] result_matrix)\n+{\n+ # variable names follow publication\n+\n+ print(\"STARTING STABLE MARRIAGE\");\n+ assert(nrow(A) == nrow(P));\n+ assert(ncol(A) == ncol(P));\n+\n+ if(nrow(P) != ncol(P) | nrow(A) != ncol(A))\n+ stop(\"StableMarriage error: Wrong Input! Both P and A must be square.\")\n+\n+ n = nrow(P)\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+ # 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+ 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+ # 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+ 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+ for(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+ # make 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+ for(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+ if(verbose)\n+ print(\"Result: \\n\"+toString(result_matrix))\n+}\n\\ No newline at end of file\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -227,6 +227,7 @@ public enum Builtins {\nSOLVE(\"solve\", false),\nSPLIT(\"split\", true),\nSPLIT_BALANCED(\"splitBalanced\", true),\n+ STABLE_MARRIAGE(\"stableMarriage\", true),\nSTATSNA(\"statsNA\", true),\nSQRT(\"sqrt\", false),\nSUM(\"sum\", false),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinStableMarriageTest.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.apache.sysds.test.functions.builtin;\n+\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.lops.LopProperties.ExecType;\n+import org.apache.sysds.runtime.matrix.data.MatrixValue;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Test;\n+\n+import java.util.ArrayList;\n+import java.util.HashMap;\n+import java.util.List;\n+\n+public class BuiltinStableMarriageTest extends AutomatedTestBase {\n+\n+\n+ private final static String TEST_NAME = \"stablemarriage\";\n+ private final static String TEST_DIR = \"functions/builtin/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + BuiltinStableMarriageTest.class.getSimpleName() + \"/\";\n+\n+ private final static double eps = 0.0001;\n+\n+\n+\n+ @Override\n+ public void setUp() {\n+ addTestConfiguration(TEST_NAME,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME,new String[]{\"SM\"}));\n+ }\n+\n+ @Test\n+ public void testStableMarriage1() {\n+ double[][] P = {{2, 1, 3}, {1, 2, 3}, {1, 3, 2}};\n+ double[][] A = {{3, 1, 2}, {2, 1, 3}, {3, 2, 1}};\n+ // this is an expected matrix\n+ double[][] EM = { {0, 0, 3}, {0, 3, 0}, {1, 0, 0}};\n+ runtestStableMarriage(P, A, EM, \"TRUE\", ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testStableMarriage2() {\n+ double[][] P = {{4, 3, 2, 1}, {2, 4, 3, 1}, {1, 4, 3, 2}, {4, 1, 2, 3}};\n+ double[][] A = {{2, 3, 4, 1}, {2, 3, 4, 1}, {4, 3, 1, 2}, {2, 1, 4, 3}};\n+ // this is an expected matrix\n+ double[][] EM = {{0, 0, 3, 0}, {0, 4, 0, 0}, {0, 0, 0, 4}, {3, 0, 0, 0}};\n+ runtestStableMarriage(P, A, EM, \"TRUE\", ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testStableMarriage3() {\n+ double[][] P = {{4, 3, 2, 1}, {2, 4, 3, 1}, {1, 4, 3, 2}, {4, 1, 2, 3}};\n+ double[][] A = {{2, 3, 4, 1}, {2, 3, 4, 1}, {4, 3, 1, 2}, {2, 1, 4, 3}};\n+ // this is an expected matrix\n+ double[][] EM = {{2, 0, 0, 0}, {0, 0, 4, 0}, {0, 3, 0, 0}, {0, 0, 0, 3}};\n+ runtestStableMarriage(P, A, EM, \"FALSE\", ExecType.CP);\n+ }\n+\n+\n+ @Test\n+ public void testStableMarriageSP() {\n+ double[][] P = {{4, 3, 2, 1}, {2, 4, 3, 1}, {1, 4, 3, 2}, {4, 1, 2, 3}};\n+ double[][] A = {{2, 3, 4, 1}, {2, 3, 4, 1}, {4, 3, 1, 2}, {2, 1, 4, 3}};\n+ // this is an expected matrix\n+ double[][] EM = {{0, 0, 3, 0}, {0, 4, 0, 0}, {0, 0, 0, 4}, {3, 0, 0, 0}};\n+ runtestStableMarriage(P, A, EM, \"TRUE\", ExecType.SPARK);\n+ }\n+\n+\n+ private void runtestStableMarriage(double[][] P, double[][] A, double[][] EM, String ordered, ExecType instType) {\n+ Types.ExecMode platformOld = setExecMode(instType);\n+\n+ try\n+ {\n+ loadTestConfiguration(getTestConfiguration(TEST_NAME));\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ List<String> proArgs = new ArrayList<>();\n+ proArgs.add(\"-args\");\n+ proArgs.add(input(\"P\"));\n+ proArgs.add(input(\"A\"));\n+ proArgs.add(ordered);\n+ proArgs.add(output(\"SM\"));\n+\n+ programArgs = proArgs.toArray(new String[0]);\n+\n+ writeInputMatrixWithMTD(\"P\", P, true);\n+ writeInputMatrixWithMTD(\"A\", A, true);\n+\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ //compare expected results\n+ HashMap<MatrixValue.CellIndex, Double> matrixU = readDMLMatrixFromOutputDir(\"SM\");\n+ double[][] OUT = TestUtils.convertHashMapToDoubleArray(matrixU);\n+ TestUtils.compareMatrices(EM, OUT, eps);\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ }\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/stablemarriage.dml", "diff": "+#-------------------------------------------------------------\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 dml file will call the stableMarriage built-in functions inside scripts/builtin\n+P = read($1)\n+A = read($2)\n+ordered = as.logical($3)\n+output = stableMarriage(P = P, A = A, ordered = ordered, verbose = TRUE)\n+write(output, $4)\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2976] Builtin for Stable Marriage Algorithm Closes #1279.
49,722
22.05.2021 22:13:36
-7,200
db30d5d319426fa3d0695670214515bef897b869
Federated frame element-wise map-lambda operations Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/InstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/InstructionUtils.java", "diff": "@@ -1128,7 +1128,7 @@ public class InstructionUtils\nreturn linst;\n}\n- private static String removeFEDOutputFlag(String linst){\n+ public static String removeFEDOutputFlag(String linst){\nreturn linst.substring(0, linst.lastIndexOf(Lop.OPERAND_DELIMITOR));\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/BinaryFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/BinaryFEDInstruction.java", "diff": "@@ -72,6 +72,8 @@ public abstract class BinaryFEDInstruction extends ComputationFEDInstruction {\nthrow new DMLRuntimeException(\"Federated binary tensor tensor operations not yet supported\");\nelse if( in1.isMatrix() && in2.isScalar() || in2.isMatrix() && in1.isScalar() )\nreturn new BinaryMatrixScalarFEDInstruction(operator, in1, in2, out, opcode, str, fedOut);\n+ else if( in1.isFrame() && in2.isScalar() || in2.isFrame() && in1.isScalar() )\n+ return new BinaryFrameScalarFEDInstruction(operator, in1, in2, out, opcode, InstructionUtils.removeFEDOutputFlag(str));\nelse\nthrow new DMLRuntimeException(\"Federated binary operations not yet supported:\" + opcode);\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/BinaryFrameScalarFEDInstruction.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.apache.sysds.runtime.instructions.fed;\n+\n+import org.apache.sysds.runtime.controlprogram.caching.FrameObject;\n+import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\n+import org.apache.sysds.runtime.controlprogram.federated.FederatedRequest;\n+import org.apache.sysds.runtime.controlprogram.federated.FederationMap;\n+import org.apache.sysds.runtime.controlprogram.federated.FederationUtils;\n+import org.apache.sysds.runtime.instructions.cp.CPOperand;\n+import org.apache.sysds.runtime.matrix.operators.Operator;\n+\n+public class BinaryFrameScalarFEDInstruction extends BinaryFEDInstruction\n+{\n+ protected BinaryFrameScalarFEDInstruction(Operator op, CPOperand in1,\n+ CPOperand in2, CPOperand out, String opcode, String istr) {\n+ super(FEDInstruction.FEDType.Binary, op, in1, in2, out, opcode, istr);\n+ }\n+\n+ @Override\n+ public void processInstruction(ExecutionContext ec) {\n+ // get input frames\n+ FrameObject fo = ec.getFrameObject(input1);\n+ FederationMap fedMap = fo.getFedMapping();\n+\n+ //compute results\n+ FederatedRequest fr1 = FederationUtils.callInstruction(instString,\n+ output, new CPOperand[] {input1}, new long[] {fedMap.getID()});\n+ fedMap.execute(getTID(), true, fr1);\n+\n+ FrameObject out = ec.getFrameObject(output);\n+ out.setSchema(fo.getSchema());\n+ out.getDataCharacteristics().set(fo.getDataCharacteristics());\n+ out.setFedMapping(fedMap.copyWithNewID(fr1.getID()));\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "diff": "@@ -35,6 +35,7 @@ import org.apache.sysds.runtime.instructions.cp.AggregateBinaryCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.AggregateTernaryCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.AggregateUnaryCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.BinaryCPInstruction;\n+import org.apache.sysds.runtime.instructions.cp.BinaryFrameScalarCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.CtableCPInstruction;\nimport org.apache.sysds.runtime.instructions.cp.Data;\nimport org.apache.sysds.runtime.instructions.cp.IndexingCPInstruction;\n@@ -156,6 +157,9 @@ public class FEDInstructionUtils {\nelse\nfedinst = BinaryFEDInstruction.parseInstruction(\nInstructionUtils.concatOperands(inst.getInstructionString(),FederatedOutput.NONE.name()));\n+ } else if(inst.getOpcode().equals(\"_map\") && inst instanceof BinaryFrameScalarCPInstruction && !inst.getInstructionString().contains(\"UtilFunctions\")\n+ && instruction.input1.isFrame() && ec.getFrameObject(instruction.input1).isFederated()) {\n+ fedinst = BinaryFrameScalarFEDInstruction.parseInstruction(InstructionUtils.concatOperands(inst.getInstructionString(),FederatedOutput.NONE.name()));\n}\n}\nelse if( inst instanceof ParameterizedBuiltinCPInstruction ) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedFrameMapTest.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.apache.sysds.test.functions.federated.primitives;\n+\n+import java.util.Arrays;\n+import java.util.Collection;\n+\n+import org.apache.sysds.api.DMLScript;\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.runtime.meta.MatrixCharacteristics;\n+import org.apache.sysds.runtime.util.HDFSTool;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+\n+@RunWith(value = Parameterized.class)\[email protected]\n+public class FederatedFrameMapTest extends AutomatedTestBase {\n+\n+ private final static String TEST_NAME1 = \"FederatedFrameMapTest\";\n+\n+ private final static String TEST_DIR = \"functions/federated/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + FederatedFrameMapTest.class.getSimpleName() + \"/\";\n+\n+ private final static int blocksize = 1024;\n+ @Parameterized.Parameter()\n+ public int rows;\n+ @Parameterized.Parameter(1)\n+ public int cols;\n+\n+ @Parameterized.Parameter(2)\n+ public boolean rowPartitioned;\n+\n+ @Parameterized.Parameters\n+ public static Collection<Object[]> data() {\n+ return Arrays.asList(new Object[][] {\n+ {100, 12, true},\n+ {100, 12, false},\n+ });\n+ }\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] {\"S\"}));\n+ }\n+\n+ @Test\n+ public void testLeftIndexFullDenseFrameCP() {\n+ runAggregateOperationTest(ExecMode.SINGLE_NODE);\n+ }\n+\n+ private void runAggregateOperationTest(ExecMode execMode) {\n+ setExecMode(execMode);\n+\n+ String TEST_NAME = TEST_NAME1;\n+\n+ getAndLoadTestConfiguration(TEST_NAME);\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+\n+ // write input matrices\n+ int r1 = rows;\n+ int c1 = cols / 4;\n+ if(rowPartitioned) {\n+ r1 = rows / 4;\n+ c1 = cols;\n+ }\n+\n+ double[][] X1 = getRandomMatrix(r1, c1, 1, 5, 1, 3);\n+ double[][] X2 = getRandomMatrix(r1, c1, 1, 5, 1, 7);\n+ double[][] X3 = getRandomMatrix(r1, c1, 1, 5, 1, 8);\n+ double[][] X4 = getRandomMatrix(r1, c1, 1, 5, 1, 9);\n+\n+ MatrixCharacteristics mc = new MatrixCharacteristics(r1, c1, blocksize, r1 * c1);\n+ writeInputMatrixWithMTD(\"X1\", X1, false, mc);\n+ writeInputMatrixWithMTD(\"X2\", X2, false, mc);\n+ writeInputMatrixWithMTD(\"X3\", X3, false, mc);\n+ writeInputMatrixWithMTD(\"X4\", X4, false, mc);\n+\n+ // empty script name because we don't execute any script, just start the worker\n+ fullDMLScriptName = \"\";\n+ int port1 = getRandomAvailablePort();\n+ int port2 = getRandomAvailablePort();\n+ int port3 = getRandomAvailablePort();\n+ int port4 = getRandomAvailablePort();\n+ Thread t1 = startLocalFedWorkerThread(port1, FED_WORKER_WAIT_S);\n+ Thread t2 = startLocalFedWorkerThread(port2, FED_WORKER_WAIT_S);\n+ Thread t3 = startLocalFedWorkerThread(port3, FED_WORKER_WAIT_S);\n+ Thread t4 = startLocalFedWorkerThread(port4);\n+\n+ rtplatform = execMode;\n+ if(rtplatform == ExecMode.SPARK) {\n+ System.out.println(7);\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+ }\n+ TestConfiguration config = availableTestConfigurations.get(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ // Run reference dml script with normal matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-explain\", \"-args\", input(\"X1\"), input(\"X2\"), input(\"X3\"), input(\"X4\"),\n+ Boolean.toString(rowPartitioned).toUpperCase(), expected(\"S\")};\n+ runTest(null);\n+\n+ // Run actual dml script with federated matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-nvargs\",\n+ \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"X1\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"X2\")),\n+ \"in_X3=\" + TestUtils.federatedAddress(port3, input(\"X3\")),\n+ \"in_X4=\" + TestUtils.federatedAddress(port4, input(\"X4\")),\n+ \"in_Y=\" + input(\"Y\"), \"rows=\" + rows, \"cols=\" + cols,\n+ \"rP=\" + Boolean.toString(rowPartitioned).toUpperCase(), \"out_S=\" + output(\"S\")};\n+ runTest(null);\n+\n+ // compare via files\n+ compareResults(1e-9);\n+\n+ Assert.assertTrue(heavyHittersContainsString(\"fed__map\"));\n+\n+ // check that federated input files are still existing\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X1\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X2\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X3\")));\n+ Assert.assertTrue(HDFSTool.existsFileOnHDFS(input(\"X4\")));\n+\n+ TestUtils.shutdownThreads(t1, t2, t3, t4);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedFrameMapTest.dml", "diff": "+#-------------------------------------------------------------\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+if ($rP) {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows/4, $cols), list($rows/4, 0), list(2*$rows/4, $cols),\n+ list(2*$rows/4, 0), list(3*$rows/4, $cols), list(3*$rows/4, 0), list($rows, $cols)));\n+} else {\n+ A = federated(addresses=list($in_X1, $in_X2, $in_X3, $in_X4),\n+ ranges=list(list(0, 0), list($rows, $cols/4), list(0,$cols/4), list($rows, $cols/2),\n+ list(0,$cols/2), list($rows, 3*($cols/4)), list(0, 3*($cols/4)), list($rows, $cols)));\n+}\n+\n+A = as.frame(A)\n+\n+S = map(A, \"x -> x.replace(\\\"1\\\", \\\"2\\\")\");\n+write(S, $out_S);\n+print(toString(A[1,1]))\n+print(toString(S[1,1]))\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedFrameMapTestReference.dml", "diff": "+#-------------------------------------------------------------\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+if($5) {\n+ A = rbind(read($1), read($2), read($3), read($4));\n+}\n+else {\n+ A = cbind(read($1), read($2), read($3), read($4));\n+}\n+\n+A = as.frame(A)\n+\n+S = map(A, \"x -> x.replace(\\\"1\\\", \\\"2\\\")\");\n+write(S, $6);\n+\n+print(toString(A[1,1]))\n+print(toString(S[1,1]))\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2978] Federated frame element-wise map-lambda operations Closes #1280.
49,689
23.05.2021 10:36:58
-7,200
dd2a8767e924cb33a0a4ca1060f2f36ebd9418e6
Add statistics for lineage cache in GPU This patch adds a initial set of statistics for reuse and eviction of GPU intermediates. e.g. LinCache GPU (Hit/Async/Sync): 38/26/25
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUMemoryEviction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUMemoryEviction.java", "diff": "@@ -25,6 +25,7 @@ import java.util.List;\nimport org.apache.sysds.api.DMLScript;\nimport org.apache.sysds.runtime.lineage.LineageCacheConfig;\nimport org.apache.sysds.runtime.lineage.LineageCacheEntry;\n+import org.apache.sysds.runtime.lineage.LineageCacheStatistics;\nimport org.apache.sysds.runtime.lineage.LineageGPUCacheEviction;\nimport org.apache.sysds.utils.GPUStatistics;\n@@ -122,7 +123,7 @@ public class GPUMemoryEviction implements Runnable\n// This doesn't guarantee allocation due to fragmented freed memory\n// A = cudaMallocNoWarn(tmpA, size, null);\nif (DMLScript.STATISTICS) {\n- GPUStatistics.cudaEvictCount.increment();\n+ LineageCacheStatistics.incrementGpuAsyncEvicts();\n}\ncount++;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUMemoryManager.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/context/GPUMemoryManager.java", "diff": "@@ -43,6 +43,7 @@ import org.apache.sysds.runtime.DMLRuntimeException;\nimport org.apache.sysds.runtime.instructions.gpu.GPUInstruction;\nimport org.apache.sysds.runtime.lineage.LineageCacheConfig;\nimport org.apache.sysds.runtime.lineage.LineageCacheEntry;\n+import org.apache.sysds.runtime.lineage.LineageCacheStatistics;\nimport org.apache.sysds.runtime.lineage.LineageGPUCacheEviction;\nimport org.apache.sysds.utils.GPUStatistics;\n@@ -355,7 +356,7 @@ public class GPUMemoryManager {\n// Copy from device cache to CPU lineage cache if not already copied\nLineageGPUCacheEviction.copyToHostCache(le, opcode, copied);\nif (DMLScript.STATISTICS)\n- GPUStatistics.cudaEvictCount.increment();\n+ LineageCacheStatistics.incrementGpuSyncEvicts();\n// For all the other objects, remove and clear data (only once)\nnextgpuObj = headGpuObj;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCache.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCache.java", "diff": "@@ -142,6 +142,7 @@ public class LineageCache\nreuse = reuseAll;\nif(reuse) { //reuse\n+ boolean gpuReuse = false;\n//put reuse value into symbol table (w/ blocking on placeholders)\nfor (MutablePair<LineageItem, LineageCacheEntry> entry : liList) {\ne = entry.getValue();\n@@ -174,8 +175,9 @@ public class LineageCache\n//shallow copy the cached GPUObj to the output MatrixObject\nec.getMatrixObject(outName).setGPUObject(ec.getGPUContext(0),\nec.getGPUContext(0).shallowCopyGPUObject(e._gpuObject, ec.getMatrixObject(outName)));\n- //Set dirty to true, so that it is later copied to the host\n+ //Set dirty to true, so that it is later copied to the host for write\nec.getMatrixObject(outName).getGPUObject(ec.getGPUContext(0)).setDirty(true);\n+ gpuReuse = true;\n}\nreuse = true;\n@@ -183,10 +185,14 @@ public class LineageCache\nif (DMLScript.STATISTICS) //increment saved time\nLineageCacheStatistics.incrementSavedComputeTime(e._computeTime);\n}\n- if (DMLScript.STATISTICS)\n+ if (DMLScript.STATISTICS) {\n+ if (gpuReuse)\n+ LineageCacheStatistics.incrementGpuHits();\n+ else\nLineageCacheStatistics.incrementInstHits();\n}\n}\n+ }\nreturn reuse;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCacheStatistics.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageCacheStatistics.java", "diff": "@@ -36,10 +36,15 @@ public class LineageCacheStatistics {\nprivate static final LongAdder _numWritesFS = new LongAdder();\nprivate static final LongAdder _numMemDel = new LongAdder();\nprivate static final LongAdder _numRewrites = new LongAdder();\n- private static final LongAdder _ctimeFSRead = new LongAdder(); //in nano sec\n- private static final LongAdder _ctimeFSWrite = new LongAdder(); //in nano sec\n- private static final LongAdder _ctimeSaved = new LongAdder(); //in nano sec\n- private static final LongAdder _ctimeMissed = new LongAdder(); //in nano sec\n+ // All the time measurements are in nanoseconds\n+ private static final LongAdder _ctimeFSRead = new LongAdder();\n+ private static final LongAdder _ctimeFSWrite = new LongAdder();\n+ private static final LongAdder _ctimeSaved = new LongAdder();\n+ private static final LongAdder _ctimeMissed = new LongAdder();\n+ // Bellow entries are for specific to gpu lineage cache\n+ private static final LongAdder _numHitsGpu = new LongAdder();\n+ private static final LongAdder _numAsyncEvictGpu= new LongAdder();\n+ private static final LongAdder _numSyncEvictGpu = new LongAdder();\npublic static void reset() {\n_numHitsMem.reset();\n@@ -56,6 +61,9 @@ public class LineageCacheStatistics {\n_ctimeFSWrite.reset();\n_ctimeSaved.reset();\n_ctimeMissed.reset();\n+ _numHitsGpu.reset();\n+ _numAsyncEvictGpu.reset();\n+ _numSyncEvictGpu.reset();\n}\npublic static void incrementMemHits() {\n@@ -146,6 +154,21 @@ public class LineageCacheStatistics {\nreturn _numHitsSB.longValue();\n}\n+ public static void incrementGpuHits() {\n+ // Number of times single instruction results are reused in the gpu.\n+ _numHitsGpu.increment();\n+ }\n+\n+ public static void incrementGpuAsyncEvicts() {\n+ // Number of gpu cache entries moved to cpu cache via the background thread\n+ _numAsyncEvictGpu.increment();\n+ }\n+\n+ public static void incrementGpuSyncEvicts() {\n+ // Number of gpu cache entries moved to cpu cache during malloc\n+ _numSyncEvictGpu.increment();\n+ }\n+\npublic static String displayHits() {\nStringBuilder sb = new StringBuilder();\nsb.append(_numHitsMem.longValue());\n@@ -196,4 +219,14 @@ public class LineageCacheStatistics {\nsb.append(String.format(\"%.3f\", ((double)_ctimeMissed.longValue())/1000000000)); //in sec\nreturn sb.toString();\n}\n+\n+ public static String displayGpuStats() {\n+ StringBuilder sb = new StringBuilder();\n+ sb.append(_numHitsGpu.longValue());\n+ sb.append(\"/\");\n+ sb.append(_numAsyncEvictGpu.longValue());\n+ sb.append(\"/\");\n+ sb.append(_numSyncEvictGpu.longValue());\n+ return sb.toString();\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/utils/Statistics.java", "new_path": "src/main/java/org/apache/sysds/utils/Statistics.java", "diff": "@@ -1024,6 +1024,7 @@ public class Statistics\nif (DMLScript.LINEAGE && !ReuseCacheType.isNone()) {\nsb.append(\"LinCache hits (Mem/FS/Del): \\t\" + LineageCacheStatistics.displayHits() + \".\\n\");\nsb.append(\"LinCache MultiLevel (Ins/SB/Fn):\" + LineageCacheStatistics.displayMultiLevelHits() + \".\\n\");\n+ sb.append(\"LinCache GPU (Hit/Async/Sync): \\t\" + LineageCacheStatistics.displayGpuStats() + \".\\n\");\nsb.append(\"LinCache writes (Mem/FS/Del): \\t\" + LineageCacheStatistics.displayWtrites() + \".\\n\");\nsb.append(\"LinCache FStimes (Rd/Wr): \\t\" + LineageCacheStatistics.displayFSTime() + \" sec.\\n\");\nsb.append(\"LinCache Computetime (S/M): \\t\" + LineageCacheStatistics.displayComputeTime() + \" sec.\\n\");\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/TestUtils.java", "new_path": "src/test/java/org/apache/sysds/test/TestUtils.java", "diff": "@@ -78,7 +78,7 @@ import org.apache.sysds.runtime.util.DataConverter;\nimport org.apache.sysds.runtime.util.UtilFunctions;\nimport org.junit.Assert;\n-import jcuda.runtime.JCuda;\n+//import jcuda.runtime.JCuda;\n/**\n@@ -3063,7 +3063,9 @@ public class TestUtils\npublic static int isGPUAvailable() {\n// returns cudaSuccess if at least one gpu is available\n- final int[] deviceCount = new int[1];\n- return JCuda.cudaGetDeviceCount(deviceCount);\n+ //final int[] deviceCount = new int[1];\n+ //return JCuda.cudaGetDeviceCount(deviceCount);\n+ // FIXME: Fails to skip if gpu available but no libraries\n+ return 1; //return false for now\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/lineage/GPUFullReuseTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/lineage/GPUFullReuseTest.java", "diff": "@@ -44,6 +44,7 @@ public class GPUFullReuseTest extends AutomatedTestBase{\n@BeforeClass\npublic static void checkGPU() {\n// Skip all the tests if no GPU is available\n+ // FIXME: Fails to skip if gpu available but no libraries\nAssume.assumeTrue(TestUtils.isGPUAvailable() == cudaError.cudaSuccess);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2980] Add statistics for lineage cache in GPU This patch adds a initial set of statistics for reuse and eviction of GPU intermediates. e.g. LinCache GPU (Hit/Async/Sync): 38/26/25
49,738
23.05.2021 19:42:53
-7,200
2a78db42e9d65e4ab1e256e87913f343d243f523
Fix execution context creation in constant folding This patches fixes a recently introduce bug that assumed that every execution context is created with an available program, but this is clearly not the case in constant folding and other primitives.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/context/ExecutionContextFactory.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/context/ExecutionContextFactory.java", "diff": "@@ -55,7 +55,7 @@ public class ExecutionContextFactory\n//NOTE: even in case of forced singlenode operations, users might still\n//want to run remote parfor which requires the correct execution context\nif( OptimizerUtils.getDefaultExecutionMode()==ExecMode.HYBRID\n- && !(prog.getDMLProg()!=null && prog.getDMLProg().containsRemoteParfor()))\n+ && !(prog!=null && prog.getDMLProg()!=null && prog.getDMLProg().containsRemoteParfor()))\nec = new ExecutionContext(allocateVars, allocateLineage, prog);\nelse\nec = new SparkExecutionContext(allocateVars, allocateLineage, prog);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2953] Fix execution context creation in constant folding This patches fixes a recently introduce bug that assumed that every execution context is created with an available program, but this is clearly not the case in constant folding and other primitives.
49,698
29.05.2021 09:07:38
-19,080
f41707e304ddfa3f79d344896a694100fa7a97a6
[MINOR] fix rendering of tables, use space after headers Closes
[ { "change_type": "MODIFY", "old_path": "docs/site/builtins-reference.md", "new_path": "docs/site/builtins-reference.md", "diff": "@@ -1345,6 +1345,7 @@ sherlockPredict(X, cW1, cb1, cW2, cb2, cW3, cb3, wW1, wb1, wW2, wb2, wW3, wb3,\n| Type | Description |\n| :------------- | :---------- |\n| Matrix[Double] | Class probabilities of shape (N, K). |\n+\n### Example\n```r\n@@ -1943,6 +1944,7 @@ correctTypos(strings, frequency_threshold, distance_threshold, decapitalize, cor\n| is_verbose | Boolean | FALSE | Print debug information |\n### Returns\n+\n| TYPE | Description|\n| :------------- | :---------- |\n| String | Corrected nx1 output frame |\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] fix rendering of tables, use space after headers Closes #1290.
49,738
29.05.2021 21:45:26
-7,200
d27b185f7ee6d210943eec618375894c6ffa20dd
Additional cleanups gridSearch (docs, args, defaults) This patch makes final cleanups in the gridSearch builtin function, now having correct handling for missing trainArgs, adding the handling of predictArgs, and adding the missing parameter documentation.
[ { "change_type": "MODIFY", "old_path": "scripts/builtin/gridSearch.dml", "new_path": "scripts/builtin/gridSearch.dml", "diff": "#\n#-------------------------------------------------------------\n+\n+#-------------------------------------------------------------------------------\n+# X Input feature matrix\n+# y Input label vector (or matrix)\n+# train Name ft of the train function to call via ft(trainArgs)\n+# predict Name fp of the loss function to call via fp((predictArgs,B))\n+# numB Maximum number of parameters in model B (pass the maximum\n+# because the size of B may vary with parameters like icpt\n+# params List of varied hyper-parameter names\n+# paramValues List of matrices providing the parameter values as\n+# columnvectors for position-aligned hyper-parameters in 'params'\n+# trainArgs named List of arguments to pass to the 'train' function, where\n+# gridSearch replaces enumerated hyper-parameter by name, if\n+# not provided or an empty list, the lm parameters are used\n+# predictArgs List of arguments to pass to the 'predict' function, where\n+# gridSearch appends the trained models at the end, if\n+# not provided or an empty list, list(X, y) is used instead\n+# verbose flag for verbose debug output\n+#-------------------------------------------------------------------------------\n+# B the trained model with minimal loss (by the 'predict' function)\n+# opt one-row frame w/ optimal hyperparameters (by 'params' position)\n+#-------------------------------------------------------------------------------\n+\nm_gridSearch = function(Matrix[Double] X, Matrix[Double] y, String train, String predict,\n- Integer ncolB=ncol(X), List[String] params, List[Unknown] paramValues, List[Unknown]\n- trainArgs = list(X=X, y=y, icpt=0, reg=-1, tol=-1, maxi=-1, verbose=FALSE),\n+ Integer numB=ncol(X), List[String] params, List[Unknown] paramValues,\n+ List[Unknown] trainArgs = list(), List[Unknown] predictArgs = list(),\nBoolean verbose = TRUE)\nreturn (Matrix[Double] B, Frame[Unknown] opt)\n{\n- # Step 0) preparation of parameters, lengths, and values in convenient form\n+ # Step 0) handling default arguments, which require access to passed data\n+ if( length(trainArgs) == 0 )\n+ trainArgs = list(X=X, y=y, icpt=0, reg=-1, tol=-1, maxi=-1, verbose=FALSE);\n+ if( length(predictArgs) == 0 )\n+ predictArgs = list(X, y);\n+\n+ # Step 1) preparation of parameters, lengths, and values in convenient form\nnumParams = length(params);\nparamLens = matrix(0, numParams, 1);\nfor( j in 1:numParams ) {\n@@ -40,7 +69,7 @@ m_gridSearch = function(Matrix[Double] X, Matrix[Double] y, String train, String\ncumLens = rev(cumprod(rev(paramLens))/rev(paramLens));\nnumConfigs = prod(paramLens);\n- # Step 1) materialize hyper-parameter combinations\n+ # Step 2) materialize hyper-parameter combinations\n# (simplify debugging and compared to compute negligible)\nHP = matrix(0, numConfigs, numParams);\nparfor( i in 1:nrow(HP) ) {\n@@ -53,23 +82,23 @@ m_gridSearch = function(Matrix[Double] X, Matrix[Double] y, String train, String\nprint(\"GridSeach: Hyper-parameter combinations: \\n\"+toString(HP));\n}\n- # Step 2) training/scoring of parameter combinations\n+ # Step 3) training/scoring of parameter combinations\n# TODO integrate cross validation\n- Rbeta = matrix(0, nrow(HP), ncolB);\n+ Rbeta = matrix(0, nrow(HP), numB);\nRloss = matrix(0, nrow(HP), 1);\nparfor( i in 1:nrow(HP) ) {\n# a) replace training arguments\n- largs = trainArgs;\n+ ltrainArgs = trainArgs;\nfor( j in 1:numParams )\n- largs[as.scalar(params[j])] = as.scalar(HP[i,j]);\n+ ltrainArgs[as.scalar(params[j])] = as.scalar(HP[i,j]);\n# b) core training/scoring and write-back\n- lbeta = t(eval(train, largs))\n+ lbeta = t(eval(train, ltrainArgs))\nRbeta[i,1:ncol(lbeta)] = lbeta;\n- Rloss[i,] = eval(predict, list(X, y, t(Rbeta[i,])));\n+ Rloss[i,] = eval(predict, append(predictArgs,t(lbeta)));\n}\n- # Step 3) select best parameter combination\n+ # Step 4) select best parameter combination\nix = as.scalar(rowIndexMin(t(Rloss)));\nB = t(Rbeta[ix,]); # optimal model\nopt = as.frame(HP[ix,]); # optimal hyper-parameters\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/builtin/GridSearchLM.dml", "new_path": "src/test/scripts/functions/builtin/GridSearchLM.dml", "diff": "@@ -34,9 +34,8 @@ ytest = y[(N+1):nrow(X),];\nparams = list(\"reg\", \"tol\", \"maxi\");\nparamRanges = list(10^seq(0,-4), 10^seq(-6,-12), 10^seq(1,3));\n-trainArgs = list(X=X, y=y, icpt=0, reg=-1, tol=-1, maxi=-1, verbose=FALSE);\n[B1, opt] = gridSearch(X=Xtrain, y=ytrain, train=\"lm\", predict=\"l2norm\",\n- ncolB=ncol(X), params=params, paramValues=paramRanges, trainArgs=trainArgs);\n+ numB=ncol(X), params=params, paramValues=paramRanges);\nB2 = lm(X=Xtrain, y=ytrain, verbose=FALSE);\nl1 = l2norm(Xtest, ytest, B1);\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/builtin/GridSearchMLogreg.dml", "new_path": "src/test/scripts/functions/builtin/GridSearchMLogreg.dml", "diff": "@@ -36,7 +36,8 @@ ytest = y[(N+1):nrow(X),];\nparams = list(\"icpt\", \"reg\", \"maxii\");\nparamRanges = list(seq(0,2),10^seq(1,-6), 10^seq(1,3));\ntrainArgs = list(X=Xtrain, Y=ytrain, icpt=-1, reg=-1, tol=1e-9, maxi=100, maxii=-1, verbose=FALSE);\n-[B1,opt] = gridSearch(Xtrain, ytrain, \"multiLogReg\", \"accuracy\", ncol(X)+1, params, paramRanges, trainArgs, TRUE);\n+[B1,opt] = gridSearch(X=Xtrain, y=ytrain, train=\"multiLogReg\", predict=\"accuracy\", numB=ncol(X)+1,\n+ params=params, paramValues=paramRanges, trainArgs=trainArgs, verbose=TRUE);\nB2 = multiLogReg(X=Xtrain, Y=ytrain, verbose=TRUE);\nl1 = accuracy(Xtest, ytest, B1);\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/functions/builtin/HyperbandLM3.dml", "new_path": "src/test/scripts/functions/builtin/HyperbandLM3.dml", "diff": "@@ -43,7 +43,7 @@ paramRanges = matrix(\"0 20\", rows=1, cols=2);\nparamRanges2 = list(10^seq(0,-4))\ntrainArgs = list(X=X_train, y=y_train, icpt=0, reg=-1, tol=1e-9, maxi=0, verbose=FALSE);\n-[bestWeights, optHyperParams2] = gridSearch(X=X_train, y=y_train, ncolB=ncol(X),\n+[bestWeights, optHyperParams2] = gridSearch(X=X_train, y=y_train, numB=ncol(X),\ntrain=\"lm\", predict=\"l2norm\", trainArgs=trainArgs, params=params, paramValues=paramRanges2);\nprint(toString(optHyperParams))\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2983] Additional cleanups gridSearch (docs, args, defaults) This patch makes final cleanups in the gridSearch builtin function, now having correct handling for missing trainArgs, adding the handling of predictArgs, and adding the missing parameter documentation.
49,722
30.05.2021 01:02:42
-7,200
88341e889666fc1cf3e9407886969afdfbf098e6
Federated frame tokenization (parameterized builtin) Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/InstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/InstructionUtils.java", "diff": "@@ -1089,6 +1089,12 @@ public class InstructionUtils\nreturn InstructionUtils.concatOperands(parts[0], parts[1], createOperand(op1), createOperand(op2), createOperand(out));\n}\n+ public static String constructUnaryInstString(String instString, CPOperand op1, String opcode, CPOperand out) {\n+ String[] parts = instString.split(Lop.OPERAND_DELIMITOR);\n+ parts[1] = opcode;\n+ return InstructionUtils.concatOperands(parts[0], parts[1], createOperand(op1), createOperand(out));\n+ }\n+\n/**\n* Prepare instruction string for sending in a FederatedRequest as a CP instruction.\n* This involves replacing the coordinator operand names with the worker operand names,\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/FEDInstructionUtils.java", "diff": "package org.apache.sysds.runtime.instructions.fed;\n+import org.apache.commons.lang3.ArrayUtils;\nimport org.apache.sysds.runtime.codegen.SpoofCellwise;\nimport org.apache.sysds.runtime.codegen.SpoofMultiAggregate;\nimport org.apache.sysds.runtime.codegen.SpoofOuterProduct;\n@@ -71,6 +72,10 @@ import org.apache.sysds.runtime.instructions.spark.UnarySPInstruction;\nimport org.apache.sysds.runtime.instructions.spark.WriteSPInstruction;\npublic class FEDInstructionUtils {\n+\n+ private static String[] PARAM_BUILTINS = new String[]{\n+ \"replace\", \"rmempty\", \"lowertri\", \"uppertri\", \"transformdecode\", \"transformapply\", \"tokenize\"};\n+\n// private static final Log LOG = LogFactory.getLog(FEDInstructionUtils.class.getName());\n// This is currently a rather simplistic to our solution of replacing instructions with their correct federated\n@@ -164,16 +169,9 @@ public class FEDInstructionUtils {\n}\nelse if( inst instanceof ParameterizedBuiltinCPInstruction ) {\nParameterizedBuiltinCPInstruction pinst = (ParameterizedBuiltinCPInstruction) inst;\n- if((pinst.getOpcode().equals(\"replace\") || pinst.getOpcode().equals(\"rmempty\")\n- || pinst.getOpcode().equals(\"lowertri\") || pinst.getOpcode().equals(\"uppertri\"))\n- && pinst.getTarget(ec).isFederated()) {\n+ if( ArrayUtils.contains(PARAM_BUILTINS, pinst.getOpcode()) && pinst.getTarget(ec).isFederated() )\nfedinst = ParameterizedBuiltinFEDInstruction.parseInstruction(pinst.getInstructionString());\n}\n- else if((pinst.getOpcode().equals(\"transformdecode\") || pinst.getOpcode().equals(\"transformapply\")) &&\n- pinst.getTarget(ec).isFederated()) {\n- return ParameterizedBuiltinFEDInstruction.parseInstruction(pinst.getInstructionString());\n- }\n- }\nelse if (inst instanceof MultiReturnParameterizedBuiltinCPInstruction) {\nMultiReturnParameterizedBuiltinCPInstruction minst = (MultiReturnParameterizedBuiltinCPInstruction) inst;\nif(minst.getOpcode().equals(\"transformencode\") && minst.input1.isFrame()) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/ParameterizedBuiltinFEDInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/fed/ParameterizedBuiltinFEDInstruction.java", "diff": "@@ -27,6 +27,7 @@ import java.util.HashMap;\nimport java.util.LinkedHashMap;\nimport java.util.List;\nimport java.util.Map;\n+import java.util.concurrent.Future;\nimport java.util.stream.Stream;\nimport java.util.zip.Adler32;\nimport java.util.zip.Checksum;\n@@ -57,6 +58,7 @@ import org.apache.sysds.runtime.functionobjects.ValueFunction;\nimport org.apache.sysds.runtime.instructions.InstructionUtils;\nimport org.apache.sysds.runtime.instructions.cp.CPOperand;\nimport org.apache.sysds.runtime.instructions.cp.Data;\n+import org.apache.sysds.runtime.instructions.cp.ScalarObject;\nimport org.apache.sysds.runtime.lineage.LineageItem;\nimport org.apache.sysds.runtime.lineage.LineageItemUtils;\nimport org.apache.sysds.runtime.matrix.data.FrameBlock;\n@@ -119,7 +121,7 @@ public class ParameterizedBuiltinFEDInstruction extends ComputationFEDInstructio\nValueFunction func = ParameterizedBuiltin.getParameterizedBuiltinFnObject(opcode);\nreturn new ParameterizedBuiltinFEDInstruction(new SimpleOperator(func), paramsMap, out, opcode, str);\n}\n- else if(opcode.equals(\"transformapply\") || opcode.equals(\"transformdecode\")) {\n+ else if(opcode.equals(\"transformapply\") || opcode.equals(\"transformdecode\") || opcode.equals(\"tokenize\")) {\nreturn new ParameterizedBuiltinFEDInstruction(null, paramsMap, out, opcode, str);\n}\nelse {\n@@ -154,11 +156,57 @@ public class ParameterizedBuiltinFEDInstruction extends ComputationFEDInstructio\ntransformDecode(ec);\nelse if(opcode.equalsIgnoreCase(\"transformapply\"))\ntransformApply(ec);\n+ else if(opcode.equals(\"tokenize\"))\n+ tokenize(ec);\nelse {\nthrow new DMLRuntimeException(\"Unknown opcode : \" + opcode);\n}\n}\n+ private void tokenize(ExecutionContext ec)\n+ {\n+ FrameObject in = ec.getFrameObject(getTargetOperand());\n+ FederationMap fedMap = in.getFedMapping();\n+\n+ FederatedRequest fr1 = FederationUtils.callInstruction(instString, output,\n+ new CPOperand[] {getTargetOperand()}, new long[] {fedMap.getID()});\n+ fedMap.execute(getTID(), true, fr1);\n+\n+ FrameObject out = ec.getFrameObject(output);\n+ out.setFedMapping(fedMap.copyWithNewID(fr1.getID()));\n+\n+ // get new dims and fed mapping\n+ long ncolId = FederationUtils.getNextFedDataID();\n+ CPOperand ncolOp = new CPOperand(String.valueOf(ncolId), ValueType.INT64, DataType.SCALAR);\n+\n+ String unaryString = InstructionUtils.constructUnaryInstString(instString, output, \"ncol\", ncolOp);\n+ FederatedRequest fr2 = FederationUtils.callInstruction(unaryString, ncolOp,\n+ new CPOperand[] {output}, new long[] {out.getFedMapping().getID()});\n+ FederatedRequest fr3 = new FederatedRequest(FederatedRequest.RequestType.GET_VAR, fr2.getID());\n+ Future<FederatedResponse>[] ffr = out.getFedMapping().execute(getTID(), true, fr2, fr3);\n+\n+ long cols = 0;\n+ for(int i = 0; i < ffr.length; i++) {\n+ try {\n+ if(in.isFederated(FederationMap.FType.COL)) {\n+ out.getFedMapping().getFederatedRanges()[i + 1].setBeginDim(1, cols);\n+ cols += ((ScalarObject) ffr[i].get().getData()[0]).getLongValue();\n+ }\n+ else if(in.isFederated(FederationMap.FType.ROW))\n+ cols = ((ScalarObject) ffr[i].get().getData()[0]).getLongValue();\n+ out.getFedMapping().getFederatedRanges()[i].setEndDim(1, cols);\n+ }\n+ catch(Exception e) {\n+ throw new DMLRuntimeException(e);\n+ }\n+ }\n+\n+ Types.ValueType[] schema = new Types.ValueType[(int) cols];\n+ Arrays.fill(schema, ValueType.STRING);\n+ out.setSchema(schema);\n+ out.getDataCharacteristics().setDimension(in.getNumRows(), cols);\n+ }\n+\nprivate void triangle(ExecutionContext ec, String opcode) {\nboolean lower = opcode.equals(\"lowertri\");\nboolean diag = Boolean.parseBoolean(params.get(\"diag\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/federated/primitives/FederatedTokenizeTest.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.apache.sysds.test.functions.federated.primitives;\n+\n+import java.io.IOException;\n+import java.util.Arrays;\n+import java.util.Collection;\n+\n+import org.apache.sysds.api.DMLScript;\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.common.Types.ExecMode;\n+import org.apache.sysds.parser.DataExpression;\n+import org.apache.sysds.runtime.io.FileFormatPropertiesCSV;\n+import org.apache.sysds.runtime.io.FrameReaderFactory;\n+import org.apache.sysds.runtime.io.FrameWriter;\n+import org.apache.sysds.runtime.io.FrameWriterFactory;\n+import org.apache.sysds.runtime.matrix.data.FrameBlock;\n+import org.apache.sysds.runtime.meta.MatrixCharacteristics;\n+import org.apache.sysds.runtime.util.HDFSTool;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Assert;\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+\n+@RunWith(value = Parameterized.class)\[email protected]\n+public class FederatedTokenizeTest extends AutomatedTestBase {\n+\n+ private final static String TEST_NAME1 = \"FederatedTokenizeTest\";\n+\n+ private final static String TEST_DIR = \"functions/federated/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + FederatedTokenizeTest.class.getSimpleName() + \"/\";\n+\n+ private static final String DATASET = \"20news/20news_subset_untokenized.csv\";\n+\n+ @Parameterized.Parameter()\n+ public int rows;\n+ @Parameterized.Parameter(1)\n+ public int cols;\n+\n+ @Parameterized.Parameter(2)\n+ public boolean rowPartitioned;\n+\n+ @Parameterized.Parameters\n+ public static Collection<Object[]> data() {\n+ return Arrays.asList(new Object[][] {\n+ {3, 4, true},\n+ });\n+ }\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] {\"S\"}));\n+ }\n+\n+ @Test\n+ public void testTokenizeFullDenseFrameCP() {\n+ runAggregateOperationTest(ExecMode.SINGLE_NODE);\n+ }\n+\n+ private void runAggregateOperationTest(ExecMode execMode) {\n+ setExecMode(execMode);\n+\n+ String TEST_NAME = TEST_NAME1;\n+\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+ int port1 = getRandomAvailablePort();\n+ int port2 = getRandomAvailablePort();\n+ int port3 = getRandomAvailablePort();\n+ int port4 = getRandomAvailablePort();\n+ Thread t1 = startLocalFedWorkerThread(port1, FED_WORKER_WAIT_S);\n+ Thread t2 = startLocalFedWorkerThread(port2, FED_WORKER_WAIT_S);\n+ Thread t3 = startLocalFedWorkerThread(port3, FED_WORKER_WAIT_S);\n+ Thread t4 = startLocalFedWorkerThread(port4);\n+\n+ FileFormatPropertiesCSV ffpCSV = new FileFormatPropertiesCSV(false, DataExpression.DEFAULT_DELIM_DELIMITER, false);\n+\n+ // split dataset\n+ FrameBlock dataset;\n+ try {\n+ dataset = FrameReaderFactory.createFrameReader(Types.FileFormat.CSV, ffpCSV)\n+ .readFrameFromHDFS(DATASET_DIR + DATASET, -1, -1);\n+\n+ // default for write\n+ FrameWriter fw = FrameWriterFactory.createFrameWriter(Types.FileFormat.CSV, ffpCSV);\n+ writeDatasetSlice(dataset, fw, ffpCSV, \"AH\");\n+ writeDatasetSlice(dataset, fw, ffpCSV, \"AL\");\n+ writeDatasetSlice(dataset, fw, ffpCSV, \"BH\");\n+ }\n+ catch(IOException e) {\n+ e.printStackTrace();\n+ }\n+\n+ rtplatform = execMode;\n+ if(rtplatform == ExecMode.SPARK) {\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+ }\n+ TestConfiguration config = availableTestConfigurations.get(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ // Run reference dml script with normal matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-explain\", \"-args\", DATASET_DIR + DATASET, HOME + TEST_NAME + \".json\", expected(\"S\")};\n+ runTest(null);\n+ // Run actual dml script with federated matrix\n+\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"100\", \"-nvargs\",\n+ \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"AH\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"AL\")),\n+ \"in_X3=\" + TestUtils.federatedAddress(port3, input(\"BH\")),\n+ \"in_S=\" + input(HOME + TEST_NAME + \".json\"), \"rows=\" + rows, \"cols=\" + cols,\n+ \"out_R=\" + output(\"S\")};\n+ runTest(null);\n+\n+ compareResults(1e-9);\n+ Assert.assertTrue(heavyHittersContainsString(\"fed_tokenize\"));\n+ TestUtils.shutdownThreads(t1, t2, t3, t4);\n+ }\n+\n+ private void writeDatasetSlice(FrameBlock dataset, FrameWriter fw, FileFormatPropertiesCSV ffpCSV, String name) throws IOException {\n+ fw.writeFrameToHDFS(dataset, input(name), dataset.getNumRows(), dataset.getNumColumns());\n+ HDFSTool.writeMetaDataFile(input(DataExpression.getMTDFileName(name)), null, dataset.getSchema(),\n+ Types.DataType.FRAME, new MatrixCharacteristics(dataset.getNumRows(), dataset.getNumColumns()),\n+ Types.FileFormat.CSV, ffpCSV);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedTokenizeTest.dml", "diff": "+#-------------------------------------------------------------\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+F1 = federated(type=\"frame\", addresses=list($in_X1, $in_X2, $in_X3),\n+ ranges=list(list(0, 0), list(2, $cols), list(2, 0), list(4, $cols),\n+ list(4, 0), list(6, $cols)));\n+\n+max_token = 2000;\n+\n+# Example spec:\n+jspec = \"{algo:ngram, algo_params: {min_gram: 1,max_gram: 3}, out:hash, out_params:\n+ {num_features: 128}, format_wide: true, id_cols: [2,1], tokenize_col: 3}\";\n+\n+F2 = tokenize(target=F1[,2:4], spec=jspec, max_tokens=max_token);\n+\n+jspec2 = \"{ids: true, recode: [1,2]}\";\n+[X, M] = transformencode(target=F2, spec=jspec2);\n+write(X, $out_R);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedTokenizeTestReference.dml", "diff": "+#-------------------------------------------------------------\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+F = read($1, data_type=\"frame\", format=\"csv\", sep=\",\");\n+F = F[2:3, 1:4];\n+F = rbind(F, rbind(F, F));\n+\n+max_token = 2000;\n+\n+# Example spec:\n+jspec = \"{algo:ngram, algo_params:{min_gram:1, max_gram:3}, out:hash, out_params:\n+ {num_features: 128},format_wide: true,id_cols: [2,1],tokenize_col: 3}\";\n+\n+res = tokenize(target=F[,2:4], spec=jspec, max_tokens=max_token);\n+\n+jspec2 = \"{ids: true, recode: [1,2]}\";\n+[X, M] = transformencode(target=res, spec=jspec2);\n+write(X, $3);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2978] Federated frame tokenization (parameterized builtin) Closes #1284.
49,738
30.05.2021 01:24:29
-7,200
5f23666d50a7f70123e23c0e4e8c9d32d0c639d4
[MINOR] Cleanup list of builtin functions (alphabetical ordering)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/common/Builtins.java", "new_path": "src/main/java/org/apache/sysds/common/Builtins.java", "diff": "@@ -38,16 +38,15 @@ import org.apache.sysds.common.Types.ReturnType;\n*/\npublic enum Builtins {\n//builtin functions\n- ARIMA(\"arima\", true),\n- ABS(\"abs\", false),\n- GET_ACCURACY(\"getAccuracy\", true),\nABSTAIN(\"abstain\", true),\n+ ABS(\"abs\", false),\nACOS(\"acos\", false),\nALS(\"als\", true),\nALS_CG(\"alsCG\", true),\nALS_DS(\"alsDS\", true),\nALS_PREDICT(\"alsPredict\", true),\nALS_TOPK_PREDICT(\"alsTopkPredict\", true),\n+ ARIMA(\"arima\", true),\nASIN(\"asin\", false),\nATAN(\"atan\", false),\nAUTOENCODER2LAYER(\"autoencoder_2layer\", true),\n@@ -55,9 +54,9 @@ public enum Builtins {\nAVG_POOL_BACKWARD(\"avg_pool_backward\", false),\nBATCH_NORM2D(\"batch_norm2d\", false, ReturnType.MULTI_RETURN),\nBATCH_NORM2D_BACKWARD(\"batch_norm2d_backward\", false, ReturnType.MULTI_RETURN),\n- BANDIT(\"bandit\", true),\nBIASADD(\"bias_add\", false),\nBIASMULT(\"bias_multiply\", false),\n+ BANDIT(\"bandit\", true),\nBITWAND(\"bitwAnd\", false),\nBITWOR(\"bitwOr\", false),\nBITWXOR(\"bitwXor\", false),\n@@ -72,6 +71,7 @@ public enum Builtins {\nCAST_AS_BOOLEAN(\"as.logical\", \"as.boolean\", false),\nCBIND(\"cbind\", \"append\", false),\nCEIL(\"ceil\", \"ceiling\", false),\n+ CHOLESKY(\"cholesky\", false),\nCOLMAX(\"colMaxs\", false),\nCOLMEAN(\"colMeans\", false),\nCOLMIN(\"colMins\", false),\n@@ -82,27 +82,29 @@ public enum Builtins {\nCOLVAR(\"colVars\", false),\nCOMPONENTS(\"components\", true),\nCOMPRESS(\"compress\", false),\n- CSPLINE(\"cspline\", true),\n- CSPLINE_CG(\"csplineCG\", true),\n- CSPLINE_DS(\"csplineDS\", true),\n- DECOMPRESS(\"decompress\", false),\n+ CONFUSIONMATRIX(\"confusionMatrix\", true),\nCONV2D(\"conv2d\", false),\nCONV2D_BACKWARD_FILTER(\"conv2d_backward_filter\", false),\nCONV2D_BACKWARD_DATA(\"conv2d_backward_data\", false),\n+ COR(\"cor\", true),\nCORRECTTYPOS(\"correctTypos\", true),\nCOS(\"cos\", false),\n- COV(\"cov\", false),\nCOSH(\"cosh\", false),\n- CHOLESKY(\"cholesky\", false),\n+ COUNT_DISTINCT(\"countDistinct\",false),\n+ COUNT_DISTINCT_APPROX(\"countDistinctApprox\",false),\n+ COV(\"cov\", false),\n+ COX(\"cox\", true),\n+ CSPLINE(\"cspline\", true),\n+ CSPLINE_CG(\"csplineCG\", true),\n+ CSPLINE_DS(\"csplineDS\", true),\nCUMMAX(\"cummax\", false),\nCUMMIN(\"cummin\", false),\nCUMPROD(\"cumprod\", false),\nCUMSUM(\"cumsum\", false),\nCUMSUMPROD(\"cumsumprod\", false),\n- CONFUSIONMATRIX(\"confusionMatrix\", true),\n- COR(\"cor\", true),\n- COX(\"cox\", true),\nDBSCAN(\"dbscan\", true),\n+ DECISIONTREE(\"decisionTree\", true),\n+ DECOMPRESS(\"decompress\", false),\nDETECTSCHEMA(\"detectSchema\", false),\nDENIALCONSTRAINTS(\"denialConstraints\", true),\nDIAG(\"diag\", false),\n@@ -121,6 +123,7 @@ public enum Builtins {\nFLOOR(\"floor\", false),\nFRAME_SORT(\"frameSort\", true),\nGAUSSIAN_CLASSIFIER(\"gaussianClassifier\", true),\n+ GET_ACCURACY(\"getAccuracy\", true),\nGET_PERMUTATIONS(\"getPermutations\", true),\nGLM(\"glm\", true),\nGMM(\"gmm\", true),\n@@ -131,9 +134,6 @@ public enum Builtins {\nIFELSE(\"ifelse\", false),\nIMG_MIRROR(\"img_mirror\", true),\nIMG_BRIGHTNESS(\"img_brightness\", true),\n- IMPUTE_BY_MEAN(\"imputeByMean\", true),\n- IMPUTE_BY_MEDIAN(\"imputeByMedian\", true),\n- IMPUTE_BY_MODE(\"imputeByMode\", true),\nIMG_CROP(\"img_crop\", true),\nIMG_TRANSFORM(\"img_transform\", true),\nIMG_TRANSLATE(\"img_translate\", true),\n@@ -143,6 +143,9 @@ public enum Builtins {\nIMG_SAMPLE_PAIRING(\"img_sample_pairing\", true),\nIMG_INVERT(\"img_invert\", true),\nIMG_POSTERIZE(\"img_posterize\", true),\n+ IMPUTE_BY_MEAN(\"imputeByMean\", true),\n+ IMPUTE_BY_MEDIAN(\"imputeByMedian\", true),\n+ IMPUTE_BY_MODE(\"imputeByMode\", true),\nIMPUTE_FD(\"imputeByFD\", true),\nINTERQUANTILE(\"interQuantile\", false),\nINTERSECT(\"intersect\", true),\n@@ -156,7 +159,6 @@ public enum Builtins {\nKMEANSPREDICT(\"kmeansPredict\", true),\nKNNBF(\"knnbf\", true),\nKNN(\"knn\", true),\n- DECISIONTREE(\"decisionTree\", true),\nL2SVM(\"l2svm\", true),\nL2SVMPREDICT(\"l2svmPredict\", true),\nLASSO(\"lasso\", true),\n@@ -173,29 +175,29 @@ public enum Builtins {\nLSTM_BACKWARD(\"lstm_backward\", false, ReturnType.MULTI_RETURN),\nLU(\"lu\", false, ReturnType.MULTI_RETURN),\nMAP(\"map\", false),\n- MEAN(\"mean\", \"avg\", false),\n- MICE(\"mice\", true),\n- MIN(\"min\", \"pmin\", false),\nMAX(\"max\", \"pmax\", false),\nMAX_POOL(\"max_pool\", false),\nMAX_POOL_BACKWARD(\"max_pool_backward\", false),\n+ MEAN(\"mean\", \"avg\", false),\nMEDIAN(\"median\", false),\n+ MICE(\"mice\", true),\n+ MIN(\"min\", \"pmin\", false),\nMOMENT(\"moment\", \"centralMoment\", false),\nMSVM(\"msvm\", true),\nMSVMPREDICT(\"msvmPredict\", true),\nMULTILOGREG(\"multiLogReg\", true),\nMULTILOGREGPREDICT(\"multiLogRegPredict\", true),\nNA_LOCF(\"na_locf\", true),\n+ NAIVEBAYES(\"naiveBayes\", true, false),\n+ NAIVEBAYESPREDICT(\"naiveBayesPredict\", true, false),\nNCOL(\"ncol\", false),\nNORMALIZE(\"normalize\", true),\nNROW(\"nrow\", false),\n- NAIVEBAYES(\"naiveBayes\", true, false),\n- NAIVEBAYESPREDICT(\"naiveBayesPredict\", true, false),\nOUTER(\"outer\", false),\nOUTLIER(\"outlier\", true, false), //TODO parameterize opposite\n- OUTLIER_SD(\"outlierBySd\", true),\n- OUTLIER_IQR(\"outlierByIQR\", true),\nOUTLIER_ARIMA(\"outlierByArima\",true),\n+ OUTLIER_IQR(\"outlierByIQR\", true),\n+ OUTLIER_SD(\"outlierBySd\", true),\nPCA(\"pca\", true),\nPCAINVERSE(\"pcaInverse\", true),\nPCATRANSFORM(\"pcaTransform\", true),\n@@ -213,9 +215,9 @@ public enum Builtins {\nROUND(\"round\", false),\nROWINDEXMAX(\"rowIndexMax\", false),\nROWINDEXMIN(\"rowIndexMin\", false),\n- ROWMIN(\"rowMins\", false),\nROWMAX(\"rowMaxs\", false),\nROWMEAN(\"rowMeans\", false),\n+ ROWMIN(\"rowMins\", false),\nROWPROD(\"rowProds\", false),\nROWSD(\"rowSds\", false),\nROWSUM(\"rowSums\", false),\n@@ -229,7 +231,6 @@ public enum Builtins {\nSIGN(\"sign\", false),\nSIN(\"sin\", false),\nSINH(\"sinh\", false),\n- STEPLM(\"steplm\",true, ReturnType.MULTI_RETURN),\nSLICEFINDER(\"slicefinder\", true),\nSMOTE(\"smote\", true),\nSOLVE(\"solve\", false),\n@@ -237,27 +238,27 @@ public enum Builtins {\nSPLIT_BALANCED(\"splitBalanced\", true),\nSTABLE_MARRIAGE(\"stableMarriage\", true),\nSTATSNA(\"statsNA\", true),\n+ STEPLM(\"steplm\",true, ReturnType.MULTI_RETURN),\nSQRT(\"sqrt\", false),\nSUM(\"sum\", false),\nSVD(\"svd\", false, ReturnType.MULTI_RETURN),\n- TRANS(\"t\", false),\nTABLE(\"table\", \"ctable\", false),\nTAN(\"tan\", false),\nTANH(\"tanh\", false),\n- TRACE(\"trace\", false),\nTO_ONE_HOT(\"toOneHot\", true),\nTOMEKLINK(\"tomeklink\", true),\n+ TRACE(\"trace\", false),\n+ TRANS(\"t\", false),\nTYPEOF(\"typeof\", false),\n- COUNT_DISTINCT(\"countDistinct\",false),\n- COUNT_DISTINCT_APPROX(\"countDistinctApprox\",false),\n+ UNIVAR(\"univar\", true),\nVAR(\"var\", false),\nVECTOR_TO_CSV(\"vectorToCsv\", true),\n- XOR(\"xor\", false),\n- UNIVAR(\"univar\", true),\nWINSORIZE(\"winsorize\", true, false), //TODO parameterize w/ prob, min/max val\n+ XOR(\"xor\", false),\n//parameterized builtin functions\nCDF(\"cdf\", false, true),\n+ CVLM(\"cvlm\", true, false),\nGROUPEDAGG(\"aggregate\", \"groupedAggregate\", false, true),\nINVCDF(\"icdf\", false, true),\nLISTNV(\"list\", false, true), //note: builtin and parbuiltin\n@@ -270,16 +271,15 @@ public enum Builtins {\nPNORM(\"pnorm\", false, true),\nPT(\"pt\", false, true),\nQCHISQ(\"qchisq\", false, true),\n+ QEXP(\"qexp\", false, true),\nQF(\"qf\", false, true),\nQNORM(\"qnorm\", false, true),\nQT(\"qt\", false, true),\n- QEXP(\"qexp\", false, true),\nREPLACE(\"replace\", false, true),\nRMEMPTY(\"removeEmpty\", false, true),\nSCALE(\"scale\", true, false),\nSCALEAPPLY(\"scaleApply\", true, false),\nTIME(\"time\", false),\n- CVLM(\"cvlm\", true, false),\nTOKENIZE(\"tokenize\", false, true),\nTOSTRING(\"toString\", false, true),\nTRANSFORMAPPLY(\"transformapply\", false, true),\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Cleanup list of builtin functions (alphabetical ordering)
49,692
02.06.2021 18:18:07
-7,200
fd4b0d05a38a29567c2a44d6c872c1f7d120cef8
Add initial lineage based debugger This patch adds a lineage based debugger which helps tracking the first operator responsible for a constraint violation. Currently, the supported constraints are NAN, positive infinity and negative infinity. AMLS project SS2021. Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/api/DMLOptions.java", "new_path": "src/main/java/org/apache/sysds/api/DMLOptions.java", "diff": "@@ -66,6 +66,7 @@ public class DMLOptions {\npublic ReuseCacheType linReuseType = ReuseCacheType.NONE; // reuse type (full, partial, hybrid)\npublic LineageCachePolicy linCachePolicy= LineageCachePolicy.COSTNSIZE; // lineage cache eviction policy\npublic boolean lineage_estimate = false; // whether estimate reuse benefits\n+ public boolean lineage_debugger = false; // whether enable lineage debugger\npublic boolean fedWorker = false;\npublic int fedWorkerPort = -1;\npublic boolean checkPrivacy = false; // Check which privacy constraints are loaded and checked during federated execution\n@@ -140,6 +141,8 @@ public class DMLOptions {\ndmlOptions.linCachePolicy = LineageCachePolicy.DAGHEIGHT;\nelse if (lineageType.equalsIgnoreCase(\"estimate\"))\ndmlOptions.lineage_estimate = lineageType.equalsIgnoreCase(\"estimate\");\n+ else if (lineageType.equalsIgnoreCase(\"debugger\"))\n+ dmlOptions.lineage_debugger = lineageType.equalsIgnoreCase(\"debugger\");\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/apache/sysds/api/DMLScript.java", "new_path": "src/main/java/org/apache/sysds/api/DMLScript.java", "diff": "@@ -100,6 +100,7 @@ public class DMLScript\npublic static ReuseCacheType LINEAGE_REUSE = DMLOptions.defaultOptions.linReuseType; // whether lineage-based reuse\npublic static LineageCachePolicy LINEAGE_POLICY = DMLOptions.defaultOptions.linCachePolicy; // lineage cache eviction policy\npublic static boolean LINEAGE_ESTIMATE = DMLOptions.defaultOptions.lineage_estimate; // whether estimate reuse benefits\n+ public static boolean LINEAGE_DEBUGGER = DMLOptions.defaultOptions.lineage_debugger; // whether enable lineage debugger\npublic static boolean CHECK_PRIVACY = DMLOptions.defaultOptions.checkPrivacy; // Check which privacy constraints are loaded and checked during federated execution\npublic static boolean USE_ACCELERATOR = DMLOptions.defaultOptions.gpu;\n@@ -224,6 +225,7 @@ public class DMLScript\nLINEAGE_POLICY = dmlOptions.linCachePolicy;\nLINEAGE_ESTIMATE = dmlOptions.lineage_estimate;\nCHECK_PRIVACY = dmlOptions.checkPrivacy;\n+ LINEAGE_DEBUGGER = dmlOptions.lineage_debugger;\nString fnameOptConfig = dmlOptions.configFile;\nboolean isFile = dmlOptions.filePath != null;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/context/ExecutionContext.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/context/ExecutionContext.java", "diff": "@@ -48,6 +48,7 @@ import org.apache.sysds.runtime.instructions.gpu.context.CSRPointer;\nimport org.apache.sysds.runtime.instructions.gpu.context.GPUContext;\nimport org.apache.sysds.runtime.instructions.gpu.context.GPUObject;\nimport org.apache.sysds.runtime.lineage.Lineage;\n+import org.apache.sysds.runtime.lineage.LineageDebugger;\nimport org.apache.sysds.runtime.lineage.LineageItem;\nimport org.apache.sysds.runtime.matrix.data.FrameBlock;\nimport org.apache.sysds.runtime.matrix.data.MatrixBlock;\n@@ -808,9 +809,16 @@ public class ExecutionContext {\npublic void traceLineage(Instruction inst) {\nif( _lineage == null )\nthrow new DMLRuntimeException(\"Lineage Trace unavailable.\");\n+ // TODO bra: store all newly created lis in active list\n_lineage.trace(inst, this);\n}\n+ public void maintainLineageDebuggerInfo(Instruction inst) {\n+ if( _lineage == null )\n+ throw new DMLRuntimeException(\"Lineage Trace unavailable.\");\n+ LineageDebugger.maintainSpecialValueBits(_lineage, inst, this);\n+ }\n+\npublic LineageItem getLineageItem(CPOperand input) {\nif( _lineage == null )\nthrow new DMLRuntimeException(\"Lineage Trace unavailable.\");\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/CPInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/cp/CPInstruction.java", "diff": "@@ -152,6 +152,9 @@ public abstract class CPInstruction extends Instruction\nif (!LineageCacheConfig.ReuseCacheType.isNone() && DMLScript.USE_ACCELERATOR\n&& LineageCacheConfig.CONCURRENTGPUEVICTION)\nLineageCacheConfig.STOPBACKGROUNDEVICTION = true;\n+\n+ if (DMLScript.LINEAGE_DEBUGGER)\n+ ec.maintainLineageDebuggerInfo(this);\n}\n/**\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/GPUInstruction.java", "new_path": "src/main/java/org/apache/sysds/runtime/instructions/gpu/GPUInstruction.java", "diff": "@@ -226,6 +226,9 @@ public abstract class GPUInstruction extends Instruction implements LineageTrace\nif(gpuCtx != null)\ngpuCtx.printMemoryInfo(getOpcode());\n}\n+\n+ //default post-process behavior\n+ super.postprocessInstruction(ec);\n}\n/**\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysds/runtime/lineage/BooleanArray32.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.apache.sysds.runtime.lineage;\n+\n+public class BooleanArray32 {\n+ private int _value;\n+\n+ public BooleanArray32(int value){\n+ _value = value;\n+ }\n+\n+ public boolean get(int pos) {\n+ return (_value & (1 << pos)) != 0;\n+ }\n+\n+ public void set(int pos, boolean value) {\n+ int mask = 1 << pos;\n+ _value = (_value & ~mask) | (value ? mask : 0);\n+ }\n+\n+ public int getValue() {\n+ return _value;\n+ }\n+\n+ public void setValue(int value) {\n+ _value = value;\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageDebugger.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.apache.sysds.runtime.lineage;\n+\n+\n+import org.apache.sysds.runtime.controlprogram.caching.CacheableData;\n+import org.apache.sysds.runtime.controlprogram.context.ExecutionContext;\n+import org.apache.sysds.runtime.instructions.Instruction;\n+import org.apache.sysds.runtime.instructions.cp.*;\n+import org.apache.sysds.runtime.matrix.data.MatrixBlock;\n+\n+import java.util.ArrayList;\n+import java.util.Collection;\n+import java.util.Queue;\n+import java.util.LinkedList;\n+\n+public class LineageDebugger {\n+ public static final int POS_NAN = 0;\n+ public static final int POS_POSITIVE_INFINITY = 1;\n+ public static final int POS_NEGATIVE_INFINITY = 2;\n+\n+ public static void maintainSpecialValueBits(Lineage lineage, Instruction inst, ExecutionContext ec) {\n+ ArrayList<CPOperand> outputs = new ArrayList<>();\n+\n+ // Only CP instructions are supported right now\n+ CPOperand singleOutput =\n+ inst instanceof ComputationCPInstruction ? ((ComputationCPInstruction) inst).getOutput() :\n+ inst instanceof BuiltinNaryCPInstruction ? ((BuiltinNaryCPInstruction) inst).getOutput() :\n+ inst instanceof SqlCPInstruction ? ((SqlCPInstruction) inst).getOutput() :\n+ inst instanceof VariableCPInstruction ? ((VariableCPInstruction) inst).getOutput() :\n+ null;\n+ if (singleOutput != null)\n+ outputs.add(singleOutput);\n+\n+ Collection<CPOperand> multiOutputs =\n+ inst instanceof MultiReturnBuiltinCPInstruction ? ((MultiReturnBuiltinCPInstruction) inst).getOutputs() :\n+ inst instanceof MultiReturnParameterizedBuiltinCPInstruction ? ((MultiReturnParameterizedBuiltinCPInstruction) inst).getOutputs() :\n+ null;\n+ if (multiOutputs != null)\n+ outputs.addAll(multiOutputs);\n+\n+ for (CPOperand output : outputs) {\n+ CacheableData<MatrixBlock> cd = ec.getMatrixObject(output);\n+ MatrixBlock mb = cd.acquireReadAndRelease();\n+ LineageItem li = lineage.get(output);\n+\n+ updateSpecialValueBit(mb, li, POS_NAN, Double.NaN);\n+ updateSpecialValueBit(mb, li, POS_POSITIVE_INFINITY, Double.POSITIVE_INFINITY);\n+ updateSpecialValueBit(mb, li, POS_NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY);\n+ }\n+ }\n+\n+ public static LineageItem firstOccurrenceOfNR(LineageItem li, int pos) {\n+ if (!li.getSpecialValueBit(pos))\n+ return null;\n+\n+ LineageItem tmp;\n+ Queue<LineageItem> q = new LinkedList<>();\n+ q.add(li);\n+\n+ while ((tmp = q.poll()) != null) {\n+ if (tmp.isVisited())\n+ continue;\n+\n+ if (tmp.getInputs() != null) {\n+ boolean flag = false;\n+ for (LineageItem in : tmp.getInputs()) {\n+ flag |= in.getSpecialValueBit(pos);\n+ q.add(in);\n+ }\n+ if (!flag)\n+ break;\n+ }\n+ tmp.setVisited(true);\n+ }\n+ li.resetVisitStatusNR();\n+ return tmp;\n+ }\n+\n+ private static void updateSpecialValueBit(MatrixBlock mb, LineageItem li, int pos, double pattern) {\n+ boolean flag = false;\n+ for (LineageItem input : li.getInputs()) {\n+ if (input.getSpecialValueBit(pos)) {\n+ flag = true;\n+ break;\n+ }\n+ }\n+ flag |= mb.containsValue(pattern);\n+ li.setSpecialValueBit(pos, flag);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageItem.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageItem.java", "diff": "@@ -37,6 +37,7 @@ public class LineageItem {\nprivate int _hash = 0;\nprivate LineageItem _dedupPatch;\nprivate long _distLeaf2Node;\n+ private final BooleanArray32 _specialValueBits; // TODO: Move this to a new subclass\n// init visited to true to ensure visited items are\n// not hidden when used as inputs to new items\nprivate boolean _visited = true;\n@@ -53,30 +54,30 @@ public class LineageItem {\n}\npublic LineageItem(long id, String data) {\n- this(id, data, \"\", null);\n+ this(id, data, \"\", null, 0);\n}\npublic LineageItem(String data, String opcode) {\n- this(_idSeq.getNextID(), data, opcode, null);\n+ this(_idSeq.getNextID(), data, opcode, null, 0);\n}\npublic LineageItem(String opcode, LineageItem[] inputs) {\n- this(_idSeq.getNextID(), \"\", opcode, inputs);\n+ this(_idSeq.getNextID(), \"\", opcode, inputs, 0);\n}\npublic LineageItem(String data, String opcode, LineageItem[] inputs) {\n- this(_idSeq.getNextID(), data, opcode, inputs);\n+ this(_idSeq.getNextID(), data, opcode, inputs, 0);\n}\npublic LineageItem(String opcode, LineageItem dedupPatch, LineageItem[] inputs) {\n- this(_idSeq.getNextID(), \"\", opcode, inputs);\n+ this(_idSeq.getNextID(), \"\", opcode, inputs, 0);\n// maintain a pointer to the dedup patch\n_dedupPatch = dedupPatch;\n_hash = _dedupPatch._hash;\n}\npublic LineageItem(String opcode, LineageItem dedupPatch, int dpatchHash, LineageItem[] inputs) {\n- this(_idSeq.getNextID(), \"\", opcode, inputs);\n+ this(_idSeq.getNextID(), \"\", opcode, inputs, 0);\n// maintain a pointer to the dedup patch\n_dedupPatch = dedupPatch;\n_hash = dpatchHash;\n@@ -87,14 +88,14 @@ public class LineageItem {\n}\npublic LineageItem(long id, LineageItem li) {\n- this(id, li._data, li._opcode, li._inputs);\n+ this(id, li._data, li._opcode, li._inputs, 0);\n}\npublic LineageItem(long id, String data, String opcode) {\n- this(id, data, opcode, null);\n+ this(id, data, opcode, null, 0);\n}\n- public LineageItem(long id, String data, String opcode, LineageItem[] inputs) {\n+ public LineageItem(long id, String data, String opcode, LineageItem[] inputs, int specialValueBits) {\n_id = id;\n_opcode = opcode;\n_data = data;\n@@ -104,6 +105,7 @@ public class LineageItem {\n_hash = hashCode();\n// store the distance of this node from the leaves. (O(#inputs)) operation\n_distLeaf2Node = distLeaf2Node();\n+ _specialValueBits = new BooleanArray32(specialValueBits);\n}\npublic LineageItem[] getInputs() {\n@@ -142,6 +144,14 @@ public class LineageItem {\n_visited = flag;\n}\n+ public void setSpecialValueBit(int pos, boolean flag) {\n+ _specialValueBits.set(pos, flag);\n+ }\n+\n+ public void setSpecialValueBits(int value) {\n+ _specialValueBits.setValue(value);\n+ }\n+\nprivate long distLeaf2Node() {\n// Derive height only if the corresponding reuse\n// policy is selected, otherwise set -1.\n@@ -169,6 +179,14 @@ public class LineageItem {\nreturn _opcode;\n}\n+ public boolean getSpecialValueBit(int pos) {\n+ return _specialValueBits.get(pos);\n+ }\n+\n+ public int getSpecialValueBits() {\n+ return _specialValueBits.getValue();\n+ }\n+\npublic boolean isPlaceholder() {\nreturn _opcode.startsWith(LineageItemUtils.LPLACEHOLDER);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageItemUtils.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageItemUtils.java", "diff": "@@ -135,6 +135,9 @@ public class LineageItemUtils {\n.map(i -> String.format(\"(%d)\", i.getId()))\n.collect(Collectors.joining(\" \"));\nsb.append(ids);\n+\n+ if (DMLScript.LINEAGE_DEBUGGER)\n+ sb.append(\" \").append(\"[\").append(li.getSpecialValueBits()).append(\"]\");\n}\nreturn sb.toString().trim();\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageParser.java", "new_path": "src/main/java/org/apache/sysds/runtime/lineage/LineageParser.java", "diff": "@@ -108,15 +108,19 @@ public class LineageParser\n}*/\nArrayList<LineageItem> inputs = new ArrayList<>();\n+ int specialValueBits = 0;\nfor( int i=1; i<tokens.length; i++ ) {\nString token = tokens[i];\nif (token.startsWith(\"(\") && token.endsWith(\")\")) {\ntoken = token.substring(1, token.length()-1); //rm parentheses\ninputs.add(map.get(Long.valueOf(token)));\n+ } else if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n+ token = token.substring(1, token.length() - 1); //rm parentheses\n+ specialValueBits = Integer.parseInt(token);\n} else\nthrow new ParseException(\"Invalid format for LineageItem reference\");\n}\n- return new LineageItem(id, \"\", opcode, inputs.toArray(new LineageItem[0]));\n+ return new LineageItem(id, \"\", opcode, inputs.toArray(new LineageItem[0]), specialValueBits);\n}\nprotected static void parseLineageTraceDedup(String str) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/TestUtils.java", "new_path": "src/test/java/org/apache/sysds/test/TestUtils.java", "diff": "@@ -1021,6 +1021,10 @@ public class TestUtils\nassertEquals(expected, actual);\n}\n+ public static void compareScalars(Boolean expected, Boolean actual) {\n+ assertEquals(expected, actual);\n+ }\n+\npublic static boolean compareMatrices(HashMap<CellIndex, Double> m1, HashMap<CellIndex, Double> m2,\ndouble tolerance, String name1, String name2)\n{\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/lineage/LineageDebuggerTest.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.apache.sysds.test.functions.lineage;\n+\n+import org.apache.sysds.hops.OptimizerUtils;\n+import org.apache.sysds.hops.recompile.Recompiler;\n+import org.apache.sysds.runtime.lineage.Lineage;\n+import org.apache.sysds.runtime.lineage.LineageDebugger;\n+import org.apache.sysds.runtime.lineage.LineageItem;\n+import org.apache.sysds.runtime.lineage.LineageParser;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.apache.sysds.utils.Explain;\n+import org.junit.Test;\n+\n+import java.util.ArrayList;\n+import java.util.List;\n+\n+public class LineageDebuggerTest extends LineageBase {\n+\n+ protected static final String TEST_DIR = \"functions/lineage/\";\n+ protected static final String TEST_NAME1 = \"LineageDebugger1\";\n+ protected String TEST_CLASS_DIR = TEST_DIR + LineageDebuggerTest.class.getSimpleName() + \"/\";\n+\n+ protected static final int numRecords = 10;\n+ protected static final int numFeatures = 5;\n+\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 testLineageDebuggerNaN() {\n+ testLineageDebuggerNaN(TEST_NAME1);\n+ }\n+\n+ @Test\n+ public void testLineageDebuggerInf1() {\n+ testLineageDebuggerInf(TEST_NAME1, true, false);\n+ }\n+\n+ @Test\n+ public void testLineageDebuggerInf2() { testLineageDebuggerInf(TEST_NAME1, false, true); }\n+\n+ @Test\n+ public void testLineageDebuggerInf3() { testLineageDebuggerInf(TEST_NAME1, true, true); }\n+\n+ @Test\n+ public void testLineageDebuggerFirstOccurrence1() { testLineageDebuggerFirstOccurrence(TEST_NAME1); }\n+\n+ public void testLineageDebuggerNaN(String testname) {\n+ boolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ boolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n+\n+ try {\n+ LOG.debug(\"------------ BEGIN \" + testname + \"------------\");\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = false;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = false;\n+\n+ int rows = numRecords;\n+ int cols = numFeatures;\n+\n+ getAndLoadTestConfiguration(testname);\n+\n+ List<String> proArgs = new ArrayList<>();\n+\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(\"debugger\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(input(\"X\"));\n+ proArgs.add(input(\"Y\"));\n+ proArgs.add(output(\"Z\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ fullDMLScriptName = getScript();\n+\n+ double[][] X = getRandomMatrix(rows, cols, 0, 1, 0.8, -1);\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+\n+ double[][] Y = getRandomMatrix(rows, cols, 0, 1, 0.8, -1);\n+ Y[3][3] = Double.NaN;\n+ writeInputMatrixWithMTD(\"Y\", Y, true);\n+\n+ Lineage.resetInternalState();\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ String Z_lineage = readDMLLineageFromHDFS(\"Z\");\n+ LineageItem Z_li = LineageParser.parseLineageTrace(Z_lineage);\n+ TestUtils.compareScalars(Z_lineage, Explain.explain(Z_li));\n+\n+ TestUtils.compareScalars(true, Z_li.getSpecialValueBit(LineageDebugger.POS_NAN));\n+ TestUtils.compareScalars(false, Z_li.getSpecialValueBit(LineageDebugger.POS_NEGATIVE_INFINITY));\n+ TestUtils.compareScalars(false, Z_li.getSpecialValueBit(LineageDebugger.POS_POSITIVE_INFINITY));\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+ public void testLineageDebuggerInf(String testname, boolean positive, boolean negative) {\n+ boolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ boolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n+\n+ try {\n+ LOG.debug(\"------------ BEGIN \" + testname + \"------------\");\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = false;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = false;\n+\n+ int rows = numRecords;\n+ int cols = numFeatures;\n+\n+ getAndLoadTestConfiguration(testname);\n+\n+ List<String> proArgs = new ArrayList<>();\n+\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(\"debugger\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(input(\"X\"));\n+ proArgs.add(input(\"Y\"));\n+ proArgs.add(output(\"Z\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ fullDMLScriptName = getScript();\n+\n+ double[][] X = getRandomMatrix(rows, cols, 0, 1, 0.8, -1);\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+\n+ double[][] Y = getRandomMatrix(rows, cols, 0, 1, 0.8, -1);\n+ if (positive)\n+ Y[2][2] = Double.POSITIVE_INFINITY;\n+ if (negative)\n+ Y[3][3] = Double.NEGATIVE_INFINITY;\n+ writeInputMatrixWithMTD(\"Y\", Y, true);\n+\n+ Lineage.resetInternalState();\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ String Z_lineage = readDMLLineageFromHDFS(\"Z\");\n+ LineageItem Z_li = LineageParser.parseLineageTrace(Z_lineage);\n+ TestUtils.compareScalars(Z_lineage, Explain.explain(Z_li));\n+\n+ if (positive)\n+ TestUtils.compareScalars(true, Z_li.getSpecialValueBit(LineageDebugger.POS_POSITIVE_INFINITY));\n+ if (negative)\n+ TestUtils.compareScalars(true, Z_li.getSpecialValueBit(LineageDebugger.POS_NEGATIVE_INFINITY));\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+ public void testLineageDebuggerFirstOccurrence(String testname) {\n+ boolean old_simplification = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ boolean old_sum_product = OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES;\n+\n+ try {\n+ LOG.debug(\"------------ BEGIN \" + testname + \"------------\");\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = false;\n+ OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES = false;\n+\n+ int rows = numRecords;\n+ int cols = numFeatures;\n+\n+ getAndLoadTestConfiguration(testname);\n+\n+ List<String> proArgs = new ArrayList<>();\n+\n+ proArgs.add(\"-stats\");\n+ proArgs.add(\"-lineage\");\n+ proArgs.add(\"debugger\");\n+ proArgs.add(\"-args\");\n+ proArgs.add(input(\"X\"));\n+ proArgs.add(input(\"Y\"));\n+ proArgs.add(output(\"Z\"));\n+ programArgs = proArgs.toArray(new String[proArgs.size()]);\n+\n+ fullDMLScriptName = getScript();\n+\n+ double[][] X = getRandomMatrix(rows, cols, 0, 1, 0.8, -1);\n+\n+ writeInputMatrixWithMTD(\"X\", X, true);\n+\n+ double[][] Y = getRandomMatrix(rows, cols, 0, 1, 0.8, -1);\n+ Y[3][3] = Double.NaN;\n+ writeInputMatrixWithMTD(\"Y\", Y, true);\n+\n+ Lineage.resetInternalState();\n+ runTest(true, EXCEPTION_NOT_EXPECTED, null, -1);\n+\n+ String Z_lineage = readDMLLineageFromHDFS(\"Z\");\n+ LineageItem Z_li = LineageParser.parseLineageTrace(Z_lineage);\n+ TestUtils.compareScalars(Z_lineage, Explain.explain(Z_li));\n+\n+ LineageItem firstOccurrence = LineageDebugger.firstOccurrenceOfNR(Z_li, LineageDebugger.POS_NAN);\n+ TestUtils.compareScalars(true, firstOccurrence.getSpecialValueBit(LineageDebugger.POS_NAN));\n+ for (LineageItem li : firstOccurrence.getInputs())\n+ TestUtils.compareScalars(false, li.getSpecialValueBit(LineageDebugger.POS_NAN));\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/LineageDebugger1.dml", "diff": "+#-------------------------------------------------------------\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+# How to invoke this dml script LineageTrace.dml?\n+# Assume LR_HOME is set to the home of the dml script\n+# Assume rows = 20 and cols = 20 for X\n+# hadoop jar SystemDS.jar -f $LR_HOME/LineageTrace.dml -args \"$INPUT_DIR/X\" \"$OUTPUT_DIR/X\" \"$OUTPUT_DIR/Y\"\n+\n+X = read($1);\n+Y = read($2);\n+\n+X = X + 3;\n+X = X * 5;\n+\n+X = X * Y;\n+\n+Z = t(X) %*% X;\n+\n+# write(X, $3, format=\"text\");\n+# write(Y, $4, format=\"text\");\n+write(Z, $3, format=\"text\");\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2889] Add initial lineage based debugger This patch adds a lineage based debugger which helps tracking the first operator responsible for a constraint violation. Currently, the supported constraints are NAN, positive infinity and negative infinity. AMLS project SS2021. Closes #1286.
49,738
02.06.2021 22:19:48
-7,200
28742bc397887c5ab9c9a8f3193c311ebd4b9e39
[MINOR] Fix robustness and cleanup lmPredict, more gridSearch tests
[ { "change_type": "MODIFY", "old_path": "scripts/builtin/lmPredict.dml", "new_path": "scripts/builtin/lmPredict.dml", "diff": "@@ -23,8 +23,8 @@ m_lmPredict = function(Matrix[Double] X, Matrix[Double] B,\nMatrix[Double] ytest, Integer icpt = 0, Boolean verbose = FALSE)\nreturn (Matrix[Double] yhat)\n{\n- intercept = ifelse(icpt==0, matrix(0,1,ncol(B)), B[nrow(B),]);\n- yhat = X %*% B[1:ncol(X)] + matrix(1,nrow(X),1) %*% intercept;\n+ intercept = ifelse(icpt>0 | ncol(X)+1==nrow(B), as.scalar(B[nrow(B),]), 0);\n+ yhat = X %*% B[1:ncol(X),] + intercept;\nif( verbose ) {\ny_residual = ytest - yhat;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/cocode/CoCodeCostTSMM.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/cocode/CoCodeCostTSMM.java", "diff": "@@ -149,7 +149,7 @@ public class CoCodeCostTSMM extends AColumnCoCoder {\nreturn cost;\n}\n- private double getCostOfSelfTSMM(CompressedSizeInfoColGroup g) {\n+ private static double getCostOfSelfTSMM(CompressedSizeInfoColGroup g) {\ndouble cost = 0;\nfinal int nCol = g.getColumns().length;\ncost += g.getNumVals() * (nCol * (nCol + 1)) / 2;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/BitmapLossyEncoder.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/BitmapLossyEncoder.java", "diff": "@@ -89,6 +89,7 @@ public class BitmapLossyEncoder {\n* @param numRows The number of Rows.\n* @return a lossy bitmap.\n*/\n+ @SuppressWarnings(\"unused\")\nprivate static BitmapLossy make8BitLossy(Bitmap ubm, Stats stats, int numRows) {\nfinal double[] fp = ubm.getValues();\nint numCols = ubm.getNumColumns();\n@@ -284,6 +285,7 @@ public class BitmapLossyEncoder {\n}\n}\n+ @SuppressWarnings(\"unused\")\nprivate static double[] getMemLocalDoubleArray(int length, boolean clean) {\ndouble[] ar = memPoolDoubleArray.get();\nif(ar != null && ar.length >= length) {\n@@ -312,6 +314,7 @@ public class BitmapLossyEncoder {\nprotected double maxDelta;\nprotected boolean sameDelta;\n+ @SuppressWarnings(\"unused\")\npublic Stats(double[] fp) {\nmax = Double.NEGATIVE_INFINITY;\nmin = Double.POSITIVE_INFINITY;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibRightMultBy.java", "new_path": "src/main/java/org/apache/sysds/runtime/compress/lib/CLALibRightMultBy.java", "diff": "@@ -149,7 +149,7 @@ public class CLALibRightMultBy {\n}\nprivate static ColGroupEmpty findEmptyColumnsAndMakeEmptyColGroup(List<AColGroup> colGroups, int nCols, int nRows) {\n- Set<Integer> emptyColumns = new HashSet<Integer>(nCols);\n+ Set<Integer> emptyColumns = new HashSet<>(nCols);\nfor(int i = 0; i < nCols; i++)\nemptyColumns.add(i);\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinGridSearchTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/builtin/BuiltinGridSearchTest.java", "diff": "@@ -23,16 +23,16 @@ import org.junit.Assert;\nimport org.junit.Test;\nimport org.apache.sysds.common.Types.ExecMode;\n-import org.apache.sysds.common.Types.ExecType;\nimport org.apache.sysds.test.AutomatedTestBase;\nimport org.apache.sysds.test.TestConfiguration;\nimport org.apache.sysds.test.TestUtils;\n-\n+import org.apache.sysds.utils.Statistics;\npublic class BuiltinGridSearchTest extends AutomatedTestBase\n{\nprivate final static String TEST_NAME1 = \"GridSearchLM\";\nprivate final static String TEST_NAME2 = \"GridSearchMLogreg\";\n+ private final static String TEST_NAME3 = \"GridSearchLM2\";\nprivate final static String TEST_DIR = \"functions/builtin/\";\nprivate final static String TEST_CLASS_DIR = TEST_DIR + BuiltinGridSearchTest.class.getSimpleName() + \"/\";\n@@ -43,24 +43,45 @@ public class BuiltinGridSearchTest extends AutomatedTestBase\npublic void setUp() {\naddTestConfiguration(TEST_NAME1,new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1,new String[]{\"R\"}));\naddTestConfiguration(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\npublic void testGridSearchLmCP() {\n- runGridSearch(TEST_NAME1, ExecType.CP);\n+ runGridSearch(TEST_NAME1, ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ public void testGridSearchLmHybrid() {\n+ runGridSearch(TEST_NAME1, ExecMode.HYBRID);\n}\n@Test\npublic void testGridSearchLmSpark() {\n- runGridSearch(TEST_NAME1, ExecType.SPARK);\n+ runGridSearch(TEST_NAME1, ExecMode.SPARK);\n}\n@Test\npublic void testGridSearchMLogregCP() {\n- runGridSearch(TEST_NAME2, ExecType.CP);\n+ runGridSearch(TEST_NAME2, ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ public void testGridSearchMLogregHybrid() {\n+ runGridSearch(TEST_NAME2, ExecMode.HYBRID);\n+ }\n+\n+ @Test\n+ public void testGridSearchLm2CP() {\n+ runGridSearch(TEST_NAME3, ExecMode.SINGLE_NODE);\n+ }\n+\n+ @Test\n+ public void testGridSearchLm2Hybrid() {\n+ runGridSearch(TEST_NAME3, ExecMode.HYBRID);\n}\n- private void runGridSearch(String testname, ExecType et)\n+ private void runGridSearch(String testname, ExecMode et)\n{\nExecMode modeOld = setExecMode(et);\ntry {\n@@ -78,6 +99,8 @@ public class BuiltinGridSearchTest extends AutomatedTestBase\n//expected loss smaller than default invocation\nAssert.assertTrue(TestUtils.readDMLBoolean(output(\"R\")));\n+ if( et != ExecMode.SPARK )\n+ Assert.assertEquals(0, Statistics.getNoOfExecutedSPInst());\n}\nfinally {\nresetExecMode(modeOld);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/builtin/GridSearchLM2.dml", "diff": "+#-------------------------------------------------------------\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+l2norm = function(Matrix[Double] X, Matrix[Double] y, Matrix[Double] B)\n+ return (Matrix[Double] loss)\n+{\n+ yhat = lmPredict(X=X, B=B, ytest=y)\n+ loss = as.matrix(sum((y - yhat)^2));\n+}\n+\n+X = read($1);\n+y = read($2);\n+\n+N = 200;\n+Xtrain = X[1:N,];\n+ytrain = y[1:N,];\n+Xtest = X[(N+1):nrow(X),];\n+ytest = y[(N+1):nrow(X),];\n+\n+params = list(\"icpt\",\"reg\", \"tol\", \"maxi\");\n+paramRanges = list(seq(0,1,2),10^seq(0,-4), 10^seq(-6,-12), 10^seq(1,3));\n+[B1, opt] = gridSearch(X=Xtrain, y=ytrain, train=\"lm\", predict=\"l2norm\",\n+ numB=ncol(X)+1, params=params, paramValues=paramRanges);\n+B2 = lm(X=Xtrain, y=ytrain, verbose=FALSE);\n+\n+l1 = l2norm(Xtest, ytest, B1);\n+l2 = l2norm(Xtest, ytest, B2);\n+R = as.scalar(l1 < l2);\n+\n+write(R, $3)\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix robustness and cleanup lmPredict, more gridSearch tests
49,713
07.05.2021 22:14:03
-7,200
bfc58f15aec8d65ab01e8488678c6eb9838f19d1
Python Multi Return Continuation This commit adds support for python multi return continuation. It give the ability to continue processing variables that are returned from a function call that return more than one variable.
[ { "change_type": "MODIFY", "old_path": "src/main/python/systemds/context/systemds_context.py", "new_path": "src/main/python/systemds/context/systemds_context.py", "diff": "@@ -38,7 +38,7 @@ import numpy as np\nimport pandas as pd\nfrom py4j.java_gateway import GatewayParameters, JavaGateway\nfrom py4j.protocol import Py4JNetworkError\n-from systemds.operator import Frame, Matrix, OperationNode, Scalar, Source\n+from systemds.operator import Frame, Matrix, OperationNode, Scalar, Source, List\nfrom systemds.script_building import OutputType\nfrom systemds.utils.consts import VALID_INPUT_TYPES\nfrom systemds.utils.helpers import get_module_dir\n@@ -458,3 +458,17 @@ class SystemDSContext(object):\n:param print_imported_methods: boolean specifying if the imported methods should be printed.\n\"\"\"\nreturn Source(self, path, name, print_imported_methods)\n+\n+ def list(self, *args: Sequence[VALID_INPUT_TYPES], **kwargs: Dict[str, VALID_INPUT_TYPES]) -> 'List':\n+ if len(kwargs) != 0 and len(args) != 0:\n+ raise Exception(\"Accepts either args or kwargs\")\n+ elif len(kwargs) != 0:\n+ out = []\n+ for key, arg in kwargs.items():\n+ out.append((key, OutputType.from_type(arg)))\n+ return List(self, 'list', named_input_nodes=kwargs, outputs=out)\n+ elif len(args) != 0:\n+ out = []\n+ for idx, arg in enumerate(args):\n+ out.append((f\"_{idx}\", OutputType.from_type(arg)))\n+ return List(self, 'list', unnamed_input_nodes=args, outputs=out)\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/__init__.py", "new_path": "src/main/python/systemds/operator/__init__.py", "diff": "@@ -24,6 +24,7 @@ from systemds.operator.nodes.scalar import Scalar\nfrom systemds.operator.nodes.matrix import Matrix\nfrom systemds.operator.nodes.frame import Frame\nfrom systemds.operator.nodes.source import Source\n+from systemds.operator.nodes.list import List\nfrom systemds.operator import algorithm\n-__all__ = [OperationNode, algorithm, Scalar, Matrix, Frame, Source]\n+__all__ = [OperationNode, algorithm, Scalar, List, Matrix, Frame, Source]\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/python/systemds/operator/nodes/list.py", "diff": "+# -------------------------------------------------------------\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+__all__ = [\"List\"]\n+\n+from typing import Dict, Sequence, Tuple, Union, Iterable, List\n+\n+import numpy as np\n+from py4j.java_gateway import JavaObject\n+\n+from systemds.operator import OperationNode, Matrix\n+from systemds.script_building.dag import OutputType\n+from systemds.utils.consts import VALID_INPUT_TYPES\n+from systemds.utils.converters import numpy_to_matrix_block\n+from systemds.utils.helpers import create_params_string\n+\n+\n+class List(OperationNode):\n+\n+ def __init__(self, sds_context: 'SystemDSContext', operation: str,\n+ unnamed_input_nodes: Union[str, Iterable[VALID_INPUT_TYPES]] = None,\n+ named_input_nodes: Dict[str, VALID_INPUT_TYPES] = None,\n+ outputs: List[Tuple[str, OutputType]] = [(\"_1\", OutputType.MATRIX)]):\n+\n+ is_python_local_data = False\n+ self._outputs = outputs\n+ self._named_output_nodes = {}\n+ for idx, output in enumerate(outputs):\n+ if output[1] == OutputType.MATRIX:\n+ self.named_output_nodes[output[0]] = Matrix(sds_context, operation='list', named_input_nodes={f\"_{idx}\": self})\n+ # TODO add output types\n+\n+ super().__init__(sds_context, operation, unnamed_input_nodes,\n+ named_input_nodes, OutputType.LIST, is_python_local_data)\n+\n+ def __getitem__(self, key):\n+ if isinstance(key, int):\n+ return self.named_output_nodes[self._outputs[key][0]]\n+ return self.named_output_nodes[key]\n+\n+ def pass_python_data_to_prepared_script(self, sds, var_name: str, prepared_script: JavaObject) -> None:\n+ assert self.is_python_local_data, 'Can only pass data to prepared script if it is python local!'\n+ if self._is_numpy():\n+ prepared_script.setMatrix(var_name, numpy_to_matrix_block(\n+ sds, self._np_array), True) # True for reuse\n+\n+ def __parse_output_result_list(self, result_variables):\n+ result_var = []\n+ named_output_nodes_types_list = [type(named_output_node).__name__ for named_output_node in list(self.named_output_nodes.values())]\n+ for idx, v in enumerate(self._script.out_var_name):\n+ if named_output_nodes_types_list[idx] == \"Matrix\":\n+ result_var.append(self.__parse_output_result_matrix(result_variables, v))\n+ elif named_output_nodes_types_list[idx] == \"Frame\":\n+ result_var.append(self.__parse_output_result_frame(result_variables, v))\n+ else:\n+ result_var.append(result_variables.getDouble(self._script.out_var_name[idx]))\n+ return result_var\n+\n+ def code_line(self, var_name: str, unnamed_input_vars: Sequence[str],\n+ named_input_vars: Dict[str, str]) -> str:\n+\n+ inputs_comma_sep = create_params_string(unnamed_input_vars, named_input_vars)\n+ output = \"[\"\n+ for idx, output_node in enumerate(self.named_output_nodes):\n+ output += f'{var_name}_{idx},'\n+ output = output[:-1] + \"]\"\n+ return f'{output}={self.operation}({inputs_comma_sep});'\n+\n+ def compute(self, verbose: bool = False, lineage: bool = False) -> Union[np.array]:\n+ return super().compute(verbose, lineage)\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/operator/operation_node.py", "new_path": "src/main/python/systemds/operator/operation_node.py", "diff": "@@ -50,9 +50,7 @@ class OperationNode(DAGNode):\nIterable[VALID_INPUT_TYPES]] = None,\nnamed_input_nodes: Dict[str, VALID_INPUT_TYPES] = None,\noutput_type: OutputType = OutputType.MATRIX,\n- is_python_local_data: bool = False,\n- number_of_outputs=1,\n- output_types: Iterable[OutputType] = None):\n+ is_python_local_data: bool = False):\n\"\"\"\nCreate general `OperationNode`\n@@ -81,10 +79,9 @@ class OperationNode(DAGNode):\nself._result_var = None\nself._lineage_trace = None\nself._script = None\n- self._number_of_outputs = number_of_outputs\n- self._output_types = output_types\nself._source_node = None\nself._already_added = False\n+ self.dml_name = \"\"\ndef compute(self, verbose: bool = False, lineage: bool = False) -> \\\nUnion[float, np.array, Tuple[Union[float, np.array], str]]:\n@@ -138,21 +135,6 @@ class OperationNode(DAGNode):\nself.sds_context, result_variables.getFrameBlock(var_name)\n)\n- def __parse_output_result_list(self, result_variables):\n- result_var = []\n- for idx, v in enumerate(self._script.out_var_name):\n- if(self._output_types == None or self._output_types[idx] == OutputType.MATRIX):\n- result_var.append(\n- self.__parse_output_result_matrix(result_variables, v))\n- elif self._output_types[idx] == OutputType.FRAME:\n- result_var.append(\n- self.__parse_output_result_frame(result_variables, v))\n-\n- else:\n- result_var.append(result_variables.getDouble(\n- self._script.out_var_name[idx]))\n- return result_var\n-\ndef get_lineage_trace(self) -> str:\n\"\"\"Get the lineage trace for this node.\n@@ -174,16 +156,9 @@ class OperationNode(DAGNode):\nunnamed_input_vars) == 2, 'Binary Operations need exactly two input variables'\nreturn f'{var_name}={unnamed_input_vars[0]}{self.operation}{unnamed_input_vars[1]}'\n- inputs_comma_sep = create_params_string(\n- unnamed_input_vars, named_input_vars)\n+ inputs_comma_sep = create_params_string(unnamed_input_vars, named_input_vars)\n- if self.output_type == OutputType.LIST:\n- output = \"[\"\n- for idx in range(self._number_of_outputs):\n- output += f'{var_name}_{idx},'\n- output = output[:-1] + \"]\"\n- return f'{output}={self.operation}({inputs_comma_sep});'\n- elif self.output_type == OutputType.NONE:\n+ if self.output_type == OutputType.NONE:\nreturn f'{self.operation}({inputs_comma_sep});'\n# elif self.output_type == OutputType.ASSIGN:\n# return f'{var_name}={self.operation};'\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/systemds/script_building/dag.py", "new_path": "src/main/python/systemds/script_building/dag.py", "diff": "@@ -24,6 +24,8 @@ from enum import Enum, auto\nfrom typing import TYPE_CHECKING, Any, Dict, Sequence, Union, Optional\nfrom py4j.java_gateway import JavaObject, JVMView\n+\n+import systemds.operator\nfrom systemds.utils.consts import VALID_INPUT_TYPES\nif TYPE_CHECKING:\n@@ -68,18 +70,37 @@ class OutputType(Enum):\nreturn OutputType.NONE\n+ @staticmethod\n+ def from_type(obj):\n+ if obj is not None:\n+ if isinstance(obj, systemds.operator.Matrix):\n+ return OutputType.MATRIX\n+ elif isinstance(obj, systemds.operator.Frame):\n+ return OutputType.FRAME\n+ elif isinstance(obj, systemds.operator.Scalar):\n+ return OutputType.SCALAR\n+ elif isinstance(obj, float): # TODO is this correct?\n+ return OutputType.DOUBLE\n+ elif isinstance(obj, str):\n+ return OutputType.STRING\n+ elif isinstance(obj, systemds.operator.List):\n+ return OutputType.LIST\n+\n+ return OutputType.NONE\n+\nclass DAGNode(ABC):\n\"\"\"A Node in the directed-acyclic-graph (DAG) defining all operations.\"\"\"\nsds_context: 'SystemDSContext'\n_unnamed_input_nodes: Sequence[Union['DAGNode', str, int, float, bool]]\n_named_input_nodes: Dict[str, Union['DAGNode', str, int, float, bool]]\n+ _named_output_nodes: Dict[str, Union['DAGNode', str, int, float, bool]]\n_source_node: Optional[\"DAGNode\"]\n_output_type: OutputType\n_script: Optional[\"DMLScript\"]\n_is_python_local_data: bool\n- _number_of_outputs: int\n_already_added: bool\n+ _dml_name: str\ndef compute(self, verbose: bool = False, lineage: bool = False) -> Any:\n\"\"\"Get result of this operation. Builds the dml script and executes it in SystemDS, before this method is called\n@@ -126,12 +147,12 @@ class DAGNode(ABC):\nreturn self._named_input_nodes\n@property\n- def is_python_local_data(self):\n- return self._is_python_local_data\n+ def named_output_nodes(self):\n+ return self._named_output_nodes\n@property\n- def number_of_outputs(self):\n- return self._number_of_outputs\n+ def is_python_local_data(self):\n+ return self._is_python_local_data\n@property\ndef output_type(self):\n@@ -148,3 +169,11 @@ class DAGNode(ABC):\n@property\ndef script_str(self):\nreturn self._script.dml_script\n+\n+ @property\n+ def dml_name(self):\n+ return self._dml_name\n+\n+ @dml_name.setter\n+ def dml_name(self, value):\n+ self._dml_name = value\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": "@@ -158,10 +158,10 @@ class DMLScript:\n:param dag_root: the topmost operation of our DAG, result of operation will be output\n\"\"\"\nbaseOutVarString = self._dfs_dag_nodes(dag_root)\n- if(dag_root.output_type != OutputType.NONE):\n- if(dag_root.number_of_outputs > 1):\n+ if dag_root.output_type != OutputType.NONE:\n+ if dag_root.output_type == OutputType.LIST:\nself.out_var_name = []\n- for idx in range(dag_root.number_of_outputs):\n+ for idx, output_node in enumerate(dag_root.named_output_nodes):\nself.add_code(\nf'write({baseOutVarString}_{idx}, \\'./tmp_{idx}\\');')\nself.out_var_name.append(f'{baseOutVarString}_{idx}')\n@@ -179,31 +179,37 @@ class DMLScript:\nif isinstance(dag_node, bool):\nreturn 'TRUE' if dag_node else 'FALSE'\nreturn str(dag_node)\n+\n+ if dag_node.dml_name != \"\":\n+ return dag_node.dml_name\n+\nif dag_node._output_type == OutputType.IMPORT:\nif not dag_node.already_added:\nself.add_code(dag_node.code_line(None, None))\nreturn None\n+\nif dag_node._source_node is not None:\nself._dfs_dag_nodes(dag_node._source_node)\n# for each node do the dfs operation and save the variable names in `input_var_names`\n# get variable names of unnamed parameters\n- unnamed_input_vars = [self._dfs_dag_nodes(\n- input_node) for input_node in dag_node.unnamed_input_nodes]\n+ unnamed_input_vars = [self._dfs_dag_nodes(input_node) for input_node in dag_node.unnamed_input_nodes]\n- # get variable names of named parameters\n- named_input_vars = {name: self._dfs_dag_nodes(input_node) for name, input_node in\n- dag_node.named_input_nodes.items()}\n+ named_input_vars = {}\n+ for name, input_node in dag_node.named_input_nodes.items():\n+ named_input_vars[name] = self._dfs_dag_nodes(input_node)\n+ if isinstance(input_node, DAGNode) and input_node._output_type == OutputType.LIST:\n+ dag_node.dml_name = named_input_vars[name] + name\n+ return dag_node.dml_name\n- curr_var_name = self._next_unique_var()\n+ dag_node.dml_name = self._next_unique_var()\nif dag_node.is_python_local_data:\n- self.add_input_from_python(curr_var_name, dag_node)\n+ self.add_input_from_python(dag_node.dml_name, dag_node)\n- code_line = dag_node.code_line(\n- curr_var_name, unnamed_input_vars, named_input_vars)\n+ code_line = dag_node.code_line(dag_node.dml_name, unnamed_input_vars, named_input_vars)\nself.add_code(code_line)\n- return curr_var_name\n+ return dag_node.dml_name\ndef _next_unique_var(self) -> str:\n\"\"\"Gets the next unique variable name\n" }, { "change_type": "MODIFY", "old_path": "src/main/python/tests/algorithms/test_pca.py", "new_path": "src/main/python/tests/algorithms/test_pca.py", "diff": "@@ -25,6 +25,9 @@ import numpy as np\nfrom systemds.context import SystemDSContext\nfrom systemds.operator.algorithm import pca\n+from systemds.operator import List\n+from systemds.script_building.dag import OutputType\n+\nclass TestPCA(unittest.TestCase):\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/python/tests/list/test_operations.py", "diff": "+# -------------------------------------------------------------\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+import unittest\n+\n+import numpy as np\n+from systemds.context import SystemDSContext\n+from systemds.operator.algorithm import pca\n+\n+from systemds.operator import List\n+from systemds.script_building.dag import OutputType\n+\n+\n+class TestListOperations(unittest.TestCase):\n+\n+ sds: SystemDSContext = None\n+\n+ @classmethod\n+ def setUpClass(cls):\n+ cls.sds = SystemDSContext()\n+\n+ @classmethod\n+ def tearDownClass(cls):\n+ cls.sds.close()\n+\n+ def test_creation(self):\n+ \"\"\"\n+ Tests the creation of a List object via the SystemDSContext\n+ \"\"\"\n+ m1 = self.sds.from_numpy(np.array([1, 2, 3]))\n+ m2 = self.sds.from_numpy(np.array([4, 5, 6]))\n+ list_obj = self.sds.list(m1, m2)\n+ tmp = list_obj[0] + list_obj[1]\n+ res = tmp.compute()\n+ self.assertTrue(np.allclose(m2, res))\n+\n+ def test_addition(self):\n+ \"\"\"\n+ Tests the creation of a List object via the SystemDSContext and adds a value\n+ \"\"\"\n+ m1 = self.sds.from_numpy(np.array([1, 2, 3]))\n+ m2 = self.sds.from_numpy(np.array([4, 5, 6]))\n+ list_obj = self.sds.list(m1, m2)\n+ tmp = list_obj[0] + 2\n+ res = tmp.compute()\n+ self.assertTrue(np.allclose(m2 + 2, res))\n+\n+ def test_500x2b(self):\n+ \"\"\"\n+ The purpose of this test is to show that an operation can be performed on the output of a multi output list node,\n+ without the need of calculating the result first.\n+ \"\"\"\n+ m1 = self.generate_matrices_for_pca(30, seed=1304)\n+ node0 = self.sds.from_numpy(m1)\n+ # print(features)\n+ node1 = List(node0.sds_context, 'pca', named_input_nodes={\"X\": node0, \"K\": 1, \"scale\": \"FALSE\", \"center\": \"FALSE\"},\n+ outputs=[(\"res\", OutputType.MATRIX), (\"model\", OutputType.MATRIX), (\"scale\", OutputType.MATRIX), (\"center\", OutputType.MATRIX)])\n+ node2 = node1[\"res\"].abs()\n+ res = node2.compute(verbose=False)\n+\n+ def test_multiple_outputs(self):\n+ \"\"\"\n+ The purpose of this test is to show that we can use multiple outputs\n+ of a single list node in the DAG in one script\n+ \"\"\"\n+ node0 = self.sds.from_numpy(np.array([1, 2, 3, 4, 5, 6, 7, 8, 9]))\n+ node1 = self.sds.from_numpy(np.array([10, 20, 30, 40, 50, 60, 70, 80, 90]))\n+ params_dict = {'X': node0, 'Y': node1}\n+ node2 = List(self.sds, 'split', named_input_nodes=params_dict,\n+ outputs=[(\"X_train\", OutputType.MATRIX), (\"X_test\", OutputType.MATRIX), (\"Y_train\", OutputType.MATRIX), (\"Y_test\", OutputType.MATRIX)])\n+ node3 = node2[\"X_train\"] + node2[\"Y_train\"]\n+ # X_train and Y_train are of the same shape because node0 and node1 have both only one dimension.\n+ # Therefore they can be added together\n+ res = node3.compute(verbose=False)\n+\n+ def generate_matrices_for_pca(self, dims: int, seed: int = 1234):\n+ np.random.seed(seed)\n+\n+ mu, sigma = 0, 0.1\n+ s = np.random.normal(mu, sigma, dims)\n+\n+ m1 = np.array(np.c_[np.copy(s) * 1, np.copy(s)*0.3], dtype=np.double)\n+\n+ return m1\n+\n+\n+if __name__ == \"__main__\":\n+ unittest.main(exit=False)\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2828] Python Multi Return Continuation This commit adds support for python multi return continuation. It give the ability to continue processing variables that are returned from a function call that return more than one variable.
49,706
03.06.2021 15:56:56
-7,200
8970977d0349f26ca81150e52dd9e3a70ea4d3be
Python Tests Printing Fail Fix We have some unstable tests in the python api where the std out from systemds is captured in subsequent tests, rather than the tests intended. To fix this we simply add a small wait before probing the std out.
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/python/tests/script/__init__.py", "diff": "+# -------------------------------------------------------------\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" }, { "change_type": "RENAME", "old_path": "src/main/python/tests/test_dml_script.py", "new_path": "src/main/python/tests/script/test_dml_script.py", "diff": "# -------------------------------------------------------------\nimport unittest\n+import time\nfrom systemds.context import SystemDSContext\nfrom systemds.script_building import DMLScript\n@@ -43,6 +44,7 @@ class Test_DMLScript(unittest.TestCase):\nscript = DMLScript(self.sds)\nscript.add_code('print(\"Hello\")')\nscript.execute()\n+ time.sleep(0.5)\nstdout = self.sds.get_stdout(100)\nself.assertListEqual([\"Hello\"], stdout)\n@@ -52,6 +54,7 @@ class Test_DMLScript(unittest.TestCase):\nscript.add_code('print(\"World\")')\nscript.add_code('print(\"!\")')\nscript.execute()\n+ time.sleep(0.5)\nstdout = self.sds.get_stdout(100)\nself.assertListEqual(['Hello', 'World', '!'], stdout)\n@@ -59,14 +62,11 @@ class Test_DMLScript(unittest.TestCase):\nscr_a = DMLScript(self.sds)\nscr_a.add_code('x = 4')\nscr_a.add_code('print(x)')\n- # TODO FIX HERE TO ENABLE MULTI EXECUTION\n- # scr_a.execute()\nscr_a.add_code('y = x + 1')\nscr_a.add_code('print(y)')\n- # print(scr_a.dml_script)\nscr_a.execute()\n+ time.sleep(0.5)\nstdout = self.sds.get_stdout(100)\n- # print(stdout)\nself.assertEqual(\"4\", stdout[0])\nself.assertEqual(\"5\", stdout[1])\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-3008] Python Tests Printing Fail Fix We have some unstable tests in the python api where the std out from systemds is captured in subsequent tests, rather than the tests intended. To fix this we simply add a small wait before probing the std out.
49,738
05.06.2021 01:21:20
-7,200
64a38eb6710dbbbca999db2333095de2ecc69e3a
Fix remaining issues consistent blocksize handling
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/CacheableData.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/CacheableData.java", "diff": "@@ -826,7 +826,7 @@ public abstract class CacheableData<T extends CacheBlock> extends Data\nboolean eqScheme = IOUtilFunctions.isSameFileScheme(\nnew Path(_hdfsFileName), new Path(fName));\nboolean eqFormat = isEqualOutputFormat(outputFormat);\n- boolean eqBlksize = outputFormat.equals(\"binary\")\n+ boolean eqBlksize = (outputFormat == null || outputFormat.equals(\"binary\"))\n&& ConfigurationManager.getBlocksize() != getBlocksize();\n//actual export (note: no direct transfer of local copy in order to ensure blocking (and hence, parallelism))\n@@ -841,16 +841,15 @@ public abstract class CacheableData<T extends CacheBlock> extends Data\n{\n//read data from HDFS if required (never read before), this applies only to pWrite w/ different output formats\n//note: for large rdd outputs, we compile dedicated writespinstructions (no need to handle this here)\n- try\n- {\n+ try {\nif( getRDDHandle()==null || getRDDHandle().allowsShortCircuitRead() )\n_data = readBlobFromHDFS( _hdfsFileName );\nelse if( getRDDHandle() != null )\n_data = readBlobFromRDD( getRDDHandle(), new MutableBoolean() );\nelse if(!federatedWrite)\n_data = readBlobFromFederated( getFedMapping() );\n-\nsetDirty(false);\n+ refreshMetaData(); //e.g., after unknown csv read\n}\ncatch (IOException e) {\nthrow new DMLRuntimeException(\"Reading of \" + _hdfsFileName + \" (\"+hashCode()+\") failed.\", e);\n@@ -858,7 +857,6 @@ public abstract class CacheableData<T extends CacheBlock> extends Data\n}\n//get object from cache\nif(!federatedWrite) {\n-\nif( _data == null )\ngetCache();\nacquire( false, _data==null ); //incl. read matrix if evicted\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/MatrixObject.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/MatrixObject.java", "diff": "@@ -509,7 +509,8 @@ public class MatrixObject extends CacheableData<MatrixBlock>\n//obtain matrix block from RDD\nint rlen = (int)mc.getRows();\nint clen = (int)mc.getCols();\n- int blen = mc.getBlocksize();\n+ int blen = mc.getBlocksize() > 0 ? mc.getBlocksize() :\n+ ConfigurationManager.getBlocksize();\nlong nnz = mc.getNonZerosBound();\n//guarded rdd collect\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysds/test/functions/transform/TransformCSVFrameEncodeReadTest.java", "new_path": "src/test/java/org/apache/sysds/test/functions/transform/TransformCSVFrameEncodeReadTest.java", "diff": "@@ -126,6 +126,7 @@ public class TransformCSVFrameEncodeReadTest extends AutomatedTestBase\ntry\n{\ngetAndLoadTestConfiguration(TEST_NAME1);\n+ setOutputBuffering(true);\nString HOME = SCRIPT_DIR + TEST_DIR;\nint nrows = subset ? 4 : 13;\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-2981] Fix remaining issues consistent blocksize handling
49,722
05.06.2021 15:40:05
-7,200
e9ba92b36a8776b12aff95abb294fc7b6054d914
Additional federated MSVM algorithm tests Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/CacheableData.java", "new_path": "src/main/java/org/apache/sysds/runtime/controlprogram/caching/CacheableData.java", "diff": "@@ -1033,7 +1033,8 @@ public abstract class CacheableData<T extends CacheBlock> extends Data\n// Federated read\nprotected T readBlobFromFederated(FederationMap fedMap) throws IOException {\n- LOG.info(\"Pulling data from federated sites\");\n+ if( LOG.isDebugEnabled() ) //common if instructions keep federated outputs\n+ LOG.debug(\"Pulling data from federated sites\");\nMetaDataFormat iimd = (MetaDataFormat) _metaData;\nDataCharacteristics dc = iimd.getDataCharacteristics();\nreturn readBlobFromFederated(fedMap, dc.getDims());\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysds/test/functions/federated/algorithms/FederatedMSVMTest.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.apache.sysds.test.functions.federated.algorithms;\n+\n+import java.util.Arrays;\n+import java.util.Collection;\n+\n+import org.apache.sysds.api.DMLScript;\n+import org.apache.sysds.common.Types;\n+import org.apache.sysds.runtime.meta.MatrixCharacteristics;\n+import org.apache.sysds.test.AutomatedTestBase;\n+import org.apache.sysds.test.TestConfiguration;\n+import org.apache.sysds.test.TestUtils;\n+import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Parameterized;\n+\n+@RunWith(value = Parameterized.class)\[email protected]\n+public class FederatedMSVMTest extends AutomatedTestBase {\n+\n+ private final static String TEST_DIR = \"functions/federated/\";\n+ private final static String TEST_NAME = \"FederatedMSVMTest\";\n+ private final static String TEST_CLASS_DIR = TEST_DIR + FederatedMSVMTest.class.getSimpleName() + \"/\";\n+\n+ private final static int blocksize = 1024;\n+ @Parameterized.Parameter()\n+ public int rows;\n+ @Parameterized.Parameter(1)\n+ public int cols;\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] {\"Z\"}));\n+ }\n+\n+ @Parameterized.Parameters\n+ public static Collection<Object[]> data() {\n+ // rows have to be even and > 1\n+ return Arrays.asList(new Object[][] {\n+ // {2, 1000}, {10, 100}, {100, 10}, {1000, 1}, {10, 2000},\n+ {2000, 10}});\n+ }\n+\n+ @Test\n+ public void federatedMSVM2CP() {\n+ federatedMSVM(Types.ExecMode.SINGLE_NODE, false);\n+ }\n+\n+ @Test\n+ public void federatedMSVM1CP() {\n+ federatedMSVM(Types.ExecMode.SINGLE_NODE, true);\n+ }\n+\n+ public void federatedMSVM(Types.ExecMode execMode, boolean singleWorker) {\n+ boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\n+ Types.ExecMode platformOld = rtplatform;\n+ rtplatform = execMode;\n+ if(rtplatform == Types.ExecMode.SPARK) {\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+ }\n+\n+ getAndLoadTestConfiguration(TEST_NAME);\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+\n+ // write input matrices\n+ int halfRows = rows / 2;\n+ // We have two matrices handled by a single federated worker\n+ double[][] X1 = getRandomMatrix(halfRows, cols, 0, 1, 1, 42);\n+ double[][] X2 = getRandomMatrix(halfRows, cols, 0, 1, 1, 1340);\n+ double[][] Y = getRandomMatrix(rows, 1, 0, 10, 1, 3);\n+ Y = TestUtils.round(Y);\n+\n+ writeInputMatrixWithMTD(\"X1\", X1, false, new MatrixCharacteristics(halfRows, cols, blocksize, halfRows * cols));\n+ writeInputMatrixWithMTD(\"X2\", X2, false, new MatrixCharacteristics(halfRows, cols, blocksize, halfRows * cols));\n+ writeInputMatrixWithMTD(\"Y\", Y, false, new MatrixCharacteristics(rows, 1, blocksize, rows));\n+\n+ // empty script name because we don't execute any script, just start the worker\n+ fullDMLScriptName = \"\";\n+ int port1 = getRandomAvailablePort();\n+ int port2 = getRandomAvailablePort();\n+ Thread t1 = startLocalFedWorkerThread(port1, FED_WORKER_WAIT_S);\n+ Thread t2 = startLocalFedWorkerThread(port2);\n+\n+ TestConfiguration config = availableTestConfigurations.get(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ // Run reference dml script with normal matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \"Reference.dml\";\n+ programArgs = new String[] {\"-args\", input(\"X1\"), input(\"X2\"), input(\"Y\"),\n+ String.valueOf(singleWorker).toUpperCase(), expected(\"Z\")};\n+ runTest(true, false, null, -1);\n+\n+ // Run actual dml script with federated matrix\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[] {\"-stats\", \"30\", \"-nvargs\", \"in_X1=\" + TestUtils.federatedAddress(port1, input(\"X1\")),\n+ \"in_X2=\" + TestUtils.federatedAddress(port2, input(\"X2\")), \"rows=\" + rows, \"cols=\" + cols,\n+ \"in_Y=\" + input(\"Y\"), \"single=\" + String.valueOf(singleWorker).toUpperCase(), \"out=\" + output(\"Z\")};\n+ runTest(true, false, null, -1);\n+\n+ // compare via files\n+ compareResults(1e-9);\n+\n+ TestUtils.shutdownThreads(t1, t2);\n+\n+ rtplatform = platformOld;\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedMSVMTest.dml", "diff": "+#-------------------------------------------------------------\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+Y = read($in_Y)\n+\n+if( $single ) {\n+ X = federated(addresses=list($in_X1), ranges=list(list(0, 0), list($rows/2, $cols)))\n+ Y = Y[1:nrow(X),]\n+}\n+else {\n+ X = federated(addresses=list($in_X1, $in_X2),\n+ ranges=list(list(0, 0), list($rows / 2, $cols), list($rows / 2, 0), list($rows, $cols)))\n+}\n+\n+model = msvm(X=X, Y=Y, intercept = FALSE, epsilon = 1e-12, lambda = 1, maxIterations = 100, verbose = FALSE)\n+\n+write(model, $out)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/federated/FederatedMSVMTestReference.dml", "diff": "+#-------------------------------------------------------------\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+Y = read($3)\n+if( $4 ) {\n+ X = read($1)\n+ Y = Y[1:nrow(X),]\n+}\n+else\n+ X = rbind(read($1), read($2))\n+\n+model = msvm(X=X, Y=Y, intercept = FALSE, epsilon = 1e-12, lambda = 1, maxIterations = 100, verbose = FALSE)\n+\n+write(model, $5)\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMDS-3009] Additional federated MSVM algorithm tests Closes #1294.