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,736
31.01.2018 16:49:41
28,800
f69047ea48fe5eb4c7269b49c3e6d1aef7f6967d
Update algorithm selection logic on GPU for conv2d_backward_data
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixCuDNNConvolutionAlgorithm.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixCuDNNConvolutionAlgorithm.java", "diff": "@@ -217,29 +217,32 @@ public class LibMatrixCuDNNConvolutionAlgorithm implements java.lang.AutoCloseab\npublic static LibMatrixCuDNNConvolutionAlgorithm cudnnGetConvolutionBackwardDataAlgorithm(\nGPUContext gCtx, String instName, int N, int C, int H, int W, int K, int R, int S,\nint pad_h, int pad_w, int stride_h, int stride_w, int P, int Q, long workspaceLimit) throws DMLRuntimeException {\n- //long t1 = DMLScript.FINEGRAINED_STATISTICS ? System.nanoTime() : 0;\nLibMatrixCuDNNConvolutionAlgorithm ret = new LibMatrixCuDNNConvolutionAlgorithm(gCtx, instName, N, C, H, W, K, R, S,\npad_h, pad_w, stride_h, stride_w, P, Q);\n-\n+ if(H == R || W == S) {\n// CuDNN's cudnnGetConvolutionBackwardDataAlgorithm returns CUDNN_CONVOLUTION_BWD_DATA_ALGO_1 for atleast one scenario\n// for sentence CNN (N=1, C=1, H=2060, W=300, F=500, Hf=5, Wf=300, sparsity=0.1).\n// This causes more than 100x slowdown when compared with CUDNN_CONVOLUTION_BWD_DATA_ALGO_0.\n- // To keep things simple for now, we will always prefer to use memory-less operator: CUDNN_CONVOLUTION_BWD_DATA_ALGO_0\n+ // To keep things simple for now, we will always prefer to use memory-less operator for conv1d: CUDNN_CONVOLUTION_BWD_DATA_ALGO_0\nret.algo = jcuda.jcudnn.cudnnConvolutionBwdDataAlgo.CUDNN_CONVOLUTION_BWD_DATA_ALGO_0;\n-// int[] algos = {-1};\n-// long sizeInBytesArray[] = {Math.min(workspaceLimit, MAX_WORKSPACE_LIMIT_BYTES)};\n-// jcuda.jcudnn.JCudnn.cudnnGetConvolutionBackwardDataAlgorithm(\n-// LibMatrixCuDNN.getCudnnHandle(gCtx),\n-// ret.filterDesc, ret.nkpqTensorDesc, ret.convDesc, ret.nchwTensorDesc,\n-// cudnnConvolutionBwdDataPreference.CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT, sizeInBytesArray[0], algos);\n-// jcuda.jcudnn.JCudnn.cudnnGetConvolutionBackwardDataWorkspaceSize(LibMatrixCuDNN.getCudnnHandle(gCtx),\n-// ret.filterDesc, ret.nkpqTensorDesc, ret.convDesc, ret.nchwTensorDesc, algos[0], sizeInBytesArray);\n-// if (sizeInBytesArray[0] != 0)\n-// ret.workSpace = gCtx.allocate(sizeInBytesArray[0]);\n-// ret.sizeInBytes = sizeInBytesArray[0];\n-// ret.algo = algos[0];\n-// if (DMLScript.FINEGRAINED_STATISTICS)\n-// GPUStatistics.maintainCPMiscTimes(instName, GPUInstruction.MISC_TIMER_CUDNN_INIT, System.nanoTime() - t1);\n+ }\n+ else {\n+ long t1 = DMLScript.FINEGRAINED_STATISTICS ? System.nanoTime() : 0;\n+ int[] algos = {-1};\n+ long sizeInBytesArray[] = {Math.min(workspaceLimit, MAX_WORKSPACE_LIMIT_BYTES)};\n+ jcuda.jcudnn.JCudnn.cudnnGetConvolutionBackwardDataAlgorithm(\n+ LibMatrixCuDNN.getCudnnHandle(gCtx),\n+ ret.filterDesc, ret.nkpqTensorDesc, ret.convDesc, ret.nchwTensorDesc,\n+ jcuda.jcudnn.cudnnConvolutionBwdDataPreference.CUDNN_CONVOLUTION_BWD_DATA_SPECIFY_WORKSPACE_LIMIT, sizeInBytesArray[0], algos);\n+ jcuda.jcudnn.JCudnn.cudnnGetConvolutionBackwardDataWorkspaceSize(LibMatrixCuDNN.getCudnnHandle(gCtx),\n+ ret.filterDesc, ret.nkpqTensorDesc, ret.convDesc, ret.nchwTensorDesc, algos[0], sizeInBytesArray);\n+ if (sizeInBytesArray[0] != 0)\n+ ret.workSpace = gCtx.allocate(sizeInBytesArray[0]);\n+ ret.sizeInBytes = sizeInBytesArray[0];\n+ ret.algo = algos[0];\n+ if (DMLScript.FINEGRAINED_STATISTICS)\n+ GPUStatistics.maintainCPMiscTimes(instName, GPUInstruction.MISC_TIMER_CUDNN_INIT, System.nanoTime() - t1);\n+ }\nreturn ret;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-445] Update algorithm selection logic on GPU for conv2d_backward_data
49,736
31.01.2018 21:38:29
28,800
5da8132ea8c165d6d1a65c2c293fc87aaa15a2a3
Guard JCudaKernels with sysml.gpu.sync.postProcess flag
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/gpu/context/JCudaKernels.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/gpu/context/JCudaKernels.java", "diff": "@@ -27,6 +27,7 @@ import java.io.IOException;\nimport java.io.InputStream;\nimport java.util.HashMap;\n+import org.apache.sysml.api.DMLScript;\nimport org.apache.sysml.runtime.DMLRuntimeException;\nimport org.apache.sysml.runtime.io.IOUtilFunctions;\nimport org.apache.sysml.runtime.matrix.data.LibMatrixCUDA;\n@@ -110,6 +111,7 @@ public class JCudaKernels {\ncheckResult(cuLaunchKernel(function, config.gridDimX, config.gridDimY, config.gridDimZ, config.blockDimX,\nconfig.blockDimY, config.blockDimZ, config.sharedMemBytes, config.stream, Pointer.to(kernelParams),\nnull));\n+ if(DMLScript.SYNCHRONIZE_GPU)\nJCuda.cudaDeviceSynchronize();\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-445] Guard JCudaKernels with sysml.gpu.sync.postProcess flag
49,736
01.02.2018 14:40:34
28,800
ad5275932e9d74fc4c980757c1ef8e94b6ea04e1
Disable ternary aggregate rewrite on GPU backend This issue will be revisited when we add tack+ and tak+ kernels.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/AggUnaryOp.java", "new_path": "src/main/java/org/apache/sysml/hops/AggUnaryOp.java", "diff": "@@ -551,6 +551,10 @@ public class AggUnaryOp extends Hop implements MultiThreadedHop\n{\nboolean ret = false;\n+ // TODO: Disable ternary aggregate rewrite on GPU backend.\n+ if(DMLScript.USE_ACCELERATOR)\n+ return false;\n+\n//currently we support only sum over binary multiply but potentially\n//it can be generalized to any RC aggregate over two common binary operations\nif( OptimizerUtils.ALLOW_SUM_PRODUCT_REWRITES && _op == AggOp.SUM &&\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-445] Disable ternary aggregate rewrite on GPU backend - This issue will be revisited when we add tack+ and tak+ kernels.
49,736
01.02.2018 16:45:25
28,800
416ebc02a2a7eddfa2d8e0456003cede7af9fa37
Added load_keras_weights flag in Keras2DML to avoid transfering randomly initialized weights By default, load_keras_weights is set to False. Hence, the weights will be transferred to SystemML by default.
[ { "change_type": "MODIFY", "old_path": "src/main/python/systemml/mllearn/estimators.py", "new_path": "src/main/python/systemml/mllearn/estimators.py", "diff": "@@ -896,7 +896,7 @@ class Keras2DML(Caffe2DML):\n\"\"\"\n- def __init__(self, sparkSession, keras_model, input_shape, transferUsingDF=False, weights=None, labels=None, batch_size=64, max_iter=2000, test_iter=10, test_interval=500, display=100, lr_policy=\"step\", weight_decay=5e-4, regularization_type=\"L2\"):\n+ def __init__(self, sparkSession, keras_model, input_shape, transferUsingDF=False, load_keras_weights=True, weights=None, labels=None, batch_size=64, max_iter=2000, test_iter=10, test_interval=500, display=100, lr_policy=\"step\", weight_decay=5e-4, regularization_type=\"L2\"):\n\"\"\"\nPerforms training/prediction for a given keras model.\n@@ -906,6 +906,7 @@ class Keras2DML(Caffe2DML):\nkeras_model: keras model\ninput_shape: 3-element list (number of channels, input height, input width)\ntransferUsingDF: whether to pass the input dataset via PySpark DataFrame (default: False)\n+ load_keras_weights: whether to load weights from the keras_model. If False, the weights will be initialized to random value using NN libraries' init method (default: True)\nweights: directory whether learned weights are stored (default: None)\nlabels: file containing mapping between index and string labels (default: None)\nbatch_size: size of the input batch (default: 64)\n@@ -931,6 +932,7 @@ class Keras2DML(Caffe2DML):\nconvertKerasToCaffeNetwork(keras_model, self.name + \".proto\", int(batch_size))\nconvertKerasToCaffeSolver(keras_model, self.name + \".proto\", self.name + \"_solver.proto\", int(max_iter), int(test_iter), int(test_interval), int(display), lr_policy, weight_decay, regularization_type)\nself.weights = tempfile.mkdtemp() if weights is None else weights\n+ if load_keras_weights:\nconvertKerasToSystemMLModel(sparkSession, keras_model, self.weights)\nif labels is not None and (labels.startswith('https:') or labels.startswith('http:')):\nimport urllib\n@@ -939,6 +941,7 @@ class Keras2DML(Caffe2DML):\nfrom shutil import copyfile\ncopyfile(labels, os.path.join(weights, 'labels.txt'))\nsuper(Keras2DML,self).__init__(sparkSession, self.name + \"_solver.proto\", input_shape, transferUsingDF)\n+ if load_keras_weights:\nself.load(self.weights)\ndef close(self):\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-445] Added load_keras_weights flag in Keras2DML to avoid transfering randomly initialized weights - By default, load_keras_weights is set to False. Hence, the weights will be transferred to SystemML by default.
49,736
02.02.2018 18:30:41
28,800
525381d51a9df8a2613f699cad2538d2ddf1f759
Support single-precision conv2d with MKL Closes
[ { "change_type": "MODIFY", "old_path": "src/main/cpp/CMakeLists.txt", "new_path": "src/main/cpp/CMakeLists.txt", "diff": "@@ -25,7 +25,7 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} \"${CMAKE_SOURCE_DIR}/cmake/\")\n# Options to Use OpenBLAS or Intel MKL\noption(USE_OPEN_BLAS \"Whether to use OpenBLAS (Defaults to compiling with Intel MKL, if both set, MKL has priority)\" OFF)\n-option(USE_INTEL_MKL \"Whether to use Intel MKL (Defaults to compiling with Intel MKL)\" ON)\n+option(USE_INTEL_MKL \"Whether to use Intel MKL (Defaults to compiling with Intel MKL)\" OFF)\n# Build a shared libraray\nadd_library(systemml SHARED libmatrixdnn.cpp libmatrixmult.cpp systemml.cpp)\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/lib/libsystemml_mkl-Linux-x86_64.so", "new_path": "src/main/cpp/lib/libsystemml_mkl-Linux-x86_64.so", "diff": "Binary files a/src/main/cpp/lib/libsystemml_mkl-Linux-x86_64.so and b/src/main/cpp/lib/libsystemml_mkl-Linux-x86_64.so differ\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/lib/libsystemml_openblas-Linux-x86_64.so", "new_path": "src/main/cpp/lib/libsystemml_openblas-Linux-x86_64.so", "diff": "Binary files a/src/main/cpp/lib/libsystemml_openblas-Linux-x86_64.so and b/src/main/cpp/lib/libsystemml_openblas-Linux-x86_64.so differ\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/libmatrixdnn.cpp", "new_path": "src/main/cpp/libmatrixdnn.cpp", "diff": "@@ -480,6 +480,7 @@ int sconv2dBiasAddDense(float* inputPtr, float* biasPtr, float* filterPtr, float\n// Step 3: Destroy the description of the operation\ndnnDelete_F32(pConvolution);\n+ return computeNNZ<float>(retPtr, N*KPQ);\n#else\n// First step: Avoids oversubscription and other openmp/internal blas threading issues\nsetNumThreadsForBLAS(1);\n@@ -515,7 +516,7 @@ int sconv2dBiasAddDense(float* inputPtr, float* biasPtr, float* filterPtr, float\nnnz += computeNNZ<float>(retPtr + n*KPQ, KPQ);\n}\ndelete [] loweredMatArrays;\n+ return nnz;\n#endif\n- return nnz;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/libmatrixmult.cpp", "new_path": "src/main/cpp/libmatrixmult.cpp", "diff": "#include <cstdlib>\n#include \"omp.h\"\n#include <cmath>\n+\n+#ifdef USE_OPEN_BLAS\n#include <cblas.h>\n+#endif\nint SYSML_CURRENT_NUM_THREADS = -1;\nvoid setNumThreadsForBLAS(int numThreads) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/libmatrixmult.h", "new_path": "src/main/cpp/libmatrixmult.h", "diff": "// we call \"extension\" APIs for setting number of threads of the given API.\n// For example: for OpenBLAS we use openblas_set_num_threads and\n// for MKL we use mkl_set_num_threads. This avoids performance degradation due to overprovisioning.\n-#ifdef USE_OPEN_BLAS\n-#include <cblas.h>\n-extern \"C\" void openblas_set_num_threads(int numThreads);\n-#elif defined USE_INTEL_MKL\n+#ifdef USE_INTEL_MKL\n#include <mkl.h>\n#include <mkl_service.h>\n+#else\n+ #include <cblas.h>\n+ extern \"C\" void openblas_set_num_threads(int numThreads);\n#endif\nvoid setNumThreadsForBLAS(int numThreads);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2105] Support single-precision conv2d with MKL Closes #723.
49,738
02.02.2018 20:04:53
28,800
c95019fd99076b4b8b7e6c5cfec85fd9949b2512
New single-precision native matrix multiply This patch extends - similar to native conv2d/con2d_bias_add operations also the native matrix multiply for optional single-precision use. This also includes cleanups of mkl imports and nnz maintenance in double and single-precision conv2d operations. Furthermore, this patch includes build shared libraries for both mkl and openblas.
[ { "change_type": "MODIFY", "old_path": "src/main/cpp/lib/libsystemml_mkl-Linux-x86_64.so", "new_path": "src/main/cpp/lib/libsystemml_mkl-Linux-x86_64.so", "diff": "Binary files a/src/main/cpp/lib/libsystemml_mkl-Linux-x86_64.so and b/src/main/cpp/lib/libsystemml_mkl-Linux-x86_64.so differ\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/lib/libsystemml_openblas-Linux-x86_64.so", "new_path": "src/main/cpp/lib/libsystemml_openblas-Linux-x86_64.so", "diff": "Binary files a/src/main/cpp/lib/libsystemml_openblas-Linux-x86_64.so and b/src/main/cpp/lib/libsystemml_openblas-Linux-x86_64.so differ\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/libmatrixdnn.cpp", "new_path": "src/main/cpp/libmatrixdnn.cpp", "diff": "@@ -406,8 +406,8 @@ int dconv2dBiasAddDense(double* inputPtr, double* biasPtr, double* filterPtr, do\n// Step 3: Destroy the description of the operation\ndnnDelete_F64(pConvolution);\n+ return computeNNZ<double>(retPtr, N*KPQ);\n#else\n- // ------------------------------------------------------------------------------------\n// First step: Avoids oversubscription and other openmp/internal blas threading issues\nsetNumThreadsForBLAS(1);\n@@ -418,8 +418,9 @@ int dconv2dBiasAddDense(double* inputPtr, double* biasPtr, double* filterPtr, do\n// Allocate temporary data structures used in parallel for\nint numOpenMPThreads = MIN(numThreads, N);\ndouble* loweredMatArrays = new double[numIm2ColElem*numOpenMPThreads];\n+ int nnz = 0;\n-#pragma omp parallel for num_threads(numOpenMPThreads)\n+#pragma omp parallel for reduction(+: nnz) num_threads(numOpenMPThreads)\nfor (int n = 0; n < N; n++) {\nint threadID = omp_get_thread_num();\ndouble* loweredMat = loweredMatArrays + numIm2ColElem*threadID;\n@@ -436,12 +437,13 @@ int dconv2dBiasAddDense(double* inputPtr, double* biasPtr, double* filterPtr, do\ndouble* outputArr = retPtr + n*KPQ;\nif( addBias )\nbiasAdd<double>(biasPtr, outputArr, K, PQ);\n- } // end omp parallel for\n+\n+ // Step 4: thread-local nnz maintenance\n+ nnz += computeNNZ<double>(retPtr + n*KPQ, KPQ);\n+ }\ndelete [] loweredMatArrays;\n- // ------------------------------------------------------------------------------------\n+ return nnz;\n#endif\n-\n- return computeNNZ<double>(retPtr, N*KPQ);\n}\nint sconv2dBiasAddDense(float* inputPtr, float* biasPtr, float* filterPtr, float* retPtr,\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/libmatrixmult.cpp", "new_path": "src/main/cpp/libmatrixmult.cpp", "diff": "#ifdef USE_OPEN_BLAS\n#include <cblas.h>\n+#else\n+ #include <mkl_service.h>\n#endif\nint SYSML_CURRENT_NUM_THREADS = -1;\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/libmatrixmult.h", "new_path": "src/main/cpp/libmatrixmult.h", "diff": "//#endif\n// Since we call cblas_dgemm in openmp for loop,\n-// we call \"extension\" APIs for setting number of threads of the given API.\n-// For example: for OpenBLAS we use openblas_set_num_threads and\n-// for MKL we use mkl_set_num_threads. This avoids performance degradation due to overprovisioning.\n+// we call \"extension\" APIs for setting the number of threads.\n#ifdef USE_INTEL_MKL\n#include <mkl.h>\n#include <mkl_service.h>\n+ extern \"C\" void mkl_set_num_threads(int numThreads);\n#else\n#include <cblas.h>\nextern \"C\" void openblas_set_num_threads(int numThreads);\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/systemml.cpp", "new_path": "src/main/cpp/systemml.cpp", "diff": "@@ -75,9 +75,10 @@ JNIEXPORT void JNICALL Java_org_apache_sysml_utils_NativeHelper_setMaxNumThreads\nmaxThreads = (int) jmaxThreads;\n}\n-JNIEXPORT jboolean JNICALL Java_org_apache_sysml_utils_NativeHelper_matrixMultDenseDense(\n+JNIEXPORT jboolean JNICALL Java_org_apache_sysml_utils_NativeHelper_dmmdd(\nJNIEnv* env, jclass cls, jdoubleArray m1, jdoubleArray m2, jdoubleArray ret,\n- jint m1rlen, jint m1clen, jint m2clen, jint numThreads) {\n+ jint m1rlen, jint m1clen, jint m2clen, jint numThreads)\n+{\ndouble* m1Ptr = GET_DOUBLE_ARRAY(env, m1, numThreads);\ndouble* m2Ptr = GET_DOUBLE_ARRAY(env, m2, numThreads);\ndouble* retPtr = GET_DOUBLE_ARRAY(env, ret, numThreads);\n@@ -92,6 +93,21 @@ JNIEXPORT jboolean JNICALL Java_org_apache_sysml_utils_NativeHelper_matrixMultDe\nreturn (jboolean) true;\n}\n+JNIEXPORT jboolean JNICALL Java_org_apache_sysml_utils_NativeHelper_smmdd(\n+ JNIEnv* env, jclass cls, jobject m1, jobject m2, jobject ret,\n+ jint m1rlen, jint m1clen, jint m2clen, jint numThreads)\n+{\n+ float* m1Ptr = (float*) env->GetDirectBufferAddress(m1);\n+ float* m2Ptr = (float*) env->GetDirectBufferAddress(m2);\n+ float* retPtr = (float*) env->GetDirectBufferAddress(ret);\n+ if(m1Ptr == NULL || m2Ptr == NULL || retPtr == NULL)\n+ return (jboolean) false;\n+\n+ smatmult(m1Ptr, m2Ptr, retPtr, (int)m1rlen, (int)m1clen, (int)m2clen, (int)numThreads);\n+\n+ return (jboolean) true;\n+}\n+\nJNIEXPORT jboolean JNICALL Java_org_apache_sysml_utils_NativeHelper_tsmm\n(JNIEnv * env, jclass cls, jdoubleArray m1, jdoubleArray ret, jint m1rlen, jint m1clen, jboolean isLeftTranspose, jint numThreads) {\ndouble* m1Ptr = GET_DOUBLE_ARRAY(env, m1, numThreads);\n" }, { "change_type": "MODIFY", "old_path": "src/main/cpp/systemml.h", "new_path": "src/main/cpp/systemml.h", "diff": "@@ -28,12 +28,18 @@ extern \"C\" {\n#endif\n/*\n* Class: org_apache_sysml_utils_NativeHelper\n- * Method: matrixMultDenseDense\n- * Signature: ([D[D[DIIII)Z\n+ * Method: dmmdd\n*/\n-JNIEXPORT jboolean JNICALL Java_org_apache_sysml_utils_NativeHelper_matrixMultDenseDense\n+JNIEXPORT jboolean JNICALL Java_org_apache_sysml_utils_NativeHelper_dmmdd\n(JNIEnv *, jclass, jdoubleArray, jdoubleArray, jdoubleArray, jint, jint, jint, jint);\n+/*\n+ * Class: org_apache_sysml_utils_NativeHelper\n+ * Method: smmdd\n+ */\n+JNIEXPORT jboolean JNICALL Java_org_apache_sysml_utils_NativeHelper_smmdd\n+ (JNIEnv *, jclass, jobject, jobject, jobject, jint, jint, jint, jint);\n+\n/*\n* Class: org_apache_sysml_utils_NativeHelper\n* Method: tsmm\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixDNNHelper.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixDNNHelper.java", "diff": "@@ -68,7 +68,7 @@ public class LibMatrixDNNHelper\nret.sparse = false;\nif(ret.getDenseBlock() == null)\nret.allocateDenseBlock();\n- NativeHelper.matrixMultDenseDense(m1.getDenseBlockValues(), m2.getDenseBlockValues(),\n+ NativeHelper.dmmdd(m1.getDenseBlockValues(), m2.getDenseBlockValues(),\nret.getDenseBlockValues(), m1.rlen, m1.clen, m2.clen, 1);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixNative.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixNative.java", "diff": "@@ -34,7 +34,10 @@ import org.apache.sysml.utils.Statistics;\npublic class LibMatrixNative\n{\n- /** ThreadLocal reuse of direct buffers for inputs/outputs (extended on demand).*/\n+ // ThreadLocal reuse of direct buffers for inputs/outputs (extended on demand).\n+ // note: since we anyway have to convert from double to float, we use\n+ // preallocated direct buffers (with thread-local reuse and resizing on demand)\n+ // to ensure there are no additional copies created by the transfer over jni\nprivate static ThreadLocal<FloatBuffer> inBuff = new ThreadLocal<FloatBuffer>();\nprivate static ThreadLocal<FloatBuffer> biasBuff = new ThreadLocal<FloatBuffer>();\nprivate static ThreadLocal<FloatBuffer> filterBuff = new ThreadLocal<FloatBuffer>();\n@@ -65,32 +68,45 @@ public class LibMatrixNative\nk = k <= 0 ? NativeHelper.getMaxNumThreads() : k;\n// check inputs / outputs\n- if (m1.isEmptyBlock() || m2.isEmptyBlock()) {\n+ if (m1.isEmptyBlock(false) || m2.isEmptyBlock(false)){\nret.setNonZeros(0);\nif(examSparsity)\nret.examSparsity(); // turn empty dense into sparse\nreturn;\n}\n- if (NativeHelper.isNativeLibraryLoaded() &&\n- !isMatMultMemoryBound(m1.rlen, m1.clen, m2.clen) && !m1.isInSparseFormat() && !m2.isInSparseFormat()) {\n+\n+ if (NativeHelper.isNativeLibraryLoaded()\n+ && !isMatMultMemoryBound(m1.rlen, m1.clen, m2.clen)\n+ && !m1.isInSparseFormat() && !m2.isInSparseFormat())\n+ {\nret.sparse = false;\nret.allocateDenseBlock();\nlong start = DMLScript.STATISTICS ? System.nanoTime() : 0;\n- if (NativeHelper.matrixMultDenseDense(m1.getDenseBlockValues(), m2.getDenseBlockValues(),\n- ret.getDenseBlockValues(), m1.getNumRows(), m1.getNumColumns(), m2.getNumColumns(), k)) {\n+ boolean rccode = false;\n+ if( isSinglePrecision() ) {\n+ FloatBuffer fin1 = toFloatBuffer(m1.getDenseBlockValues(), inBuff, true);\n+ FloatBuffer fin2 = toFloatBuffer(m2.getDenseBlockValues(), filterBuff, true);\n+ FloatBuffer fout = toFloatBuffer(ret.getDenseBlockValues(), outBuff, false);\n+ rccode = NativeHelper.smmdd(fin1, fin2, fout,\n+ m1.getNumRows(), m1.getNumColumns(), m2.getNumColumns(), k);\n+ fromFloatBuffer(outBuff.get(), ret.getDenseBlockValues());\n+ }\n+ else {\n+ rccode = NativeHelper.dmmdd(m1.getDenseBlockValues(), m2.getDenseBlockValues(),\n+ ret.getDenseBlockValues(), m1.getNumRows(), m1.getNumColumns(), m2.getNumColumns(), k);\n+ }\n+ if (rccode) {\nif(DMLScript.STATISTICS) {\nStatistics.nativeLibMatrixMultTime += System.nanoTime() - start;\nStatistics.numNativeLibMatrixMultCalls.increment();\n}\nret.recomputeNonZeros();\n- // post-processing (nnz maintained in parallel)\nif(examSparsity)\nret.examSparsity();\nreturn;\n- } else {\n- // Else fall back to Java\n- Statistics.incrementNativeFailuresCounter();\n}\n+ //else record failure and fallback to java\n+ Statistics.incrementNativeFailuresCounter();\n}\nif (k == 1)\nLibMatrixMult.matrixMult(m1, m2, ret, examSparsity);\n@@ -135,14 +151,9 @@ public class LibMatrixNative\nelse {\nif(params.bias.isInSparseFormat())\nparams.bias.sparseToDense(); // Bias matrix is usually extremely small\n- boolean singlePrecision = ConfigurationManager.getDMLConfig()\n- .getTextValue(DMLConfig.FLOATING_POINT_PRECISION).equals(\"single\");\nlong start = DMLScript.STATISTICS ? System.nanoTime() : 0;\nint nnz = -1;\n- if( singlePrecision ) {\n- //note: since we anyway have to convert from double to float, we use\n- //preallocated direct buffers (with thread-local reuse and resizing on demand)\n- //to ensure there are no additional copies created by the transfer over jni\n+ if( isSinglePrecision() ) {\nFloatBuffer finput = toFloatBuffer(input.getDenseBlockValues(), inBuff, true);\nFloatBuffer fbias = toFloatBuffer(params.bias.getDenseBlockValues(), biasBuff, true);\nFloatBuffer ffilter = toFloatBuffer(filter.getDenseBlockValues(), filterBuff, true);\n@@ -260,6 +271,11 @@ public class LibMatrixNative\nLibMatrixDNN.conv2dBackwardData(filter, dout, outputBlock, params);\n}\n+ private static boolean isSinglePrecision() {\n+ return ConfigurationManager.getDMLConfig()\n+ .getTextValue(DMLConfig.FLOATING_POINT_PRECISION).equals(\"single\");\n+ }\n+\nprivate static FloatBuffer toFloatBuffer(double[] input, ThreadLocal<FloatBuffer> buff, boolean copy) {\n//maintain thread-local buffer (resized on demand)\nFloatBuffer ret = buff.get();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/utils/NativeHelper.java", "new_path": "src/main/java/org/apache/sysml/utils/NativeHelper.java", "diff": "@@ -324,7 +324,12 @@ public class NativeHelper {\n}\n// TODO: Add pmm, wsloss, mmchain, etc.\n- public static native boolean matrixMultDenseDense(double [] m1, double [] m2, double [] ret, int m1rlen, int m1clen, int m2clen, int numThreads);\n+\n+ //double-precision matrix multiply dense-dense\n+ public static native boolean dmmdd(double [] m1, double [] m2, double [] ret, int m1rlen, int m1clen, int m2clen, int numThreads);\n+ //single-precision matrix multiply dense-dense\n+ public static native boolean smmdd(FloatBuffer m1, FloatBuffer m2, FloatBuffer ret, int m1rlen, int m1clen, int m2clen, int numThreads);\n+ //transpose-self matrix multiply\nprivate static native boolean tsmm(double [] m1, double [] ret, int m1rlen, int m1clen, boolean isLeftTranspose, int numThreads);\n// ----------------------------------------------------------------------------------------------------------------\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2106] New single-precision native matrix multiply This patch extends - similar to native conv2d/con2d_bias_add operations - also the native matrix multiply for optional single-precision use. This also includes cleanups of mkl imports and nnz maintenance in double and single-precision conv2d operations. Furthermore, this patch includes build shared libraries for both mkl and openblas.
49,698
04.02.2018 13:53:00
28,800
c3601d419a47f218af1517eaee66383d820ada86
Codegen support for xor operations Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeBinary.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeBinary.java", "diff": "@@ -35,20 +35,22 @@ public class CNodeBinary extends CNode\nVECT_POW_ADD, VECT_MIN_ADD, VECT_MAX_ADD,\nVECT_EQUAL_ADD, VECT_NOTEQUAL_ADD, VECT_LESS_ADD,\nVECT_LESSEQUAL_ADD, VECT_GREATER_ADD, VECT_GREATEREQUAL_ADD,\n- VECT_CBIND_ADD,\n+ VECT_CBIND_ADD, VECT_XOR_ADD,\n//vector-scalar operations\nVECT_MULT_SCALAR, VECT_DIV_SCALAR, VECT_MINUS_SCALAR, VECT_PLUS_SCALAR,\nVECT_POW_SCALAR, VECT_MIN_SCALAR, VECT_MAX_SCALAR,\nVECT_EQUAL_SCALAR, VECT_NOTEQUAL_SCALAR, VECT_LESS_SCALAR,\nVECT_LESSEQUAL_SCALAR, VECT_GREATER_SCALAR, VECT_GREATEREQUAL_SCALAR,\nVECT_CBIND,\n+ VECT_XOR_SCALAR,\n//vector-vector operations\nVECT_MULT, VECT_DIV, VECT_MINUS, VECT_PLUS, VECT_MIN, VECT_MAX, VECT_EQUAL,\nVECT_NOTEQUAL, VECT_LESS, VECT_LESSEQUAL, VECT_GREATER, VECT_GREATEREQUAL,\n+ VECT_XOR,\n//scalar-scalar operations\nMULT, DIV, PLUS, MINUS, MODULUS, INTDIV,\nLESS, LESSEQUAL, GREATER, GREATEREQUAL, EQUAL,NOTEQUAL,\n- MIN, MAX, AND, OR, LOG, LOG_NZ, POW,\n+ MIN, MAX, AND, OR, XOR, LOG, LOG_NZ, POW,\nMINUS1_MULT, MINUS_NZ;\npublic static boolean contains(String value) {\n@@ -88,6 +90,7 @@ public class CNodeBinary extends CNode\ncase VECT_MINUS_ADD:\ncase VECT_PLUS_ADD:\ncase VECT_POW_ADD:\n+ case VECT_XOR_ADD:\ncase VECT_MIN_ADD:\ncase VECT_MAX_ADD:\ncase VECT_EQUAL_ADD:\n@@ -112,6 +115,7 @@ public class CNodeBinary extends CNode\ncase VECT_MINUS_SCALAR:\ncase VECT_PLUS_SCALAR:\ncase VECT_POW_SCALAR:\n+ case VECT_XOR_SCALAR:\ncase VECT_MIN_SCALAR:\ncase VECT_MAX_SCALAR:\ncase VECT_EQUAL_SCALAR:\n@@ -142,6 +146,7 @@ public class CNodeBinary extends CNode\ncase VECT_DIV:\ncase VECT_MINUS:\ncase VECT_PLUS:\n+ case VECT_XOR:\ncase VECT_MIN:\ncase VECT_MAX:\ncase VECT_EQUAL:\n@@ -199,6 +204,8 @@ public class CNodeBinary extends CNode\nreturn \" double %TMP% = 1 - %IN1% * %IN2%;\\n\";\ncase MINUS_NZ:\nreturn \" double %TMP% = (%IN1% != 0) ? %IN1% - %IN2% : 0;\\n\";\n+ case XOR:\n+ return \" double %TMP% = ( (%IN1% != 0) != (%IN2% != 0) ) ? 1 : 0;\\n\";\ndefault:\nthrow new RuntimeException(\"Invalid binary type: \"+this.toString());\n@@ -217,7 +224,8 @@ public class CNodeBinary extends CNode\n|| this == VECT_EQUAL_SCALAR || this == VECT_NOTEQUAL_SCALAR\n|| this == VECT_LESS_SCALAR || this == VECT_LESSEQUAL_SCALAR\n|| this == VECT_GREATER_SCALAR || this == VECT_GREATEREQUAL_SCALAR\n- || this == VECT_CBIND;\n+ || this == VECT_CBIND\n+ || this == VECT_XOR_SCALAR;\n}\npublic boolean isVectorVectorPrimitive() {\nreturn this == VECT_DIV || this == VECT_MULT\n@@ -225,7 +233,8 @@ public class CNodeBinary extends CNode\n|| this == VECT_MIN || this == VECT_MAX\n|| this == VECT_EQUAL || this == VECT_NOTEQUAL\n|| this == VECT_LESS || this == VECT_LESSEQUAL\n- || this == VECT_GREATER || this == VECT_GREATEREQUAL;\n+ || this == VECT_GREATER || this == VECT_GREATEREQUAL\n+ || this == VECT_XOR;\n}\npublic boolean isVectorMatrixPrimitive() {\nreturn this == VECT_MATRIXMULT\n@@ -351,6 +360,7 @@ public class CNodeBinary extends CNode\ncase VECT_DIV_SCALAR: return \"b(vd)\";\ncase VECT_MINUS_SCALAR: return \"b(vmi)\";\ncase VECT_PLUS_SCALAR: return \"b(vp)\";\n+ case VECT_XOR_SCALAR: return \"v(vxor)\";\ncase VECT_POW_SCALAR: return \"b(vpow)\";\ncase VECT_MIN_SCALAR: return \"b(vmin)\";\ncase VECT_MAX_SCALAR: return \"b(vmax)\";\n@@ -364,6 +374,7 @@ public class CNodeBinary extends CNode\ncase VECT_DIV: return \"b(v2d)\";\ncase VECT_MINUS: return \"b(v2mi)\";\ncase VECT_PLUS: return \"b(v2p)\";\n+ case VECT_XOR: return \"b(v2xor)\";\ncase VECT_MIN: return \"b(v2min)\";\ncase VECT_MAX: return \"b(v2max)\";\ncase VECT_EQUAL: return \"b(v2eq)\";\n@@ -388,6 +399,7 @@ public class CNodeBinary extends CNode\ncase NOTEQUAL: return \"b(!=)\";\ncase OR: return \"b(|)\";\ncase AND: return \"b(&)\";\n+ case XOR: return \"b(xor)\";\ncase MINUS1_MULT: return \"b(1-*)\";\ncase MINUS_NZ: return \"b(-nz)\";\ndefault: return \"b(\"+_type.name().toLowerCase()+\")\";\n@@ -413,6 +425,7 @@ public class CNodeBinary extends CNode\ncase VECT_GREATER_ADD:\ncase VECT_GREATEREQUAL_ADD:\ncase VECT_CBIND_ADD:\n+ case VECT_XOR_ADD:\nboolean vectorScalar = _inputs.get(1).getDataType()==DataType.SCALAR;\n_rows = _inputs.get(vectorScalar ? 0 : 1)._rows;\n_cols = _inputs.get(vectorScalar ? 0 : 1)._cols;\n@@ -435,6 +448,7 @@ public class CNodeBinary extends CNode\ncase VECT_MULT_SCALAR:\ncase VECT_MINUS_SCALAR:\ncase VECT_PLUS_SCALAR:\n+ case VECT_XOR_SCALAR:\ncase VECT_POW_SCALAR:\ncase VECT_MIN_SCALAR:\ncase VECT_MAX_SCALAR:\n@@ -449,6 +463,7 @@ public class CNodeBinary extends CNode\ncase VECT_MULT:\ncase VECT_MINUS:\ncase VECT_PLUS:\n+ case VECT_XOR:\ncase VECT_MIN:\ncase VECT_MAX:\ncase VECT_EQUAL:\n@@ -492,6 +507,7 @@ public class CNodeBinary extends CNode\ncase MAX:\ncase AND:\ncase OR:\n+ case XOR:\ncase LOG:\ncase LOG_NZ:\ncase POW:\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateRow.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateRow.java", "diff": "@@ -65,7 +65,7 @@ public class TemplateRow extends TemplateBase\nOpOp1.SIN, OpOp1.COS, OpOp1.TAN, OpOp1.ASIN, OpOp1.ACOS, OpOp1.ATAN, OpOp1.SINH, OpOp1.COSH, OpOp1.TANH,\nOpOp1.CUMSUM, OpOp1.CUMMIN, OpOp1.CUMMAX};\nprivate static final Hop.OpOp2[] SUPPORTED_VECT_BINARY = new OpOp2[]{\n- OpOp2.MULT, OpOp2.DIV, OpOp2.MINUS, OpOp2.PLUS, OpOp2.POW, OpOp2.MIN, OpOp2.MAX,\n+ OpOp2.MULT, OpOp2.DIV, OpOp2.MINUS, OpOp2.PLUS, OpOp2.POW, OpOp2.MIN, OpOp2.MAX, OpOp2.XOR,\nOpOp2.EQUAL, OpOp2.NOTEQUAL, OpOp2.LESS, OpOp2.LESSEQUAL, OpOp2.GREATER, OpOp2.GREATEREQUAL};\npublic TemplateRow() {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "new_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "diff": "@@ -561,6 +561,95 @@ public class LibSpoofPrimitives\nreturn vectPlusWrite(b, a, bix, bi, ai, blen, len);\n}\n+ //custom vector xor\n+ /**\n+ * Computes c = xor(A,B)\n+ *\n+ * @param a dense input vector A\n+ * @param ai start position in A\n+ * @param bval scalar value\n+ * @param c resultant vector\n+ * @param ci index of c\n+ * @param len number of processed elements\n+ * @return resultant value\n+ */\n+ public static void vectXorAdd(double[] a, double bval, double[] c, int ai, int ci, int len) {\n+ for( int j = ai; j < ai+len; j++, ci++)\n+ c[ci] += ( (a[j] != 0) != (bval != 0) ) ? 1 : 0;\n+ }\n+\n+ public static void vectXorAdd(double bval, double[] a, double[] c, int ai, int ci, int len) {\n+ for( int j = ai; j < ai+len; j++, ci++)\n+ c[ci] += ( (bval != 0) != (a[j] != 0) ) ? 1 : 0;\n+ }\n+\n+ public static void vectXorAdd(double[] a, double bval, double[] c, int[] aix, int ai, int ci, int alen, int len) {\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[ci + aix[j]] += ( (a[j] != 0) != (bval != 0) ) ? 1 : 0;\n+ }\n+\n+ public static void vectXorAdd(double bval, double[] a, double[] c, int[] aix, int ai, int ci, int alen, int len) {\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[ci + aix[j]] += ( (bval != 0) != (a[j] != 0) ) ? 1 : 0;\n+ }\n+\n+ //1. scalar vs. dense vector\n+ public static double[] vectXorWrite(double[] a, double bval, int ai, int len) {\n+ double[] c = allocVector(len, false);\n+ for( int j = 0; j < len; j++)\n+ c[j] = ( ( a[ai+j] != 0) != (bval != 0) ) ? 1 : 0;\n+ return c;\n+ }\n+\n+ //2. dense vector vs. scalar\n+ public static double[] vectXorWrite(double bval, double[] a, int ai, int len) {\n+ double[] c = allocVector(len, false);\n+ for( int j = 0; j < len; j++)\n+ c[j] = ( (bval != 0) != (a[ai + j] != 0) ) ? 1 : 0;\n+ return c;\n+ }\n+\n+ //3. dense vector vs. dense vector\n+ public static double[] vectXorWrite(double[] a, double[] b, int ai, int bi, int len) {\n+ double[] c = allocVector(len, false);\n+ for( int j = 0; j < len; j++)\n+ c[j] = ( (a[ai + j] != 0) != (b[bi + j] != 0) ) ? 1 : 0;\n+ return c;\n+ }\n+\n+ //4. sparse vector vs scalar\n+ public static double[] vectXorWrite(double[] a, double bval, int[] aix, int ai, int alen, int len) {\n+ double init = (bval != 0) ? 1 : 0;\n+ double[] c = allocVector(len, true, init);\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[aix[j]] = (a[j] != 0) ? 0 : 1;\n+ return c;\n+ }\n+\n+ //5. scalar vs. sparse vector\n+ public static double[] vectXorWrite(double bval, double[] a, int[] aix, int ai, int alen, int len) {\n+ double init = (bval != 0) ? 1 : 0;\n+ double[] c = allocVector(len, true, init);\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[aix[j]] = (a[j] != 0) ? 0 : 1;\n+ return c;\n+ }\n+\n+ //6. sparse vector vs. dense vector\n+ public static double[] vectXorWrite(double[] a, double[] b, int[] aix, int ai, int bi, int alen, int len) {\n+ double[] c = allocVector(len, false);\n+ for( int j = 0; j < len; j++ )\n+ c[j] = (b[bi+j] != 0) ? 1 : 0;\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[aix[j]] = ( ( a[j] != 0) != (c[aix[j]] != 0) )? 1 : 0;\n+ return c;\n+ }\n+\n+ //6. sparse vector vs. dense vector\n+ public static void vectXorWrite(double[] a, double[] b, int ai, int[] aix, int bi, int alen, int len) {\n+ vectXorWrite(a, b, aix, ai, bi, alen, len);\n+ }\n+\n//custom vector pow\npublic static void vectPowAdd(double[] a, double bval, double[] c, int ai, int ci, int len) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CPlanVectorPrimitivesTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CPlanVectorPrimitivesTest.java", "diff": "@@ -645,6 +645,36 @@ public class CPlanVectorPrimitivesTest extends AutomatedTestBase\ntestVectorBinaryPrimitive(BinType.VECT_GREATEREQUAL, InputType.VECTOR_SPARSE, InputType.VECTOR_DENSE);\n}\n+ @Test\n+ public void testScalarVectorXorDense() {\n+ testVectorBinaryPrimitive(BinType.VECT_XOR_SCALAR, InputType.SCALAR, InputType.VECTOR_DENSE);\n+ }\n+\n+ @Test\n+ public void testVectorScalarXorDense() {\n+ testVectorBinaryPrimitive(BinType.VECT_XOR_SCALAR, InputType.VECTOR_DENSE, InputType.VECTOR_DENSE);\n+ }\n+\n+ @Test\n+ public void testVectorVectorDenseDense() {\n+ testVectorBinaryPrimitive(BinType.VECT_XOR, InputType.VECTOR_DENSE, InputType.VECTOR_DENSE);\n+ }\n+\n+ @Test\n+ public void testVectorScalarSparse() {\n+ testVectorBinaryPrimitive(BinType.VECT_XOR_SCALAR, InputType.VECTOR_SPARSE, InputType.SCALAR);\n+ }\n+\n+ @Test\n+ public void testScalarVectorSparse() {\n+ testVectorBinaryPrimitive(BinType.VECT_XOR_SCALAR, InputType.SCALAR, InputType.VECTOR_SPARSE);\n+ }\n+\n+ @Test\n+ public void testVectorVectorSparseDense() {\n+ testVectorBinaryPrimitive(BinType.VECT_XOR, InputType.VECTOR_SPARSE, InputType.VECTOR_DENSE);\n+ }\n+\n@SuppressWarnings(\"incomplete-switch\")\nprivate static void testVectorAggPrimitive(UnaryType aggtype, InputType type1)\n{\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CellwiseTmplTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CellwiseTmplTest.java", "diff": "@@ -52,6 +52,7 @@ public class CellwiseTmplTest extends AutomatedTestBase\nprivate static final String TEST_NAME14 = TEST_NAME+14; //-2 * X + t(Y); t(Y) is rowvector\nprivate static final String TEST_NAME15 = TEST_NAME+15; //colMins(2*log(X))\nprivate static final String TEST_NAME16 = TEST_NAME+16; //colSums(2*log(X));\n+ private static final String TEST_NAME17 = TEST_NAME+17; //xor operation\nprivate static final String TEST_DIR = \"functions/codegen/\";\n@@ -65,7 +66,7 @@ public class CellwiseTmplTest extends AutomatedTestBase\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n- for( int i=1; i<=16; i++ ) {\n+ for( int i=1; i<=17; i++ ) {\naddTestConfiguration( TEST_NAME+i, new TestConfiguration(\nTEST_CLASS_DIR, TEST_NAME+i, new String[] {String.valueOf(i)}) );\n}\n@@ -288,6 +289,21 @@ public class CellwiseTmplTest extends AutomatedTestBase\ntestCodegenIntegration( TEST_NAME16, true, ExecType.SPARK );\n}\n+ @Test\n+ public void testCodegenCellwiseRewrite17() {\n+ testCodegenIntegration( TEST_NAME17, true, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenCellwise17() {\n+ testCodegenIntegration( TEST_NAME17, false, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenCellwiseRewrite17_sp() {\n+ testCodegenIntegration( TEST_NAME17, true, ExecType.SPARK );\n+ }\n+\nprivate void testCodegenIntegration( String testname, boolean rewrites, ExecType instType )\n{\n@@ -352,6 +368,8 @@ public class CellwiseTmplTest extends AutomatedTestBase\nAssert.assertTrue(!heavyHittersContainsSubString(\"uacmin\"));\nelse if( testname.equals(TEST_NAME16) )\nAssert.assertTrue(!heavyHittersContainsSubString(\"uack+\"));\n+ else if( testname.equals(TEST_NAME17) )\n+ Assert.assertTrue(!heavyHittersContainsSubString(\"xor\"));\n}\nfinally {\nrtplatform = platformOld;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/RowAggTmplTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/RowAggTmplTest.java", "diff": "@@ -72,6 +72,7 @@ public class RowAggTmplTest extends AutomatedTestBase\nprivate static final String TEST_NAME33 = TEST_NAME+\"33\"; //Kmeans, inner loop\nprivate static final String TEST_NAME34 = TEST_NAME+\"34\"; //X / rowSums(X!=0)\nprivate static final String TEST_NAME35 = TEST_NAME+\"35\"; //cbind(X/rowSums(X), Y, Z)\n+ private static final String TEST_NAME36 = TEST_NAME+\"36\"; //xor operation\nprivate static final String TEST_DIR = \"functions/codegen/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + RowAggTmplTest.class.getSimpleName() + \"/\";\n@@ -83,7 +84,7 @@ public class RowAggTmplTest extends AutomatedTestBase\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n- for(int i=1; i<=35; i++)\n+ for(int i=1; i<=36; i++)\naddTestConfiguration( TEST_NAME+i, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME+i, new String[] { String.valueOf(i) }) );\n}\n@@ -612,6 +613,20 @@ public class RowAggTmplTest extends AutomatedTestBase\ntestCodegenIntegration( TEST_NAME35, false, ExecType.SPARK );\n}\n+ @Test\n+ public void testCodegenRowAggRewrite36CP() {\n+ testCodegenIntegration( TEST_NAME36, true, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAgg36CP() {\n+ testCodegenIntegration( TEST_NAME36, false, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAgg36SP() {\n+ testCodegenIntegration( TEST_NAME36, false, ExecType.SPARK );\n+ }\nprivate void testCodegenIntegration( String testname, boolean rewrites, ExecType instType )\n{\n@@ -667,6 +682,8 @@ public class RowAggTmplTest extends AutomatedTestBase\nif( testname.equals(TEST_NAME35) )\nAssert.assertTrue(!heavyHittersContainsSubString(\"spoofRA\", 2)\n&& !heavyHittersContainsSubString(\"cbind\"));\n+ if( testname.equals(TEST_NAME36) )\n+ Assert.assertTrue(!heavyHittersContainsSubString(\"xor\"));\n}\nfinally {\nrtplatform = platformOld;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/cellwisetmpl17.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+options(digits=22)\n+library(\"Matrix\")\n+\n+X = matrix(seq(7, 1100*200+6), 1100, 200, byrow=TRUE);\n+\n+R1 = (X/3) %% 0.6;\n+R2 = (X/3) %/% 0.6;\n+\n+R = xor(R1, R2);\n+\n+writeMM(as(R,\"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/cellwisetmpl17.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 = matrix(seq(7, 1100*200+6), 1100, 200);\n+\n+R1 = (X/3) %% 0.6;\n+R2 = (X/3) %/% 0.6;\n+\n+S = xor(R1, R2);\n+\n+write(S, $1)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/rowAggPattern36.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+options(digits=22)\n+library(\"Matrix\")\n+library(\"matrixStats\")\n+\n+X = matrix(seq(1, 6000)/600, 300, 20);\n+\n+Y = X/rowSums(X)\n+\n+R = xor(X,Y);\n+\n+writeMM(as(R, \"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/rowAggPattern36.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 = matrix(seq(1, 6000)/600, 300, 20);\n+\n+Y = X/rowSums(X)\n+\n+S = xor(X, Y);\n+\n+write(S, $1);\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2068] Codegen support for xor operations Closes #718.
49,738
04.02.2018 23:56:12
28,800
ae98864e5061da0a44aebd703104177bd8a4d9d0
Fix sparse-dense vector xor operations This patch fixes the vector primitive for sparse-dense xor operations which used a wrong signature leading to codegen compilation errors.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "new_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "diff": "@@ -646,8 +646,8 @@ public class LibSpoofPrimitives\n}\n//6. sparse vector vs. dense vector\n- public static void vectXorWrite(double[] a, double[] b, int ai, int[] aix, int bi, int alen, int len) {\n- vectXorWrite(a, b, aix, ai, bi, alen, len);\n+ public static double[] vectXorWrite(double[] a, double[] b, int ai, int[] aix, int bi, int alen, int len) {\n+ return vectXorWrite(a, b, aix, ai, bi, alen, len);\n}\n//custom vector pow\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2068] Fix sparse-dense vector xor operations This patch fixes the vector primitive for sparse-dense xor operations which used a wrong signature leading to codegen compilation errors.
49,698
05.02.2018 01:20:50
28,800
2d57dc576092142a6078c09c07e5f3b97351900b
[MINOR] Fix naming sparse-sparse relu_backward Closed
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixDNNRelu.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixDNNRelu.java", "diff": "@@ -75,7 +75,7 @@ public class LibMatrixDNNRelu\nelse if(m1.isInSparseFormat() && !m2.isInSparseFormat())\nreluBackwardSparseDense(m1.getSparseBlock(), m2.getDenseBlock(), out.getSparseBlock(), _rl, _ru);\nelse //sparse-sparse\n- reluBackwardSparseDense(m1.getSparseBlock(), m2.getSparseBlock(), out.getSparseBlock(), _rl, _ru);\n+ reluBackwardSparseSparse(m1.getSparseBlock(), m2.getSparseBlock(), out.getSparseBlock(), _rl, _ru);\n//thread-local nnz maintenance\nreturn out.recomputeNonZeros(_rl, _ru-1);\n@@ -118,7 +118,7 @@ public class LibMatrixDNNRelu\n}\n}\n- private static void reluBackwardSparseDense(SparseBlock a, SparseBlock b, SparseBlock c, int rl, int ru) {\n+ private static void reluBackwardSparseSparse(SparseBlock a, SparseBlock b, SparseBlock c, int rl, int ru) {\n//b is the driver as it has likely less non-zeros\nfor(int i = rl; i < ru; i++) {\nif( a.isEmpty(i) || b.isEmpty(i) ) continue;\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix naming sparse-sparse relu_backward Closed #725.
49,738
05.02.2018 18:21:51
28,800
94f1b72efa7fe768ca694d894cb6d39130ed43fc
[MINOR] Cleanup codegen candidate exploration (preserve all candidates)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateRow.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateRow.java", "diff": "@@ -33,7 +33,6 @@ import org.apache.sysml.hops.LiteralOp;\nimport org.apache.sysml.hops.ParameterizedBuiltinOp;\nimport org.apache.sysml.hops.TernaryOp;\nimport org.apache.sysml.hops.UnaryOp;\n-import org.apache.sysml.hops.codegen.SpoofCompiler;\nimport org.apache.sysml.hops.codegen.cplan.CNode;\nimport org.apache.sysml.hops.codegen.cplan.CNodeBinary;\nimport org.apache.sysml.hops.codegen.cplan.CNodeBinary.BinType;\n@@ -86,8 +85,7 @@ public class TemplateRow extends TemplateBase\n&& hop.getInput().get(0).getDim1()>1 && hop.getInput().get(0).getDim2()>1)\n|| (hop instanceof AggBinaryOp && hop.dimsKnown() && LibMatrixMult.isSkinnyRightHandSide(\nhop.getInput().get(0).getDim1(), hop.getInput().get(0).getDim2(), //MM\n- hop.getInput().get(1).getDim1(), hop.getInput().get(1).getDim2(),\n- SpoofCompiler.PLAN_SEL_POLICY.isCostBased())\n+ hop.getInput().get(1).getDim1(), hop.getInput().get(1).getDim2(), false)\n&& hop.getInput().get(0).getDim1()>1 && hop.getInput().get(0).getDim2()>1\n&& !HopRewriteUtils.isOuterProductLikeMM(hop))\n|| (HopRewriteUtils.isTransposeOperation(hop) && hop.getParent().size()==1\n@@ -158,9 +156,8 @@ public class TemplateRow extends TemplateBase\n//check for fusable but not opening matrix multiply (vect_outer-mult)\nHop in1 = hop.getInput().get(0); //transpose\nHop in2 = hop.getInput().get(1);\n- boolean inclSizes = SpoofCompiler.PLAN_SEL_POLICY.isCostBased();\n- return LibMatrixMult.isSkinnyRightHandSide(in1.getDim2(), in1.getDim1(), hop.getDim1(), hop.getDim2(), inclSizes)\n- || LibMatrixMult.isSkinnyRightHandSide(in2.getDim1(), in2.getDim2(), hop.getDim2(), hop.getDim1(), inclSizes);\n+ return LibMatrixMult.isSkinnyRightHandSide(in1.getDim2(), in1.getDim1(), hop.getDim1(), hop.getDim2(), false)\n+ || LibMatrixMult.isSkinnyRightHandSide(in2.getDim1(), in2.getDim2(), hop.getDim2(), hop.getDim1(), false);\n}\nprivate static boolean isPartOfValidCumAggChain(Hop hop) {\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Cleanup codegen candidate exploration (preserve all candidates)
49,738
06.02.2018 20:06:28
28,800
aa537dad43f2cf21badaedcb8629b27ad301032b
Codegen support for ternary ifelse in cell/magg tmpls This patch adds basic support for ternary ifelse operations in codegen cell and magg templates along with related tests.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeTernary.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeTernary.java", "diff": "@@ -27,7 +27,7 @@ public class CNodeTernary extends CNode\n{\npublic enum TernaryType {\nPLUS_MULT, MINUS_MULT,\n- REPLACE, REPLACE_NAN,\n+ REPLACE, REPLACE_NAN, IFELSE,\nLOOKUP_RC1, LOOKUP_RVECT1;\n@@ -53,6 +53,9 @@ public class CNodeTernary extends CNode\ncase REPLACE_NAN:\nreturn \" double %TMP% = Double.isNaN(%IN1%) ? %IN3% : %IN1%;\\n\";\n+ case IFELSE:\n+ return \" double %TMP% = (%IN1% != 0) ? %IN2% : %IN3%;\\n\";\n+\ncase LOOKUP_RC1:\nreturn sparse ?\n\" double %TMP% = getValue(%IN1v%, %IN1i%, ai, alen, %IN3%-1);\\n\" :\n@@ -128,11 +131,10 @@ public class CNodeTernary extends CNode\ncase MINUS_MULT: return \"t(-*)\";\ncase REPLACE:\ncase REPLACE_NAN: return \"t(rplc)\";\n+ case IFELSE: return \"t(ifelse)\";\ncase LOOKUP_RC1: return \"u(ixrc1)\";\ncase LOOKUP_RVECT1: return \"u(ixrv1)\";\n-\n- default:\n- return super.toString();\n+ default: return super.toString();\n}\n}\n@@ -143,6 +145,7 @@ public class CNodeTernary extends CNode\ncase MINUS_MULT:\ncase REPLACE:\ncase REPLACE_NAN:\n+ case IFELSE:\ncase LOOKUP_RC1:\n_rows = 0;\n_cols = 0;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateCell.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateCell.java", "diff": "@@ -34,6 +34,7 @@ import org.apache.sysml.hops.Hop;\nimport org.apache.sysml.hops.UnaryOp;\nimport org.apache.sysml.hops.Hop.AggOp;\nimport org.apache.sysml.hops.Hop.OpOp2;\n+import org.apache.sysml.hops.Hop.OpOp3;\nimport org.apache.sysml.hops.Hop.ParamBuiltinOp;\nimport org.apache.sysml.hops.IndexingOp;\nimport org.apache.sysml.hops.LiteralOp;\n@@ -208,6 +209,7 @@ public class TemplateCell extends TemplateBase\n//add lookups if required\ncdata1 = TemplateUtils.wrapLookupIfNecessary(cdata1, hop.getInput().get(0));\n+ cdata2 = TemplateUtils.wrapLookupIfNecessary(cdata2, hop.getInput().get(1));\ncdata3 = TemplateUtils.wrapLookupIfNecessary(cdata3, hop.getInput().get(2));\n//construct ternary cnode, primitive operation derived from OpOp3\n@@ -299,11 +301,11 @@ public class TemplateCell extends TemplateBase\n//prepare indicators for ternary operations\nboolean isTernaryVectorScalarVector = false;\nboolean isTernaryMatrixScalarMatrixDense = false;\n+ boolean isTernaryIfElse = (HopRewriteUtils.isTernary(hop, OpOp3.IFELSE) && hop.getDataType().isMatrix());\nif( hop instanceof TernaryOp && hop.getInput().size()==3 && hop.dimsKnown()\n&& HopRewriteUtils.checkInputDataTypes(hop, DataType.MATRIX, DataType.SCALAR, DataType.MATRIX) ) {\nHop left = hop.getInput().get(0);\nHop right = hop.getInput().get(2);\n-\nisTernaryVectorScalarVector = TemplateUtils.isVector(left) && TemplateUtils.isVector(right);\nisTernaryMatrixScalarMatrixDense = HopRewriteUtils.isEqualSize(left, right)\n&& !HopRewriteUtils.isSparse(left) && !HopRewriteUtils.isSparse(right);\n@@ -312,7 +314,7 @@ public class TemplateCell extends TemplateBase\n//check supported unary, binary, ternary operations\nreturn hop.getDataType() == DataType.MATRIX && TemplateUtils.isOperationSupported(hop) && (hop instanceof UnaryOp\n|| isBinaryMatrixScalar || isBinaryMatrixVector || isBinaryMatrixMatrix\n- || isTernaryVectorScalarVector || isTernaryMatrixScalarMatrixDense\n+ || isTernaryVectorScalarVector || isTernaryMatrixScalarMatrixDense || isTernaryIfElse\n|| (hop instanceof ParameterizedBuiltinOp && ((ParameterizedBuiltinOp)hop).getOp()==ParamBuiltinOp.REPLACE));\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CellwiseTmplTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CellwiseTmplTest.java", "diff": "@@ -53,6 +53,7 @@ public class CellwiseTmplTest extends AutomatedTestBase\nprivate static final String TEST_NAME15 = TEST_NAME+15; //colMins(2*log(X))\nprivate static final String TEST_NAME16 = TEST_NAME+16; //colSums(2*log(X));\nprivate static final String TEST_NAME17 = TEST_NAME+17; //xor operation\n+ private static final String TEST_NAME18 = TEST_NAME+18; //sum(ifelse(X,Y,Z))\nprivate static final String TEST_DIR = \"functions/codegen/\";\n@@ -66,7 +67,7 @@ public class CellwiseTmplTest extends AutomatedTestBase\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n- for( int i=1; i<=17; i++ ) {\n+ for( int i=1; i<=18; i++ ) {\naddTestConfiguration( TEST_NAME+i, new TestConfiguration(\nTEST_CLASS_DIR, TEST_NAME+i, new String[] {String.valueOf(i)}) );\n}\n@@ -304,6 +305,21 @@ public class CellwiseTmplTest extends AutomatedTestBase\ntestCodegenIntegration( TEST_NAME17, true, ExecType.SPARK );\n}\n+ @Test\n+ public void testCodegenCellwiseRewrite18() {\n+ testCodegenIntegration( TEST_NAME18, true, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenCellwise18() {\n+ testCodegenIntegration( TEST_NAME18, false, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenCellwiseRewrite18_sp() {\n+ testCodegenIntegration( TEST_NAME18, true, ExecType.SPARK );\n+ }\n+\nprivate void testCodegenIntegration( String testname, boolean rewrites, ExecType instType )\n{\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/cellwisetmpl18.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+options(digits=22)\n+library(\"Matrix\")\n+\n+X = matrix(seq(-1000, 198999), 1000, 200, byrow=TRUE);\n+Y = matrix(seq(0, 199999), 1000, 200, byrow=TRUE);\n+Z = matrix(seq(1000, 200999), 1000, 200, byrow=TRUE);\n+\n+R = as.matrix(sum(as.numeric(ifelse(X,Y,Z))));\n+\n+writeMM(as(R,\"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/cellwisetmpl18.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 = matrix(seq(-1000, 198999), 1000, 200);\n+Y = matrix(seq(0, 199999), 1000, 200);\n+Z = matrix(seq(1000, 200999), 1000, 200);\n+\n+while(FALSE){}\n+\n+R = as.matrix(sum(ifelse(X,Y,Z)));\n+\n+write(R, $1)\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2082] Codegen support for ternary ifelse in cell/magg tmpls This patch adds basic support for ternary ifelse operations in codegen cell and magg templates along with related tests.
49,736
08.02.2018 15:06:19
28,800
8b054804e64ba48ca87016dbe82a4349489b031d
Bugfix in Caffe2DML/Keras2DML's concat layer for sentence CNN
[ { "change_type": "MODIFY", "old_path": "src/main/python/systemml/mllearn/keras2caffe.py", "new_path": "src/main/python/systemml/mllearn/keras2caffe.py", "diff": "@@ -76,10 +76,8 @@ def _getInboundLayers(layer):\nfor node in inbound_nodes:\nnode_list = node.inbound_layers # get layers pointing to this node\nin_names = in_names + node_list\n- if any('flat' in s.name for s in in_names): # For Caffe2DML to reroute any use of Flatten layers\n- return _getInboundLayers([s for s in in_names if 'flat' in s.name][0])\n- return in_names\n-\n+ # For Caffe2DML to reroute any use of Flatten layers\n+ return list(chain.from_iterable( [ _getInboundLayers(l) if isinstance(l, keras.layers.Flatten) else [ l ] for l in in_names ] ))\ndef _getCompensatedAxis(layer):\ncompensated_axis = layer.axis\n" }, { "change_type": "MODIFY", "old_path": "src/main/scala/org/apache/sysml/api/dl/CaffeLayer.scala", "new_path": "src/main/scala/org/apache/sysml/api/dl/CaffeLayer.scala", "diff": "@@ -439,6 +439,8 @@ class Concat(val param: LayerParameter, val id: Int, val net: CaffeNetwork) exte\n// This is useful because we do not support multi-input cbind and rbind in DML.\ndef _getMultiFn(fn: String): String = {\nif (_childLayers == null) _childLayers = net.getBottomLayers(param.getName).map(l => net.getCaffeLayer(l)).toList\n+ if(_childLayers.length < 2)\n+ throw new DMLRuntimeException(\"Incorrect usage of Concat layer. Expected atleast 2 bottom layers, but found \" + _childLayers.length)\nvar tmp = fn + \"(\" + _childLayers(0).out + \", \" + _childLayers(1).out + \")\"\nfor (i <- 2 until _childLayers.size) {\ntmp = fn + \"(\" + tmp + \", \" + _childLayers(i).out + \")\"\n@@ -492,20 +494,20 @@ class Concat(val param: LayerParameter, val id: Int, val net: CaffeNetwork) exte\nelse \" = \" + dOutVar + \"[,\" + indexString + \" ]; \"\n// concat_start_index = concat_end_index + 1\n- // concat_end_index = concat_start_index + $$ - 1\n+ // concat_end_index = concat_start_index + ## - 1\nval initializeIndexString = \"concat_start_index\" + outSuffix + \" = concat_end_index\" + outSuffix + \" + 1; concat_end_index\" + outSuffix +\n- \" = concat_start_index\" + outSuffix + \" + $$ - 1; \"\n+ \" = concat_start_index\" + outSuffix + \" + ## - 1; \"\nif (param.getConcatParam.getAxis == 0) {\nbottomLayers.map(l => {\ndmlScript\n- .append(initializeIndexString.replaceAll(\"$$\", nrow(l.out)))\n+ .append(initializeIndexString.replaceAll(\"##\", nrow(l.out)))\n// X1 = Z[concat_start_index:concat_end_index,]\n.append(dX(l.id) + outSuffix + doutVarAssignment)\n})\n} else {\nbottomLayers.map(l => {\ndmlScript\n- .append(initializeIndexString.replaceAll(\"$$\", int_mult(l.outputShape._1, l.outputShape._2, l.outputShape._3)))\n+ .append(initializeIndexString.replaceAll(\"##\", int_mult(l.outputShape._1, l.outputShape._2, l.outputShape._3)))\n// X1 = Z[concat_start_index:concat_end_index,]\n.append(dX(l.id) + outSuffix + doutVarAssignment)\n})\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-445] Bugfix in Caffe2DML/Keras2DML's concat layer for sentence CNN
49,738
08.02.2018 19:06:05
28,800
5983e96ee213030b854800016aecfc5018ad45a1
Fix codegen with boolean literal inputs (e.g., ifelse) This patch fixes the code generator to compile valid source code for boolean literal inputs as used in ternary ifelse of binary lgoical operations. Furthermore, this also includes the related tests.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeData.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeData.java", "diff": "@@ -60,6 +60,8 @@ public class CNodeData extends CNode\nreturn \"Double.POSITIVE_INFINITY\";\nelse if( \"-Infinity\".equals(_name) )\nreturn \"Double.NEGATIVE_INFINITY\";\n+ else if( \"true\".equals(_name) || \"false\".equals(_name) )\n+ return \"true\".equals(_name) ? \"1d\" : \"0d\";\nelse\nreturn _name;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateUtils.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateUtils.java", "diff": "@@ -317,7 +317,9 @@ public class TemplateUtils\n&& !TemplateUtils.isUnary(output,\nUnaryType.EXP, UnaryType.LOG, UnaryType.ROW_COUNTNNZS))\n|| (output instanceof CNodeBinary\n- && !TemplateUtils.isBinary(output, BinType.VECT_OUTERMULT_ADD)))\n+ && !TemplateUtils.isBinary(output, BinType.VECT_OUTERMULT_ADD))\n+ || output instanceof CNodeTernary\n+ && ((CNodeTernary)output).getType() == TernaryType.IFELSE)\n&& hasOnlyDataNodeOrLookupInputs(output);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CellwiseTmplTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CellwiseTmplTest.java", "diff": "@@ -54,7 +54,7 @@ public class CellwiseTmplTest extends AutomatedTestBase\nprivate static final String TEST_NAME16 = TEST_NAME+16; //colSums(2*log(X));\nprivate static final String TEST_NAME17 = TEST_NAME+17; //xor operation\nprivate static final String TEST_NAME18 = TEST_NAME+18; //sum(ifelse(X,Y,Z))\n-\n+ private static final String TEST_NAME19 = TEST_NAME+19; //sum(ifelse(true,Y,Z))+sum(ifelse(false,Y,Z))\nprivate static final String TEST_DIR = \"functions/codegen/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + CellwiseTmplTest.class.getSimpleName() + \"/\";\n@@ -67,7 +67,7 @@ public class CellwiseTmplTest extends AutomatedTestBase\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n- for( int i=1; i<=18; i++ ) {\n+ for( int i=1; i<=19; i++ ) {\naddTestConfiguration( TEST_NAME+i, new TestConfiguration(\nTEST_CLASS_DIR, TEST_NAME+i, new String[] {String.valueOf(i)}) );\n}\n@@ -320,6 +320,21 @@ public class CellwiseTmplTest extends AutomatedTestBase\ntestCodegenIntegration( TEST_NAME18, true, ExecType.SPARK );\n}\n+ @Test\n+ public void testCodegenCellwiseRewrite19() {\n+ testCodegenIntegration( TEST_NAME19, true, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenCellwise19() {\n+ testCodegenIntegration( TEST_NAME19, false, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenCellwiseRewrite19_sp() {\n+ testCodegenIntegration( TEST_NAME19, true, ExecType.SPARK );\n+ }\n+\nprivate void testCodegenIntegration( String testname, boolean rewrites, ExecType instType )\n{\n@@ -371,7 +386,8 @@ public class CellwiseTmplTest extends AutomatedTestBase\nTestUtils.compareMatrices(dmlfile, rfile, eps, \"Stat-DML\", \"Stat-R\");\n}\n- if( !(rewrites && testname.equals(TEST_NAME2)) ) //sigmoid\n+ if( !(rewrites && (testname.equals(TEST_NAME2)\n+ || testname.equals(TEST_NAME19))) ) //sigmoid\nAssert.assertTrue(heavyHittersContainsSubString(\n\"spoofCell\", \"sp_spoofCell\", \"spoofMA\", \"sp_spoofMA\"));\nif( testname.equals(TEST_NAME7) ) //ensure matrix mult is fused\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/cellwisetmpl19.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+options(digits=22)\n+library(\"Matrix\")\n+\n+Y = as.numeric(matrix(seq(0, 199999), 1000, 200, byrow=TRUE));\n+Z = as.numeric(matrix(seq(1000, 200999), 1000, 200, byrow=TRUE));\n+R = as.matrix(sum(Y) + sum(Z));\n+\n+writeMM(as(R,\"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/cellwisetmpl19.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 = matrix(seq(0, 199999), 1000, 200);\n+Z = matrix(seq(1000, 200999), 1000, 200);\n+\n+while(FALSE){}\n+\n+R = as.matrix(sum(ifelse(TRUE,Y,Z)) + sum(ifelse(FALSE,Y,Z)));\n+write(R, $1)\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2139] Fix codegen with boolean literal inputs (e.g., ifelse) This patch fixes the code generator to compile valid source code for boolean literal inputs as used in ternary ifelse of binary lgoical operations. Furthermore, this also includes the related tests.
49,738
09.02.2018 13:08:40
28,800
a97a144dcebf7e5233dcd09bd8b9848931359875
[MINOR] Fix long to int truncation of dims in spark reshape operations
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MatrixReshapeSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MatrixReshapeSPInstruction.java", "diff": "@@ -82,8 +82,8 @@ public class MatrixReshapeSPInstruction extends UnarySPInstruction {\nSparkExecutionContext sec = (SparkExecutionContext)ec;\n//get parameters\n- int rows = (int)ec.getScalarInput(_opRows.getName(), _opRows.getValueType(), _opRows.isLiteral()).getLongValue(); //save cast\n- int cols = (int)ec.getScalarInput(_opCols.getName(), _opCols.getValueType(), _opCols.isLiteral()).getLongValue(); //save cast\n+ long rows = ec.getScalarInput(_opRows.getName(), _opRows.getValueType(), _opRows.isLiteral()).getLongValue(); //save cast\n+ long cols = ec.getScalarInput(_opCols.getName(), _opCols.getValueType(), _opCols.isLiteral()).getLongValue(); //save cast\nboolean byRow = ec.getScalarInput(_opByRow.getName(), ValueType.BOOLEAN, _opByRow.isLiteral()).getBooleanValue();\n//get inputs\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix long to int truncation of dims in spark reshape operations
49,738
10.02.2018 13:06:34
28,800
6e932951a8a24cb184c2ba0968c63ab4e96425b8
[HOTFIX] Fix initialization of compressed matrix blocks (dim check)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/compress/CompressedMatrixBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/compress/CompressedMatrixBlock.java", "diff": "@@ -128,7 +128,7 @@ public class CompressedMatrixBlock extends MatrixBlock implements Externalizable\nprotected boolean _sharedDDC1Dict = false;\npublic CompressedMatrixBlock() {\n- super(-1, -1, true);\n+ super(0, 0, true);\n}\n/**\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix initialization of compressed matrix blocks (dim check)
49,738
10.02.2018 13:51:06
28,800
056e48d0cdd984c722797e71f2a4aec041c19690
Disable codegen for config w/ forced gpu operations Until the codegen framework supports the generation of GPU operations, we globally disable code generation in case of forced GPU acceleration.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/conf/ConfigurationManager.java", "new_path": "src/main/java/org/apache/sysml/conf/ConfigurationManager.java", "diff": "package org.apache.sysml.conf;\nimport org.apache.hadoop.mapred.JobConf;\n+import org.apache.sysml.api.DMLScript;\nimport org.apache.sysml.conf.CompilerConfig.ConfigType;\nimport org.apache.sysml.runtime.matrix.mapred.MRConfigurationNames;\nimport org.apache.sysml.runtime.matrix.mapred.MRJobConfiguration;\n@@ -190,11 +191,14 @@ public class ConfigurationManager\n}\npublic static boolean isCodegenEnabled() {\n- return getDMLConfig().getBooleanValue(DMLConfig.CODEGEN)\n- || getCompilerConfigFlag(ConfigType.CODEGEN_ENABLED);\n+ return (getDMLConfig().getBooleanValue(DMLConfig.CODEGEN)\n+ || getCompilerConfigFlag(ConfigType.CODEGEN_ENABLED))\n+ && !DMLScript.USE_ACCELERATOR;\n+ //note: until codegen is supported for the GPU backend, we globally\n+ //disable codegen if operations are forced to the GPU to avoid\n+ //a counter-productive impact on performance.\n}\n-\n///////////////////////////////////////\n// Thread-local classes\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2144] Disable codegen for config w/ forced gpu operations Until the codegen framework supports the generation of GPU operations, we globally disable code generation in case of forced GPU acceleration.
49,738
10.02.2018 18:58:57
28,800
744df8139cbacaa5b65323768c099ae87121af3c
Fix missing sprop/sigmoid codegen support in row templ This patch adds codegen support for sprop (sample proportion) and sigmoid in codegen row templates, which requires sparse and dense vector primitives. So far we only supported scalar sprop and sigmoid in outer, cell and magg templates.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeUnary.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeUnary.java", "diff": "@@ -36,6 +36,7 @@ public class CNodeUnary extends CNode\nVECT_SIN, VECT_COS, VECT_TAN, VECT_ASIN, VECT_ACOS, VECT_ATAN,\nVECT_SINH, VECT_COSH, VECT_TANH,\nVECT_CUMSUM, VECT_CUMMIN, VECT_CUMMAX,\n+ VECT_SPROP, VECT_SIGMOID,\nEXP, POW2, MULT2, SQRT, LOG, LOG_NZ,\nABS, ROUND, CEIL, FLOOR, SIGN,\nSIN, COS, TAN, ASIN, ACOS, ATAN, SINH, COSH, TANH,\n@@ -81,7 +82,9 @@ public class CNodeUnary extends CNode\ncase VECT_TANH:\ncase VECT_CUMSUM:\ncase VECT_CUMMIN:\n- case VECT_CUMMAX:{\n+ case VECT_CUMMAX:\n+ case VECT_SPROP:\n+ case VECT_SIGMOID: {\nString vectName = getVectorPrimitiveName();\nreturn sparse ? \" double[] %TMP% = LibSpoofPrimitives.vect\"+vectName+\"Write(%IN1v%, %IN1i%, %POS1%, alen, len);\\n\" :\n\" double[] %TMP% = LibSpoofPrimitives.vect\"+vectName+\"Write(%IN1%, %POS1%, %LEN%);\\n\";\n@@ -155,8 +158,8 @@ public class CNodeUnary extends CNode\n|| this == VECT_SIN || this == VECT_COS || this == VECT_TAN\n|| this == VECT_ASIN || this == VECT_ACOS || this == VECT_ATAN\n|| this == VECT_SINH || this == VECT_COSH || this == VECT_TANH\n- || this == VECT_CUMSUM || this == VECT_CUMMIN\n- || this == VECT_CUMMAX;\n+ || this == VECT_CUMSUM || this == VECT_CUMMIN || this == VECT_CUMMAX\n+ || this == VECT_SPROP || this == VECT_SIGMOID;\n}\npublic UnaryType getVectorAddPrimitive() {\nreturn UnaryType.valueOf(\"VECT_\"+getVectorPrimitiveName().toUpperCase()+\"_ADD\");\n@@ -267,7 +270,9 @@ public class CNodeUnary extends CNode\ncase VECT_CUMSUM:\ncase VECT_CUMMIN:\ncase VECT_CUMMAX:\n- case VECT_SIGN: return \"u(v\"+_type.name().toLowerCase()+\")\";\n+ case VECT_SIGN:\n+ case VECT_SIGMOID:\n+ case VECT_SPROP:return \"u(v\"+_type.name().toLowerCase()+\")\";\ncase LOOKUP_R: return \"u(ixr)\";\ncase LOOKUP_C: return \"u(ixc)\";\ncase LOOKUP_RC: return \"u(ixrc)\";\n@@ -302,6 +307,8 @@ public class CNodeUnary extends CNode\ncase VECT_CUMSUM:\ncase VECT_CUMMIN:\ncase VECT_CUMMAX:\n+ case VECT_SPROP:\n+ case VECT_SIGMOID:\n_rows = _inputs.get(0)._rows;\n_cols = _inputs.get(0)._cols;\n_dataType= DataType.MATRIX;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateRow.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateRow.java", "diff": "@@ -63,7 +63,7 @@ public class TemplateRow extends TemplateBase\nprivate static final Hop.OpOp1[] SUPPORTED_VECT_UNARY = new OpOp1[]{\nOpOp1.EXP, OpOp1.SQRT, OpOp1.LOG, OpOp1.ABS, OpOp1.ROUND, OpOp1.CEIL, OpOp1.FLOOR, OpOp1.SIGN,\nOpOp1.SIN, OpOp1.COS, OpOp1.TAN, OpOp1.ASIN, OpOp1.ACOS, OpOp1.ATAN, OpOp1.SINH, OpOp1.COSH, OpOp1.TANH,\n- OpOp1.CUMSUM, OpOp1.CUMMIN, OpOp1.CUMMAX};\n+ OpOp1.CUMSUM, OpOp1.CUMMIN, OpOp1.CUMMAX, OpOp1.SPROP, OpOp1.SIGMOID};\nprivate static final Hop.OpOp2[] SUPPORTED_VECT_BINARY = new OpOp2[]{\nOpOp2.MULT, OpOp2.DIV, OpOp2.MINUS, OpOp2.PLUS, OpOp2.POW, OpOp2.MIN, OpOp2.MAX, OpOp2.XOR,\nOpOp2.EQUAL, OpOp2.NOTEQUAL, OpOp2.LESS, OpOp2.LESSEQUAL, OpOp2.GREATER, OpOp2.GREATEREQUAL};\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "new_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "diff": "@@ -1505,6 +1505,58 @@ public class LibSpoofPrimitives\nreturn c;\n}\n+ //custom sprop\n+\n+ public static void vectSpropAdd(double[] a, double[] c, int ai, int ci, int len) {\n+ for( int j = ai; j < ai+len; j++, ci++)\n+ c[ci] += a[j] * (1 - a[j]);\n+ }\n+\n+ public static void vectSpropAdd(double[] a, double[] c, int[] aix, int ai, int ci, int alen, int len) {\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[ci + aix[j]] += a[j] * (1 - a[j]);\n+ }\n+\n+ public static double[] vectSpropWrite(double[] a, int ai, int len) {\n+ double[] c = allocVector(len, false);\n+ for( int j = 0; j < len; j++, ai++)\n+ c[j] = a[j] * (1 - a[j]);\n+ return c;\n+ }\n+\n+ public static double[] vectSpropWrite(double[] a, int[] aix, int ai, int alen, int len) {\n+ double[] c = allocVector(len, true);\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[aix[j]] = a[j] * (1 - a[j]);\n+ return c;\n+ }\n+\n+ //custom sigmoid\n+\n+ public static void vectSigmoidAdd(double[] a, double[] c, int ai, int ci, int len) {\n+ for( int j = ai; j < ai+len; j++, ci++)\n+ c[ci] += 1 / (1 + FastMath.exp(-a[j]));\n+ }\n+\n+ public static void vectSigmoidAdd(double[] a, double[] c, int[] aix, int ai, int ci, int alen, int len) {\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[ci + aix[j]] += 1 / (1 + FastMath.exp(-a[j]));\n+ }\n+\n+ public static double[] vectSigmoidWrite(double[] a, int ai, int len) {\n+ double[] c = allocVector(len, false);\n+ for( int j = 0; j < len; j++, ai++)\n+ c[j] = 1 / (1 + FastMath.exp(-a[j]));\n+ return c;\n+ }\n+\n+ public static double[] vectSigmoidWrite(double[] a, int[] aix, int ai, int alen, int len) {\n+ double[] c = allocVector(len, true, 0.5); //sigmoid(0) = 0.5\n+ for( int j = ai; j < ai+alen; j++ )\n+ c[aix[j]] = 1 / (1 + FastMath.exp(-a[j]));\n+ return c;\n+ }\n+\n//custom vector equal\npublic static void vectEqualAdd(double[] a, double bval, double[] c, int ai, int ci, int len) {\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/RowAggTmplTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/RowAggTmplTest.java", "diff": "@@ -73,6 +73,8 @@ public class RowAggTmplTest extends AutomatedTestBase\nprivate static final String TEST_NAME34 = TEST_NAME+\"34\"; //X / rowSums(X!=0)\nprivate static final String TEST_NAME35 = TEST_NAME+\"35\"; //cbind(X/rowSums(X), Y, Z)\nprivate static final String TEST_NAME36 = TEST_NAME+\"36\"; //xor operation\n+ private static final String TEST_NAME37 = TEST_NAME+\"37\"; //sprop(X/rowSums)\n+ private static final String TEST_NAME38 = TEST_NAME+\"38\"; //sigmoid(X/rowSums)\nprivate static final String TEST_DIR = \"functions/codegen/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + RowAggTmplTest.class.getSimpleName() + \"/\";\n@@ -84,7 +86,7 @@ public class RowAggTmplTest extends AutomatedTestBase\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n- for(int i=1; i<=36; i++)\n+ for(int i=1; i<=38; i++)\naddTestConfiguration( TEST_NAME+i, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME+i, new String[] { String.valueOf(i) }) );\n}\n@@ -628,6 +630,36 @@ public class RowAggTmplTest extends AutomatedTestBase\ntestCodegenIntegration( TEST_NAME36, false, ExecType.SPARK );\n}\n+ @Test\n+ public void testCodegenRowAggRewrite37CP() {\n+ testCodegenIntegration( TEST_NAME37, true, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAgg37CP() {\n+ testCodegenIntegration( TEST_NAME37, false, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAgg37SP() {\n+ testCodegenIntegration( TEST_NAME37, false, ExecType.SPARK );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAggRewrite38CP() {\n+ testCodegenIntegration( TEST_NAME38, true, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAgg38CP() {\n+ testCodegenIntegration( TEST_NAME38, false, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAgg38SP() {\n+ testCodegenIntegration( TEST_NAME38, false, ExecType.SPARK );\n+ }\n+\nprivate void testCodegenIntegration( String testname, boolean rewrites, ExecType instType )\n{\nboolean oldFlag = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/rowAggPattern37.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+options(digits=22)\n+library(\"Matrix\")\n+library(\"matrixStats\")\n+\n+X = matrix(seq(1, 6000)/600, 300, 20, byrow=TRUE);\n+\n+Y = X/(rowSums(X)%*%matrix(1,1,ncol(X)))\n+S = Y * (Y-1);\n+\n+writeMM(as(S, \"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/rowAggPattern37.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 = matrix(seq(1, 6000)/600, 300, 20);\n+\n+Y = X/rowSums(X)\n+S = Y * (Y-1);\n+\n+write(S, $1);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/rowAggPattern38.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+options(digits=22)\n+library(\"Matrix\")\n+library(\"matrixStats\")\n+\n+X = matrix(seq(1, 6000)/600, 300, 20, byrow=TRUE);\n+\n+Y = X/(rowSums(X)%*%matrix(1,1,ncol(X)))\n+S = 1 / (1 + exp(-Y));\n+\n+writeMM(as(S, \"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/rowAggPattern38.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 = matrix(seq(1, 6000)/600, 300, 20);\n+\n+Y = X/rowSums(X)\n+S = 1 / (1 + exp(-Y));\n+\n+write(S, $1);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2143] Fix missing sprop/sigmoid codegen support in row templ This patch adds codegen support for sprop (sample proportion) and sigmoid in codegen row templates, which requires sparse and dense vector primitives. So far we only supported scalar sprop and sigmoid in outer, cell and magg templates.
49,738
11.02.2018 11:34:32
28,800
5fcda00a9c2b02bddc3190b353300ddb10d356b0
[MINOR] Fix robustness of mr aggregation code path (valid dims)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "diff": "@@ -197,14 +197,13 @@ public class OperationsOnMatrixValues\n//set initial values according to operator\nif(op.initialValue==0) {\n- valueOut.reset(outRow, outCol, sparseHint);\n- correction.reset(corRow, corCol, false);\n+ valueOut.reset(Math.max(outRow,0), Math.max(outCol,0), sparseHint);\n+ correction.reset(Math.max(corRow,0), Math.max(corCol,0), false);\n}\nelse {\n- valueOut.reset(outRow, outCol, op.initialValue);\n- correction.reset(corRow, corCol, op.initialValue);\n+ valueOut.reset(Math.max(outRow, 0), Math.max(outCol,0), op.initialValue);\n+ correction.reset(Math.max(corRow,0), Math.max(corCol,0), op.initialValue);\n}\n-\n}\nelse\n{\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix robustness of mr aggregation code path (valid dims)
49,738
11.02.2018 14:44:15
28,800
f4efd99a45d57c1b2c36f62eab7470d9bd61347e
[HOTFIX][SYSTEMML-2068] Fix corrupted merge of cell bitwAnd operations
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeBinary.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeBinary.java", "diff": "@@ -210,7 +210,7 @@ public class CNodeBinary extends CNode\ncase XOR:\nreturn \" double %TMP% = ( (%IN1% != 0) != (%IN2% != 0) ) ? 1 : 0;\\n\";\ncase BITWAND:\n- return \" double %TMP% = LibSpoofPrimitives.intDiv(%IN1%, %IN2%);\\n\";\n+ return \" double %TMP% = LibSpoofPrimitives.bwAnd(%IN1%, %IN2%);\\n\";\ndefault:\nthrow new RuntimeException(\"Invalid binary type: \"+this.toString());\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX][SYSTEMML-2068] Fix corrupted merge of cell bitwAnd operations
49,738
11.02.2018 19:20:03
28,800
4add81b0443c9150c946e0d46196d5a90df3525c
[MINOR] Extended JMLC API (obtain current config of prepared scripts)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/jmlc/PreparedScript.java", "new_path": "src/main/java/org/apache/sysml/api/jmlc/PreparedScript.java", "diff": "@@ -139,6 +139,26 @@ public class PreparedScript implements ConfigurableAPI\n}\n}\n+ /**\n+ * Get the dml configuration object associated with\n+ * the prepared script instance.\n+ *\n+ * @return dml configuration\n+ */\n+ public DMLConfig getDMLConfig() {\n+ return _dmlconf;\n+ }\n+\n+ /**\n+ * Get the compiler configuration object associated with\n+ * the prepared script instance.\n+ *\n+ * @return compiler configuration\n+ */\n+ public CompilerConfig getCompilerConfig() {\n+ return _cconf;\n+ }\n+\n/**\n* Binds a scalar boolean to a registered input variable.\n*\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Extended JMLC API (obtain current config of prepared scripts)
49,738
11.02.2018 21:21:18
28,800
85cb9e34e79b1b87ebe09d2a37658f9265d8ef9a
[MINOR] Cleanup and simplification of l2svm algorithm script
[ { "change_type": "MODIFY", "old_path": "scripts/algorithms/l2-svm.dml", "new_path": "scripts/algorithms/l2-svm.dml", "diff": "# Log String --- [OPTIONAL] Location to write the log file\n# ---------------------------------------------------------------------------------------------\n-# hadoop jar SystemML.jar -f $L2SVM_HOME/l2-svm.dml -nvargs X=$INPUT_DIR/X Y=$INPUT_DIR/Y icpt=0 tol=0.001 reg=1 maxiter=100 model=$OUPUT_DIR/w Log=$OUTPUT_DIR/Log fmt=\"text\"\n+# hadoop jar SystemML.jar -f $L2SVM_HOME/l2-svm.dml -nvargs X=$INPUT_DIR/X Y=$INPUT_DIR/Y \\\n+# icpt=0 tol=0.001 reg=1 maxiter=100 model=$OUPUT_DIR/w Log=$OUTPUT_DIR/Log fmt=\"text\"\n#\n# Note about inputs:\n-# Assumes that labels (entries in Y)\n-# are set to either -1 or +1\n-# or the result of recoding\n-#\n+# Assumes that labels (entries in Y) are set to either -1 or +1 or non-negative integers\n-cmdLine_fmt = ifdef($fmt, \"text\")\n-cmdLine_icpt = ifdef($icpt, 0)\n-cmdLine_tol = ifdef($tol, 0.001)\n-cmdLine_reg = ifdef($reg, 1.0)\n-cmdLine_maxiter = ifdef($maxiter, 100)\n+fmt = ifdef($fmt, \"text\")\n+intercept = ifdef($icpt, 0)\n+epsilon = ifdef($tol, 0.001)\n+lambda = ifdef($reg, 1.0)\n+maxiterations = ifdef($maxiter, 100)\nX = read($X)\nY = read($Y)\n+#check input parameter assertions\nif(nrow(X) < 2)\nstop(\"Stopping due to invalid inputs: Not possible to learn a binary class classifier without at least 2 rows\")\n+if(intercept != 0 & intercept != 1)\n+ stop(\"Stopping due to invalid argument: Currently supported intercept options are 0 and 1\")\n+if(epsilon < 0)\n+ stop(\"Stopping due to invalid argument: Tolerance (tol) must be non-negative\")\n+if(lambda < 0)\n+ stop(\"Stopping due to invalid argument: Regularization constant (reg) must be non-negative\")\n+if(maxiterations < 1)\n+ stop(\"Stopping due to invalid argument: Maximum iterations should be a positive integer\")\n+#check input lables and transform into -1/1\ncheck_min = min(Y)\ncheck_max = max(Y)\nnum_min = sum(Y == check_min)\nnum_max = sum(Y == check_max)\n-\nif(check_min == check_max)\nstop(\"Stopping due to invalid inputs: Y seems to contain exactly one label\")\n-\nif(num_min + num_max != nrow(Y))\nstop(\"Stopping due to invalid inputs: Y seems to contain more than 2 labels\")\n-\n-if(check_min != -1 | check_max != +1)\n+if(check_min != -1 | check_max != 1)\nY = 2/(check_max - check_min)*Y - (check_min + check_max)/(check_max - check_min)\npositive_label = check_max\nnegative_label = check_min\n-\n-intercept = cmdLine_icpt\n-if(intercept != 0 & intercept != 1)\n- stop(\"Stopping due to invalid argument: Currently supported intercept options are 0 and 1\")\n-\n-epsilon = cmdLine_tol\n-if(epsilon < 0)\n- stop(\"Stopping due to invalid argument: Tolerance (tol) must be non-negative\")\n-\n-lambda = cmdLine_reg\n-if(lambda < 0)\n- stop(\"Stopping due to invalid argument: Regularization constant (reg) must be non-negative\")\n-\n-maxiterations = cmdLine_maxiter\n-if(maxiterations < 1)\n- stop(\"Stopping due to invalid argument: Maximum iterations should be a positive integer\")\n-\nnum_samples = nrow(X)\ndimensions = ncol(X)\n+num_rows_in_w = dimensions\nif (intercept == 1) {\nones = matrix(1, rows=num_samples, cols=1)\nX = cbind(X, ones);\n+ num_rows_in_w += 1\n}\n-num_rows_in_w = dimensions\n-if(intercept == 1){\n- num_rows_in_w = num_rows_in_w + 1\n-}\n-w = matrix(0, rows=num_rows_in_w, cols=1)\n-\n+w = matrix(0, num_rows_in_w, 1)\n+Xw = matrix(0, rows=nrow(X), cols=1)\ng_old = t(X) %*% Y\ns = g_old\n-Xw = matrix(0, rows=nrow(X), cols=1)\ndebug_str = \"# Iter, Obj\"\niter = 0\ncontinue = TRUE\n+\nwhile(continue & iter < maxiterations) {\n# minimizing primal obj along direction s\nstep_sz = 0\n@@ -127,13 +113,12 @@ while(continue & iter < maxiterations) {\ncontinue1 = TRUE\nwhile(continue1) {\ntmp_Xw = Xw + step_sz*Xd\n- out = 1 - Y * (tmp_Xw)\n- sv = (out > 0)\n+ out = 1 - Y * tmp_Xw\n+ sv = out > 0\nout = out * sv\ng = wd + step_sz*dd - sum(out * Y * Xd)\nh = dd + sum(Xd * sv * Xd)\nstep_sz = step_sz - g/h\n-\ncontinue1 = (g*g/h >= 0.0000000001);\n}\n@@ -142,7 +127,7 @@ while(continue & iter < maxiterations) {\nXw += step_sz * Xd\nout = 1 - Y * Xw\n- sv = (out > 0)\n+ sv = out > 0\nout = sv * out\nobj = 0.5 * sum(out * out) + lambda/2 * sum(w * w)\ng_new = t(X) %*% (out * Y) - lambda * w\n@@ -161,16 +146,15 @@ while(continue & iter < maxiterations) {\niter = iter + 1\n}\n-extra_model_params = matrix(0, rows=4, cols=1)\n+extra_model_params = matrix(0, 4, 1)\nextra_model_params[1,1] = positive_label\nextra_model_params[2,1] = negative_label\nextra_model_params[3,1] = intercept\nextra_model_params[4,1] = dimensions\n-w = t(cbind(t(w), t(extra_model_params)))\n-write(w, $model, format=cmdLine_fmt)\n+w = rbind(w, extra_model_params)\n+write(w, $model, format=fmt)\nlogFile = $Log\n-if(logFile != \" \") {\n+if(logFile != \" \")\nwrite(debug_str, logFile)\n-}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Cleanup and simplification of l2svm algorithm script
49,738
13.02.2018 15:17:45
28,800
7aa9cca7bb4d3685a6b1b3b5bb30fb092fa0ab48
[MINOR] Fix codegen cost model (missing ifelse, warn on stats overflow)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/opt/PlanSelectionFuseCostBasedV2.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/opt/PlanSelectionFuseCostBasedV2.java", "diff": "@@ -147,9 +147,13 @@ public class PlanSelectionFuseCostBasedV2 extends PlanSelection\nmemo.setDistinct(e.getKey(), e.getValue());\n//maintain statistics\n- if( DMLScript.STATISTICS )\n+ if( DMLScript.STATISTICS ) {\n+ if( sumMatPoints >= 63 )\n+ LOG.warn(\"Long overflow on maintaining codegen statistics \"\n+ + \"for a DAG with \"+sumMatPoints+\" interesting points.\");\nStatistics.incrementCodegenEnumAll(UtilFunctions.pow(2, sumMatPoints));\n}\n+ }\nprivate void selectPlans(CPlanMemoTable memo, PlanPartition part)\n{\n@@ -1033,6 +1037,7 @@ public class PlanSelectionFuseCostBasedV2 extends PlanSelection\n}\nelse if( current instanceof TernaryOp ) {\nswitch( ((TernaryOp)current).getOp() ) {\n+ case IFELSE:\ncase PLUS_MULT:\ncase MINUS_MULT: costs = 2; break;\ncase CTABLE: costs = 3; break;\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix codegen cost model (missing ifelse, warn on stats overflow)
49,738
13.02.2018 18:01:44
28,800
beb704e2dc1fe2d42a1a9d6cb6d4563f37623863
[MINOR] Improved handling of commutative binary codegen operations
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeBinary.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/cplan/CNodeBinary.java", "diff": "@@ -63,12 +63,15 @@ public class CNodeBinary extends CNode\npublic boolean isCommutative() {\nboolean ssComm = (this==EQUAL || this==NOTEQUAL\n- || this==PLUS || this==MULT || this==MIN || this==MAX);\n+ || this==PLUS || this==MULT || this==MIN || this==MAX\n+ || this==OR || this==AND || this==XOR || this==BITWAND);\nboolean vsComm = (this==VECT_EQUAL_SCALAR || this==VECT_NOTEQUAL_SCALAR\n|| this==VECT_PLUS_SCALAR || this==VECT_MULT_SCALAR\n- || this==VECT_MIN_SCALAR || this==VECT_MAX_SCALAR);\n+ || this==VECT_MIN_SCALAR || this==VECT_MAX_SCALAR\n+ || this==VECT_XOR_SCALAR || this==VECT_BITWAND_SCALAR );\nboolean vvComm = (this==VECT_EQUAL || this==VECT_NOTEQUAL\n- || this==VECT_PLUS || this==VECT_MULT || this==VECT_MIN || this==VECT_MAX);\n+ || this==VECT_PLUS || this==VECT_MULT || this==VECT_MIN || this==VECT_MAX\n+ || this==VECT_XOR || this==BinType.VECT_BITWAND);\nreturn ssComm || vsComm || vvComm;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "new_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "diff": "@@ -580,8 +580,7 @@ public class LibSpoofPrimitives\n}\npublic static void vectXorAdd(double bval, double[] a, double[] c, int ai, int ci, int len) {\n- for( int j = ai; j < ai+len; j++, ci++)\n- c[ci] += ( (bval != 0) != (a[j] != 0) ) ? 1 : 0;\n+ vectXorAdd(a, bval, c, ai, ci, len);\n}\npublic static void vectXorAdd(double[] a, double bval, double[] c, int[] aix, int ai, int ci, int alen, int len) {\n@@ -590,8 +589,7 @@ public class LibSpoofPrimitives\n}\npublic static void vectXorAdd(double bval, double[] a, double[] c, int[] aix, int ai, int ci, int alen, int len) {\n- for( int j = ai; j < ai+alen; j++ )\n- c[ci + aix[j]] += ( (bval != 0) != (a[j] != 0) ) ? 1 : 0;\n+ vectXorAdd(a, bval, c, aix, ai, ci, alen, len);\n}\n//1. scalar vs. dense vector\n@@ -604,10 +602,7 @@ public class LibSpoofPrimitives\n//2. dense vector vs. scalar\npublic static double[] vectXorWrite(double bval, double[] a, int ai, int len) {\n- double[] c = allocVector(len, false);\n- for( int j = 0; j < len; j++)\n- c[j] = ( (bval != 0) != (a[ai + j] != 0) ) ? 1 : 0;\n- return c;\n+ return vectXorWrite(a, bval, ai, len);\n}\n//3. dense vector vs. dense vector\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Improved handling of commutative binary codegen operations
49,703
14.02.2018 14:54:25
28,800
c821722db7c66f0e69a92eb6dc305a19c7d98b58
[MINOR] Update doc version to match pom.xml version
[ { "change_type": "MODIFY", "old_path": "docs/_config.yml", "new_path": "docs/_config.yml", "diff": "@@ -15,7 +15,7 @@ exclude:\n- lang-ref\n# These allow the documentation to be updated with newer releases\n-SYSTEMML_VERSION: 1.0.0-SNAPSHOT\n+SYSTEMML_VERSION: 1.1.0-SNAPSHOT\n# if 'analytics_on' is true, analytics section will be rendered on the HTML pages\nanalytics_on: true\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Update doc version to match pom.xml version
49,698
14.02.2018 22:07:05
28,800
ddaf166fb68adb107b6f4cbb064b75588e5cd80e
New tests for codegen relu backward operations Closes
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CellwiseTmplTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/CellwiseTmplTest.java", "diff": "@@ -56,6 +56,7 @@ public class CellwiseTmplTest extends AutomatedTestBase\nprivate static final String TEST_NAME18 = TEST_NAME+18; //sum(ifelse(X,Y,Z))\nprivate static final String TEST_NAME19 = TEST_NAME+19; //sum(ifelse(true,Y,Z))+sum(ifelse(false,Y,Z))\nprivate static final String TEST_NAME20 = TEST_NAME+20; //bitwAnd() operation\n+ private static final String TEST_NAME21 = TEST_NAME+21; //relu operation, (X>0)*dout\nprivate static final String TEST_DIR = \"functions/codegen/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + CellwiseTmplTest.class.getSimpleName() + \"/\";\n@@ -68,7 +69,7 @@ public class CellwiseTmplTest extends AutomatedTestBase\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n- for( int i=1; i<=20; i++ ) {\n+ for( int i=1; i<=21; i++ ) {\naddTestConfiguration( TEST_NAME+i, new TestConfiguration(\nTEST_CLASS_DIR, TEST_NAME+i, new String[] {String.valueOf(i)}) );\n}\n@@ -351,6 +352,21 @@ public class CellwiseTmplTest extends AutomatedTestBase\ntestCodegenIntegration( TEST_NAME20, true, ExecType.SPARK );\n}\n+ @Test\n+ public void testCodegenCellwiseRewrite21() {\n+ testCodegenIntegration( TEST_NAME21, true, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenCellwise21() {\n+ testCodegenIntegration( TEST_NAME21, false, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenCellwiseRewrite21_sp() {\n+ testCodegenIntegration( TEST_NAME21, true, ExecType.SPARK );\n+ }\n+\nprivate void testCodegenIntegration( String testname, boolean rewrites, ExecType instType )\n{\nboolean oldRewrites = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/RowAggTmplTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/codegen/RowAggTmplTest.java", "diff": "@@ -76,6 +76,7 @@ public class RowAggTmplTest extends AutomatedTestBase\nprivate static final String TEST_NAME37 = TEST_NAME+\"37\"; //sprop(X/rowSums)\nprivate static final String TEST_NAME38 = TEST_NAME+\"38\"; //sigmoid(X/rowSums)\nprivate static final String TEST_NAME39 = TEST_NAME+\"39\"; //BitwAnd operation\n+ private static final String TEST_NAME40 = TEST_NAME+\"40\"; //relu operation -> (X>0)* dout\nprivate static final String TEST_DIR = \"functions/codegen/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + RowAggTmplTest.class.getSimpleName() + \"/\";\n@@ -87,7 +88,7 @@ public class RowAggTmplTest extends AutomatedTestBase\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\n- for(int i=1; i<=39; i++)\n+ for(int i=1; i<=40; i++)\naddTestConfiguration( TEST_NAME+i, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME+i, new String[] { String.valueOf(i) }) );\n}\n@@ -676,6 +677,21 @@ public class RowAggTmplTest extends AutomatedTestBase\ntestCodegenIntegration( TEST_NAME39, false, ExecType.SPARK );\n}\n+ @Test\n+ public void testCodegenRowAggRewrite40CP() {\n+ testCodegenIntegration( TEST_NAME40, true, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAgg40CP() {\n+ testCodegenIntegration( TEST_NAME40, false, ExecType.CP );\n+ }\n+\n+ @Test\n+ public void testCodegenRowAgg40SP() {\n+ testCodegenIntegration( TEST_NAME40, false, ExecType.SPARK );\n+ }\n+\nprivate void testCodegenIntegration( String testname, boolean rewrites, ExecType instType )\n{\nboolean oldFlag = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/cellwisetmpl21.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+options(digits=22)\n+library(\"Matrix\")\n+\n+X = matrix(seq(7, 1006), 500, 2, byrow=TRUE);\n+\n+R1 = (X/3) %% 0.6;\n+R2 = (X/3) %/% 0.6;\n+R = (R1 > 0) * R2\n+\n+writeMM(as(R,\"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/cellwisetmpl21.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 = matrix(seq(7, 1006), 500, 2);\n+\n+R1 = (X/3) %% 0.6;\n+R2 = (X/3) %/% 0.6;\n+R = (R1 > 0) * R2;\n+\n+write(R, $1)\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/rowAggPattern40.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+options(digits=22)\n+library(\"Matrix\")\n+library(\"matrixStats\")\n+\n+X = matrix(seq(1, 6000)/600, 300, 20, byrow=TRUE);\n+\n+Y = X/(rowSums(X)%*%matrix(1,1,ncol(X)))\n+\n+R = (X>0) * Y;\n+\n+writeMM(as(R, \"CsparseMatrix\"), paste(args[2], \"S\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/codegen/rowAggPattern40.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 = matrix(seq(1, 6000)/600, 300, 20);\n+\n+Y = X/rowSums(X)\n+\n+R = (X>0) * Y;\n+\n+write(R, $1)\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2110] New tests for codegen relu backward operations Closes #726.
49,738
14.02.2018 21:48:53
28,800
868b4b98a48d549b4f9670a590693c05613d14b3
Performance codegen cell ops over compressed matrices This patch makes a minor performance improvement to codegen cell operations over compressed matrices, especially for multi-threaded execution. Specifically, we now reuse in a thread-local manner the allocated count arrays across column groups.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/codegen/SpoofCellwise.java", "new_path": "src/main/java/org/apache/sysml/runtime/codegen/SpoofCellwise.java", "diff": "@@ -1082,10 +1082,13 @@ public abstract class SpoofCellwise extends SpoofOperator implements Serializabl\nif( sparseSafe && b.length==0 && !a.hasUncompressedColGroup() ) {\n//note: all remaining groups are guaranteed ColGroupValue\nboolean entireGrp = (rl==0 && ru==a.getNumRows());\n+ int maxNumVals = a.getColGroups().stream().mapToInt(\n+ g -> ((ColGroupValue)g).getNumValues()).max().orElse(0);\n+ int[] counts = new int[maxNumVals];\nfor( ColGroup grp : a.getColGroups() ) {\nColGroupValue grpv = (ColGroupValue) grp;\n- int[] counts = entireGrp ?\n- grpv.getCounts() : grpv.getCounts(rl, ru);\n+ counts = entireGrp ? grpv.getCounts(counts) :\n+ grpv.getCounts(rl, ru, counts);\nfor(int k=0; k<grpv.getNumValues(); k++) {\nkbuff2.set(0, 0);\ndouble in = grpv.sumValues(k, kplus, kbuff2);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupDDC1.java", "new_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupDDC1.java", "diff": "@@ -204,14 +204,14 @@ public class ColGroupDDC1 extends ColGroupDDC\n}\n@Override\n- public int[] getCounts() {\n- return getCounts(0, getNumRows());\n+ public int[] getCounts(int[] counts) {\n+ return getCounts(0, getNumRows(), counts);\n}\n@Override\n- public int[] getCounts(int rl, int ru) {\n+ public int[] getCounts(int rl, int ru, int[] counts) {\nfinal int numVals = getNumValues();\n- int[] counts = new int[numVals];\n+ Arrays.fill(counts, 0, numVals, 0);\nfor( int i=rl; i<ru; i++ )\ncounts[_data[i]&0xFF] ++;\nreturn counts;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupDDC2.java", "new_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupDDC2.java", "diff": "@@ -193,14 +193,14 @@ public class ColGroupDDC2 extends ColGroupDDC\n}\n@Override\n- public int[] getCounts() {\n- return getCounts(0, getNumRows());\n+ public int[] getCounts(int[] counts) {\n+ return getCounts(0, getNumRows(), counts);\n}\n@Override\n- public int[] getCounts(int rl, int ru) {\n+ public int[] getCounts(int rl, int ru, int[] counts) {\nfinal int numVals = getNumValues();\n- int[] counts = new int[numVals];\n+ Arrays.fill(counts, 0, numVals, 0);\nfor( int i=rl; i<ru; i++ )\ncounts[_data[i]] ++;\nreturn counts;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupOLE.java", "new_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupOLE.java", "diff": "@@ -229,9 +229,9 @@ public class ColGroupOLE extends ColGroupOffset\n}\n@Override\n- public int[] getCounts() {\n+ public int[] getCounts(int[] counts) {\nfinal int numVals = getNumValues();\n- int[] counts = new int[numVals];\n+ Arrays.fill(counts, 0, numVals, 0);\nfor (int k = 0; k < numVals; k++) {\nint boff = _ptr[k];\nint blen = len(k);\n@@ -245,10 +245,10 @@ public class ColGroupOLE extends ColGroupOffset\n}\n@Override\n- public int[] getCounts(int rl, int ru) {\n+ public int[] getCounts(int rl, int ru, int[] counts) {\nfinal int blksz = BitmapEncoder.BITMAP_BLOCK_SZ;\nfinal int numVals = getNumValues();\n- int[] counts = new int[numVals];\n+ Arrays.fill(counts, 0, numVals, 0);\nfor (int k = 0; k < numVals; k++) {\nint boff = _ptr[k];\nint blen = len(k);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupRLE.java", "new_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupRLE.java", "diff": "@@ -225,9 +225,9 @@ public class ColGroupRLE extends ColGroupOffset\n}\n@Override\n- public int[] getCounts() {\n+ public int[] getCounts(int[] counts) {\nfinal int numVals = getNumValues();\n- int[] counts = new int[numVals];\n+ Arrays.fill(counts, 0, numVals, 0);\nfor (int k = 0; k < numVals; k++) {\nint boff = _ptr[k];\nint blen = len(k);\n@@ -244,9 +244,9 @@ public class ColGroupRLE extends ColGroupOffset\n}\n@Override\n- public int[] getCounts(int rl, int ru) {\n+ public int[] getCounts(int rl, int ru, int[] counts) {\nfinal int numVals = getNumValues();\n- int[] counts = new int[numVals];\n+ Arrays.fill(counts, 0, numVals, 0);\nfor (int k = 0; k < numVals; k++) {\nint boff = _ptr[k];\nint blen = len(k);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupValue.java", "new_path": "src/main/java/org/apache/sysml/runtime/compress/ColGroupValue.java", "diff": "@@ -149,9 +149,19 @@ public abstract class ColGroupValue extends ColGroup\nreturn ret;\n}\n- public abstract int[] getCounts();\n+ public final int[] getCounts() {\n+ int[] tmp = new int[getNumValues()];\n+ return getCounts(tmp);\n+ }\n+\n+ public abstract int[] getCounts(int[] out);\n+\n+ public final int[] getCounts(int rl, int ru) {\n+ int[] tmp = new int[getNumValues()];\n+ return getCounts(rl, ru, tmp);\n+ }\n- public abstract int[] getCounts(int rl, int ru);\n+ public abstract int[] getCounts(int rl, int ru, int[] out);\npublic int[] getCounts(boolean inclZeros) {\nint[] counts = getCounts();\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2148] Performance codegen cell ops over compressed matrices This patch makes a minor performance improvement to codegen cell operations over compressed matrices, especially for multi-threaded execution. Specifically, we now reuse in a thread-local manner the allocated count arrays across column groups.
49,738
14.02.2018 22:22:55
28,800
6a4f1e799532a71c292762983b8568100f52cc42
Fix unnecessary meta data in sparse block csr This patch fixes unnecessary meta data in the CSR sparse block data structure that was recently introduced (3 days) by a bad merge.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCSR.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCSR.java", "diff": "@@ -52,13 +52,6 @@ public class SparseBlockCSR extends SparseBlock\nprivate double[] _values = null; //value array (size: >=nnz)\nprivate int _size = 0; //actual number of nnz\n- //matrix meta data\n- protected int rlen = -1;\n- protected int clen = -1;\n- protected boolean sparse = true;\n- protected long nonZeros = 0;\n-\n-\npublic SparseBlockCSR(int rlen) {\nthis(rlen, INIT_CAPACITY);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2068] Fix unnecessary meta data in sparse block csr This patch fixes unnecessary meta data in the CSR sparse block data structure that was recently introduced (3 days) by a bad merge.
49,738
15.02.2018 17:23:23
28,800
72830f09ae0aae30fe1c9f24e2fe167f3cf848a1
[MINOR] Additional debug info on matrix compression (column classify)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/compress/CompressedMatrixBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/compress/CompressedMatrixBlock.java", "diff": "@@ -300,6 +300,15 @@ public class CompressedMatrixBlock extends MatrixBlock implements Externalizable\n}\n}\n+ if( LOG.isTraceEnabled() ) {\n+ LOG.trace(\"C: \"+Arrays.toString(colsC.toArray(new Integer[0])));\n+ LOG.trace(\"-- compression ratios: \"+Arrays.toString(\n+ colsC.stream().map(c -> compRatios.get(c)).toArray()));\n+ LOG.trace(\"UC: \"+Arrays.toString(colsUC.toArray(new Integer[0])));\n+ LOG.trace(\"-- compression ratios: \"+Arrays.toString(\n+ colsUC.stream().map(c -> compRatios.get(c)).toArray()));\n+ }\n+\nif( LOG.isDebugEnabled() ) {\n_stats.timePhase1 = time.stop();\nLOG.debug(\"Compression statistics:\");\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Additional debug info on matrix compression (column classify)
49,738
15.02.2018 18:49:00
28,800
62e590ced04900364bdc294538e78de6af3f4988
New simplification rewrite for replace zero w/ scalar There are multiple scripts that emulate the replacement of zeros with a scalar via X + (X==0) * s. We now rewrite this pattern to the builtin function replace(X, 0, s), which avoids an unnecessary intermediate and (partitioning-preserving) joins for distributed operations.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/rewrite/RewriteAlgebraicSimplificationStatic.java", "new_path": "src/main/java/org/apache/sysml/hops/rewrite/RewriteAlgebraicSimplificationStatic.java", "diff": "@@ -175,6 +175,7 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\nhi = fuseOrderOperationChain(hi); //e.g., order(order(X,2),1) -> order(X,(12))\nhi = removeUnnecessaryReorgOperation(hop, hi, i); //e.g., t(t(X))->X; rev(rev(X))->X potentially introduced by other rewrites\nhi = simplifyTransposeAggBinBinaryChains(hop, hi, i);//e.g., t(t(A)%*%t(B)+C) -> B%*%A+t(C)\n+ hi = simplifyReplaceZeroOperation(hop, hi, i); //e.g., X + (X==0) * s -> replace(X, 0, s)\nhi = removeUnnecessaryMinus(hop, hi, i); //e.g., -(-X)->X; potentially introduced by simplify binary or dyn rewrites\nhi = simplifyGroupedAggregate(hi); //e.g., aggregate(target=X,groups=y,fn=\"count\") -> aggregate(target=y,groups=y,fn=\"count\")\nif(OptimizerUtils.ALLOW_OPERATOR_FUSION) {\n@@ -1585,6 +1586,29 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\nreturn hi;\n}\n+ // Patterns: X + (X==0) * s -> replace(X, 0, s)\n+ private static Hop simplifyReplaceZeroOperation(Hop parent, Hop hi, int pos)\n+ throws HopsException\n+ {\n+ if( HopRewriteUtils.isBinary(hi, OpOp2.PLUS) && hi.getInput().get(0).isMatrix()\n+ && HopRewriteUtils.isBinary(hi.getInput().get(1), OpOp2.MULT)\n+ && hi.getInput().get(1).getInput().get(1).isScalar()\n+ && HopRewriteUtils.isBinaryMatrixScalar(hi.getInput().get(1).getInput().get(0), OpOp2.EQUAL, 0)\n+ && hi.getInput().get(1).getInput().get(0).getInput().contains(hi.getInput().get(0)) )\n+ {\n+ HashMap<String, Hop> args = new HashMap<>();\n+ args.put(\"target\", hi.getInput().get(0));\n+ args.put(\"pattern\", new LiteralOp(0));\n+ args.put(\"replacement\", hi.getInput().get(1).getInput().get(1));\n+ Hop replace = HopRewriteUtils.createParameterizedBuiltinOp(\n+ hi.getInput().get(0), args, ParamBuiltinOp.REPLACE);\n+ HopRewriteUtils.replaceChildReference(parent, hi, replace, pos);\n+ hi = replace;\n+ LOG.debug(\"Applied simplifyReplaceZeroOperation (line \"+hi.getBeginLine()+\").\");\n+ }\n+ return hi;\n+ }\n+\n/**\n* Pattners: t(t(X)) -> X, rev(rev(X)) -> X\n*\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2149] New simplification rewrite for replace zero w/ scalar There are multiple scripts that emulate the replacement of zeros with a scalar via X + (X==0) * s. We now rewrite this pattern to the builtin function replace(X, 0, s), which avoids an unnecessary intermediate and (partitioning-preserving) joins for distributed operations.
49,738
16.02.2018 00:09:03
28,800
5837953e94cc427aaf8207d9c94cea36a50499cf
Fix correctness of codegen row powAdd for sparse This patch fixes the result correctness of the codegen powAdd vector (primitive as used in codegen row operations) for sparse inputs.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "new_path": "src/main/java/org/apache/sysml/runtime/codegen/LibSpoofPrimitives.java", "diff": "@@ -655,15 +655,16 @@ public class LibSpoofPrimitives\n}\npublic static void vectPowAdd(double[] a, double bval, double[] c, int[] aix, int ai, int ci, int alen, int len) {\n- if( bval == 0 ) //handle 0^0=1\n+ if( bval == 0 ) //handle 0^0=1 & a^0=1\nfor( int j=0; j<len; j++ )\nc[ci + j] += 1;\n+ else //handle 0^b=0 & a^b\nfor( int j = ai; j < ai+alen; j++ )\n- c[ci + aix[j]] += Math.pow(a[j], bval) - 1;\n+ c[ci + aix[j]] += Math.pow(a[j], bval);\n}\npublic static void vectPowAdd(double bval, double[] a, double[] c, int[] aix, int ai, int ci, int alen, int len) {\n- for( int j=0; j<len; j++ )\n+ for( int j=0; j<len; j++ ) //handle 0^0=1 & b^0=1\nc[ci + j] += 1;\nfor( int j = ai; j < ai+alen; j++ )\nc[ci + aix[j]] += Math.pow(bval, a[j]) - 1;\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2151] Fix correctness of codegen row powAdd for sparse This patch fixes the result correctness of the codegen powAdd vector (primitive as used in codegen row operations) for sparse inputs.
49,738
16.02.2018 20:00:36
28,800
3d5dbe42979004fec95cdf01fd63bd065a7ccc99
Fix robustness parfor check for block partitioning This patch fixes the robustness of the parfor optimizer (for validating a potential input block partitioning) and dependency analysis with regard to null variable names in index expressions.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/ParForStatementBlock.java", "new_path": "src/main/java/org/apache/sysml/parser/ParForStatementBlock.java", "diff": "@@ -1956,9 +1956,12 @@ public class ParForStatementBlock extends ForStatementBlock\nboolean ret = ( _b.length == f2._b.length );\nfor( int i=0; i<_b.length && ret; i++ ) {\nret &= (_b[i] == f2._b[i] );\n- ret &= (_vars[i].equals(f2._vars[i])\n- ||(_vars[i].startsWith(INTERAL_FN_INDEX_ROW) && f2._vars[i].startsWith(INTERAL_FN_INDEX_ROW))\n- ||(_vars[i].startsWith(INTERAL_FN_INDEX_COL) && f2._vars[i].startsWith(INTERAL_FN_INDEX_COL)) ) ;\n+ //note robustness for null var names\n+ String var1 = String.valueOf(_vars[i]);\n+ String var2 = String.valueOf(f2._vars[i]);\n+ ret &= (var1.equals(var2)\n+ ||(var1.startsWith(INTERAL_FN_INDEX_ROW) && var2.startsWith(INTERAL_FN_INDEX_ROW))\n+ ||(var1.startsWith(INTERAL_FN_INDEX_COL) && var2.startsWith(INTERAL_FN_INDEX_COL)));\n}\nreturn ret;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2153] Fix robustness parfor check for block partitioning This patch fixes the robustness of the parfor optimizer (for validating a potential input block partitioning) and dependency analysis with regard to null variable names in index expressions.
49,738
16.02.2018 21:32:22
28,800
5e3fed25b55e60a017597fc2c8c6721e2096f056
[MINOR] Extended JMLC API (pass global dml config before prepareScript)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/jmlc/Connection.java", "new_path": "src/main/java/org/apache/sysml/api/jmlc/Connection.java", "diff": "@@ -103,8 +103,52 @@ public class Connection implements Closeable\n* Connection constructor, the starting point for any other JMLC API calls.\n*\n*/\n- public Connection()\n- {\n+ public Connection() {\n+ //with default dml configuration\n+ this(new DMLConfig());\n+ }\n+\n+ /**\n+ * Connection constructor, the starting point for any other JMLC API calls.\n+ * This variant allows to enable a set of boolean compiler configurations.\n+ *\n+ * @param cconfigs one or many boolean compiler configurations to enable.\n+ */\n+ public Connection(CompilerConfig.ConfigType... cconfigs) {\n+ //basic constructor, which also constructs the compiler config\n+ this(new DMLConfig()); //with default dml configuration\n+\n+ //set optional compiler configurations in current config\n+ for( ConfigType configType : cconfigs )\n+ _cconf.set(configType, true);\n+ setLocalConfigs();\n+ }\n+\n+ /**\n+ * Connection constructor, the starting point for any other JMLC API calls.\n+ * This variant allows to pass a global dml configuration and enable a set\n+ * of boolean compiler configurations.\n+ *\n+ * @param dmlconfig a dml configuration.\n+ * @param cconfigs one or many boolean compiler configurations to enable.\n+ */\n+ public Connection(DMLConfig dmlconfig, CompilerConfig.ConfigType... cconfigs) {\n+ //basic constructor, which also constructs the compiler config\n+ this(dmlconfig);\n+\n+ //set optional compiler configurations in current config\n+ for( ConfigType configType : cconfigs )\n+ _cconf.set(configType, true);\n+ setLocalConfigs();\n+ }\n+\n+ /**\n+ * Connection constructor, the starting point for any other JMLC API calls.\n+ * This variant allows to pass a global dml configuration.\n+ *\n+ * @param dmlconfig a dml configuration.\n+ */\n+ public Connection(DMLConfig dmlconfig) {\nDMLScript.rtplatform = RUNTIME_PLATFORM.SINGLE_NODE;\n//setup basic parameters for embedded execution\n@@ -129,28 +173,12 @@ public class Connection implements Closeable\n//disable caching globally\nCacheableData.disableCaching();\n- //create default configuration\n- _dmlconf = new DMLConfig();\n+ //assign the given configuration\n+ _dmlconf = dmlconfig;\nsetLocalConfigs();\n}\n- /**\n- * Connection constructor, the starting point for any other JMLC API calls.\n- * This variant allows to enable a set of boolean compiler configurations.\n- *\n- * @param configs one or many boolean compiler configurations to enable.\n- */\n- public Connection(CompilerConfig.ConfigType... configs) {\n- //basic constructor, which also constructs the compiler config\n- this();\n-\n- //set optional compiler configurations in current config\n- for( ConfigType configType : configs )\n- _cconf.set(configType, true);\n- setLocalConfigs();\n- }\n-\n/**\n* Prepares (precompiles) a script and registers input and output variables.\n*\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Extended JMLC API (pass global dml config before prepareScript)
49,698
19.02.2018 00:35:31
28,800
e9a6e396a3d46e0e2ce41f196e5920d3c8508dce
Sparse block API extension for validity checks Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/ProgramBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/ProgramBlock.java", "diff": "@@ -363,7 +363,13 @@ public class ProgramBlock implements ParseInfo\nsynchronized( mb ) { //potential state change\nmb.recomputeNonZeros();\nmb.examSparsity();\n+\n+ }\n+ if( mb.isInSparseFormat() && mb.isAllocated() ) {\n+ mb.getSparseBlock().checkValidity(mb.getNumRows(),\n+ mb.getNumColumns(), mb.getNonZeros(), true);\n}\n+\nboolean sparse2 = mb.isInSparseFormat();\nlong nnz2 = mb.getNonZeros();\nmo.release();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlock.java", "diff": "@@ -247,6 +247,20 @@ public abstract class SparseBlock implements Serializable\n*/\npublic abstract boolean isEmpty(int r);\n+ /**\n+ * Validate the correctness of the internal data structures of the different\n+ * sparse block implementations.\n+ *\n+ * @param rlen number of rows\n+ * @param clen number of columns\n+ * @param nnz number of non zeros\n+ * @param strict enforce optional properties\n+ * @return true if the sparse block is valid wrt the corresponding format\n+ * such as COO, CSR, MCSR.\n+ */\n+\n+ public abstract boolean checkValidity(int rlen, int clen, long nnz, boolean strict);\n+\n////////////////////////\n//obtain indexes/values/positions\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCOO.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCOO.java", "diff": "@@ -192,6 +192,12 @@ public class SparseBlockCOO extends SparseBlock\nreturn true;\n}\n+ @Override\n+ public boolean checkValidity(int rlen, int clen, long nnz, boolean strict) {\n+ //empty implementation\n+ return true;\n+ }\n+\n@Override\npublic void reset() {\n_size = 0;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCSR.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCSR.java", "diff": "@@ -842,6 +842,57 @@ public class SparseBlockCSR extends SparseBlock\nreturn sb.toString();\n}\n+ @Override\n+ public boolean checkValidity(int rlen, int clen, long nnz, boolean strict) {\n+ //1. correct meta data\n+ if( rlen < 0 || clen < 0 ) {\n+ throw new RuntimeException(\"Invalid block dimensions: \"+rlen+\" \"+clen);\n+ }\n+\n+ //2. correct array lengths\n+ if(_size != nnz && _ptr.length < rlen+1 && _values.length < nnz && _indexes.length < nnz ) {\n+ throw new RuntimeException(\"Incorrect array lengths.\");\n+ }\n+\n+ //3. non-decreasing row pointers\n+ for( int i=1; i<rlen; i++ ) {\n+ if(_ptr[i-1] > _ptr[i] && strict)\n+ throw new RuntimeException(\"Row pointers are decreasing at row: \"+i\n+ + \", with pointers \"+_ptr[i-1]+\" > \"+_ptr[i]);\n+ }\n+\n+ //4. sorted column indexes per row\n+ for( int i=0; i<rlen; i++ ) {\n+ int apos = pos(i);\n+ int alen = size(i);\n+ for( int k=apos+1; k<apos+alen; k++)\n+ if( _indexes[k-1] >= _indexes[k] )\n+ throw new RuntimeException(\"Wrong sparse row ordering: \"\n+ + k + \" \"+_indexes[k-1]+\" \"+_indexes[k]);\n+ for( int k=apos; k<apos+alen; k++ )\n+ if( _values[k] == 0 )\n+ throw new RuntimeException(\"Wrong sparse row: zero at \"\n+ + k + \" at col index \" + _indexes[k]);\n+ }\n+\n+ //5. non-existing zero values\n+ for( int i=0; i<_size; i++ ) {\n+ if( _values[i] == 0 ) {\n+ throw new RuntimeException(\"The values array should not contain zeros.\"\n+ + \" The \" + i + \"th value is \"+_values[i]);\n+ }\n+ }\n+\n+ //6. a capacity that is no larger than nnz times resize factor.\n+ int capacity = _values.length;\n+ if(capacity > nnz*RESIZE_FACTOR1 ) {\n+ throw new RuntimeException(\"Capacity is larger than the nnz times a resize factor.\"\n+ + \" Current size: \"+capacity+ \", while Expected size:\"+nnz*RESIZE_FACTOR1);\n+ }\n+\n+ return true;\n+ }\n+\n///////////////////////////\n// private helper methods\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockMCSR.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockMCSR.java", "diff": "@@ -158,6 +158,12 @@ public class SparseBlockMCSR extends SparseBlock\nreturn (_rows[r] != null);\n}\n+ @Override\n+ public boolean checkValidity(int rlen, int clen, long nnz, boolean strict) {\n+ // empty implementation\n+ return true;\n+ }\n+\n@Override\npublic void reset() {\nfor( SparseRow row : _rows )\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2130] Sparse block API extension for validity checks Closes #730.
49,738
19.02.2018 20:33:24
28,800
7b1f869991e70cea99317162453e3215f567c10b
[MINOR] Extended UDF framework (access to execution context) This patch makes a minor extension to the UDF function framework to pass the execution context, which allows access to all registered dml-bodied or external functions. The default implementation simply forwards to the existing execute call which means no existing UDF requires changes.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/udf/ExternalFunctionInvocationInstruction.java", "new_path": "src/main/java/org/apache/sysml/udf/ExternalFunctionInvocationInstruction.java", "diff": "@@ -74,7 +74,7 @@ public class ExternalFunctionInvocationInstruction extends Instruction\nfun.setFunctionInputs(getInputObjects(inputs, ec.getVariables()));\n//executes function\n- fun.execute();\n+ fun.execute(ec);\n// get and verify the outputs\nverifyAndAttachOutputs(ec, fun, outputs);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/udf/PackageFunction.java", "new_path": "src/main/java/org/apache/sysml/udf/PackageFunction.java", "diff": "@@ -22,6 +22,7 @@ package org.apache.sysml.udf;\nimport java.io.Serializable;\nimport java.util.ArrayList;\n+import org.apache.sysml.runtime.controlprogram.context.ExecutionContext;\nimport org.apache.sysml.runtime.controlprogram.parfor.util.IDSequence;\n/**\n@@ -159,4 +160,14 @@ public abstract class PackageFunction implements Serializable\n*/\npublic abstract void execute();\n+ /**\n+ * Method that will be executed to perform this function. The default\n+ * implementation simply forwards this call to execute.\n+ *\n+ * @param execution context with access to the program\n+ * e.g., for access to other dml-bodied or external functions.\n+ */\n+ public void execute(ExecutionContext ec) {\n+ execute(); //default impl\n+ }\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Extended UDF framework (access to execution context) This patch makes a minor extension to the UDF function framework to pass the execution context, which allows access to all registered dml-bodied or external functions. The default implementation simply forwards to the existing execute call which means no existing UDF requires changes.
49,738
20.02.2018 00:41:29
28,800
92034e64fdcab668c757aaa6cce74ab24fcb86c7
[HOTFIX] Fix minor java doc issue (breaking distribution build)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/udf/PackageFunction.java", "new_path": "src/main/java/org/apache/sysml/udf/PackageFunction.java", "diff": "@@ -164,7 +164,7 @@ public abstract class PackageFunction implements Serializable\n* Method that will be executed to perform this function. The default\n* implementation simply forwards this call to execute.\n*\n- * @param execution context with access to the program\n+ * @param ec execution context with access to the program\n* e.g., for access to other dml-bodied or external functions.\n*/\npublic void execute(ExecutionContext ec) {\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix minor java doc issue (breaking distribution build)
49,738
22.02.2018 18:30:30
28,800
f2fbd99e7d78eb27a560b3095c9db5565f625e95
[MINOR] Improved analysis for sparse-safe codegen cell operations
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/OptimizerUtils.java", "new_path": "src/main/java/org/apache/sysml/hops/OptimizerUtils.java", "diff": "@@ -1038,6 +1038,7 @@ public class OptimizerUtils\n||(op==OpOp2.EQUAL && val!=0)\n||(op==OpOp2.MINUS && val==0)\n||(op==OpOp2.PLUS && val==0)\n+ ||(op==OpOp2.POW && val!=0)\n||(op==OpOp2.MAX && val<=0)\n||(op==OpOp2.MIN && val>=0));\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateUtils.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/template/TemplateUtils.java", "diff": "@@ -257,8 +257,10 @@ public class TemplateUtils\npublic static boolean rIsSparseSafeOnly(CNode node, BinType...types) {\nif( !(isBinary(node, types) || node instanceof CNodeData\n- || (node instanceof CNodeUnary && ((CNodeUnary)node).getType().isScalarLookup())\n- || (node instanceof CNodeUnary && ((CNodeUnary)node).getType().isSparseSafeScalar())) )\n+ || (node instanceof CNodeUnary && ((((CNodeUnary)node).getType().isScalarLookup())\n+ || ((CNodeUnary)node).getType().isSparseSafeScalar()\n+ || ((CNodeUnary)node).getType()==UnaryType.POW2\n+ || ((CNodeUnary)node).getType()==UnaryType.MULT2)) ))\nreturn false;\nboolean ret = true;\nfor( CNode c : node.getInput() )\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Improved analysis for sparse-safe codegen cell operations
49,736
27.02.2018 13:21:32
28,800
8ffa3d158fe97e0871bcd4b77fa27504b8b85502
Allow users to pass the file paths to the binary blocked, csv and ijv datasets to mllearn classes. This allows the advance users who already have data materialized in binary blocked formats to avoid conversion overhead. Also, this facility is useful for benchmarking the performance of Keras2DML and Caffe2DML.
[ { "change_type": "MODIFY", "old_path": "src/main/python/systemml/mllearn/estimators.py", "new_path": "src/main/python/systemml/mllearn/estimators.py", "diff": "@@ -187,6 +187,18 @@ class BaseSystemMLEstimator(Estimator):\nself.y = None\nreturn self\n+ def fit_file(self, X_file, y_file):\n+ global default_jvm_stdout, default_jvm_stdout_parallel_flush\n+ try:\n+ if default_jvm_stdout:\n+ with jvm_stdout(parallel_flush=default_jvm_stdout_parallel_flush):\n+ self.model = self.estimator.fit(X_file, y_file)\n+ else:\n+ self.model = self.estimator.fit(X_file, y_file)\n+ except Py4JError:\n+ traceback.print_exc()\n+ return self\n+\n# Returns a model after calling fit(df) on Estimator object on JVM\ndef _fit(self, X):\n\"\"\"\n@@ -207,12 +219,14 @@ class BaseSystemMLEstimator(Estimator):\nParameters\n----------\n- X: NumPy ndarray, Pandas DataFrame, scipy sparse matrix\n- y: NumPy ndarray, Pandas DataFrame, scipy sparse matrix\n+ X: NumPy ndarray, Pandas DataFrame, scipy sparse matrix, Spark DataFrame, file path\n+ y: NumPy ndarray, Pandas DataFrame, scipy sparse matrix, file path\n\"\"\"\nif y is None:\nreturn self._fit(X)\n- elif y is not None and isinstance(X, SUPPORTED_TYPES) and isinstance(y, SUPPORTED_TYPES):\n+ elif isinstance(X, str) and isinstance(y, str):\n+ return self.fit_file(X, y)\n+ elif isinstance(X, SUPPORTED_TYPES) and isinstance(y, SUPPORTED_TYPES):\n# Donot encode if y is a numpy matrix => useful for segmentation\nskipEncodingY = len(y.shape) == 2 and y.shape[0] != 1 and y.shape[1] != 1\ny = y if skipEncodingY else self.encode(y)\n@@ -307,6 +321,8 @@ class BaseSystemMLEstimator(Estimator):\nexcept AttributeError:\npass\ntry:\n+ if isinstance(X, str):\n+ return self.model.transform_probability(X)\njX = self._convertPythonXToJavaObject(X)\nif default_jvm_stdout:\nwith jvm_stdout(parallel_flush=default_jvm_stdout_parallel_flush):\n@@ -323,7 +339,7 @@ class BaseSystemMLEstimator(Estimator):\nParameters\n----------\n- X: NumPy ndarray, Pandas DataFrame, scipy sparse matrix or PySpark DataFrame\n+ X: NumPy ndarray, Pandas DataFrame, scipy sparse matrix or PySpark DataFrame or file path\n\"\"\"\nglobal default_jvm_stdout, default_jvm_stdout_parallel_flush\ntry:\n@@ -332,6 +348,8 @@ class BaseSystemMLEstimator(Estimator):\nexcept AttributeError:\npass\ntry:\n+ if isinstance(X, str):\n+ return self.model.transform(X)\njX = self._convertPythonXToJavaObject(X)\nif default_jvm_stdout:\nwith jvm_stdout(parallel_flush=default_jvm_stdout_parallel_flush):\n" }, { "change_type": "MODIFY", "old_path": "src/main/scala/org/apache/sysml/api/dl/Caffe2DML.scala", "new_path": "src/main/scala/org/apache/sysml/api/dl/Caffe2DML.scala", "diff": "@@ -206,6 +206,10 @@ class Caffe2DML(val sc: SparkContext,\nval that = new Caffe2DML(sc, solverParam, solver, net, lrPolicy, numChannels, height, width)\ncopyValues(that, extra)\n}\n+ def fit(X_file: String, y_file: String): Caffe2DMLModel = {\n+ mloutput = baseFit(X_file, y_file, sc)\n+ new Caffe2DMLModel(this)\n+ }\n// Note: will update the y_mb as this will be called by Python mllearn\ndef fit(X_mb: MatrixBlock, y_mb: MatrixBlock): Caffe2DMLModel = {\nmloutput = baseFit(X_mb, y_mb, sc)\n@@ -822,6 +826,15 @@ class Caffe2DMLModel(val numClasses: String, val sc: SparkContext, val solver: C\ndef baseEstimator(): BaseSystemMLEstimator = estimator\n// Prediction\n+ def transform(X_file: String): String =\n+ if (estimator.isClassification) {\n+ Caffe2DML.LOG.debug(\"Prediction assuming classification\")\n+ baseTransform(X_file, sc, \"Prob\")\n+ } else {\n+ Caffe2DML.LOG.debug(\"Prediction assuming segmentation\")\n+ val outShape = estimator.getOutputShapeOfLastLayer\n+ baseTransform(X_file, sc, \"Prob\", outShape._1.toInt, outShape._2.toInt, outShape._3.toInt)\n+ }\ndef transform(X: MatrixBlock): MatrixBlock =\nif (estimator.isClassification) {\nCaffe2DML.LOG.debug(\"Prediction assuming classification\")\n@@ -831,6 +844,15 @@ class Caffe2DMLModel(val numClasses: String, val sc: SparkContext, val solver: C\nval outShape = estimator.getOutputShapeOfLastLayer\nbaseTransform(X, sc, \"Prob\", outShape._1.toInt, outShape._2.toInt, outShape._3.toInt)\n}\n+ def transform_probability(X_file: String): String =\n+ if (estimator.isClassification) {\n+ Caffe2DML.LOG.debug(\"Prediction of probability assuming classification\")\n+ baseTransformProbability(X_file, sc, \"Prob\")\n+ } else {\n+ Caffe2DML.LOG.debug(\"Prediction of probability assuming segmentation\")\n+ val outShape = estimator.getOutputShapeOfLastLayer\n+ baseTransformProbability(X_file, sc, \"Prob\", outShape._1.toInt, outShape._2.toInt, outShape._3.toInt)\n+ }\ndef transform_probability(X: MatrixBlock): MatrixBlock =\nif (estimator.isClassification) {\nCaffe2DML.LOG.debug(\"Prediction of probability assuming classification\")\n" }, { "change_type": "MODIFY", "old_path": "src/main/scala/org/apache/sysml/api/ml/BaseSystemMLClassifier.scala", "new_path": "src/main/scala/org/apache/sysml/api/ml/BaseSystemMLClassifier.scala", "diff": "@@ -111,6 +111,11 @@ trait HasRegParam extends Params {\n}\ntrait BaseSystemMLEstimatorOrModel {\n+ def dmlRead(X:String, fileX:String):String = {\n+ val format = if(fileX.endsWith(\".csv\")) \", format=\\\"csv\\\"\" else \"\"\n+ return X + \" = read(\\\"\" + fileX + \"\\\"\" + format + \"); \"\n+ }\n+ def dmlWrite(X:String):String = \"write(\"+ X + \", \\\"output.mtx\\\", format=\\\"binary\\\"); \"\nvar enableGPU: Boolean = false\nvar forceGPU: Boolean = false\nvar explain: Boolean = false\n@@ -215,6 +220,16 @@ trait BaseSystemMLEstimatorModel extends BaseSystemMLEstimatorOrModel {\n}\ntrait BaseSystemMLClassifier extends BaseSystemMLEstimator {\n+ def baseFit(X_file: String, y_file: String, sc: SparkContext): MLResults = {\n+ val isSingleNode = false\n+ val ml = new MLContext(sc)\n+ updateML(ml)\n+ val readScript = dml(dmlRead(\"X\", X_file) + dmlRead(\"y\", y_file)).out(\"X\", \"y\")\n+ val res = ml.execute(readScript)\n+ val ret = getTrainingScript(isSingleNode)\n+ val script = ret._1.in(ret._2, res.getMatrix(\"X\")).in(ret._3, res.getMatrix(\"y\"))\n+ ml.execute(script)\n+ }\ndef baseFit(X_mb: MatrixBlock, y_mb: MatrixBlock, sc: SparkContext): MLResults = {\nval isSingleNode = true\nval ml = new MLContext(sc)\n@@ -242,8 +257,33 @@ trait BaseSystemMLClassifier extends BaseSystemMLEstimator {\ntrait BaseSystemMLClassifierModel extends BaseSystemMLEstimatorModel {\n+ def baseTransform(X_file: String, sc: SparkContext, probVar: String): String = baseTransform(X_file, sc, probVar, -1, 1, 1)\ndef baseTransform(X: MatrixBlock, sc: SparkContext, probVar: String): MatrixBlock = baseTransform(X, sc, probVar, -1, 1, 1)\n+ def baseTransform(X: String, sc: SparkContext, probVar: String, C: Int, H: Int, W: Int): String = {\n+ val Prob = baseTransformHelper(X, sc, probVar, C, H, W)\n+ val script1 = dml(\"source(\\\"nn/util.dml\\\") as util; Prediction = util::predict_class(Prob, C, H, W); \" + dmlWrite(\"Prediction\"))\n+ .in(\"Prob\", Prob)\n+ .in(\"C\", C)\n+ .in(\"H\", H)\n+ .in(\"W\", W)\n+ val ml = new MLContext(sc)\n+ updateML(ml)\n+ ml.execute(script1)\n+ return \"output.mtx\"\n+ }\n+\n+ def baseTransformHelper(X_file: String, sc: SparkContext, probVar: String, C: Int, H: Int, W: Int): Matrix = {\n+ val isSingleNode = true\n+ val ml = new MLContext(sc)\n+ updateML(ml)\n+ val readScript = dml(dmlRead(\"X\", X_file)).out(\"X\")\n+ val res = ml.execute(readScript)\n+ val script = getPredictionScript(isSingleNode)\n+ val modelPredict = ml.execute(script._1.in(script._2, res.getMatrix(\"X\")))\n+ return modelPredict.getMatrix(probVar)\n+ }\n+\ndef baseTransform(X: MatrixBlock, sc: SparkContext, probVar: String, C: Int, H: Int, W: Int): MatrixBlock = {\nval Prob = baseTransformHelper(X, sc, probVar, C, H, W)\nval script1 = dml(\"source(\\\"nn/util.dml\\\") as util; Prediction = util::predict_class(Prob, C, H, W);\")\n@@ -282,9 +322,18 @@ trait BaseSystemMLClassifierModel extends BaseSystemMLEstimatorModel {\ndef baseTransformProbability(X: MatrixBlock, sc: SparkContext, probVar: String): MatrixBlock =\nbaseTransformProbability(X, sc, probVar, -1, 1, 1)\n+ def baseTransformProbability(X: String, sc: SparkContext, probVar: String): String =\n+ baseTransformProbability(X, sc, probVar, -1, 1, 1)\n+\ndef baseTransformProbability(X: MatrixBlock, sc: SparkContext, probVar: String, C: Int, H: Int, W: Int): MatrixBlock =\nreturn baseTransformHelper(X, sc, probVar, C, H, W).toMatrixBlock\n+ def baseTransformProbability(X: String, sc: SparkContext, probVar: String, C: Int, H: Int, W: Int): String = {\n+ val Prob = baseTransformHelper(X, sc, probVar, C, H, W)\n+ (new MLContext(sc)).execute(dml(dmlWrite(\"Prob\")).in(\"Prob\", Prob))\n+ \"output.mtx\"\n+ }\n+\ndef baseTransform(df: ScriptsUtils.SparkDataType, sc: SparkContext, probVar: String, outputProb: Boolean = true): DataFrame =\nbaseTransform(df, sc, probVar, outputProb, -1, 1, 1)\n" }, { "change_type": "MODIFY", "old_path": "src/main/scala/org/apache/sysml/api/ml/BaseSystemMLRegressor.scala", "new_path": "src/main/scala/org/apache/sysml/api/ml/BaseSystemMLRegressor.scala", "diff": "@@ -35,6 +35,17 @@ import org.apache.sysml.api.mlcontext.ScriptFactory._\ntrait BaseSystemMLRegressor extends BaseSystemMLEstimator {\n+ def baseFit(X_file: String, y_file: String, sc: SparkContext): MLResults = {\n+ val isSingleNode = false\n+ val ml = new MLContext(sc)\n+ updateML(ml)\n+ val readScript = dml(dmlRead(\"X\", X_file) + dmlRead(\"y\", y_file)).out(\"X\", \"y\")\n+ val res = ml.execute(readScript)\n+ val ret = getTrainingScript(isSingleNode)\n+ val script = ret._1.in(ret._2, res.getMatrix(\"X\")).in(ret._3, res.getMatrix(\"y\"))\n+ ml.execute(script)\n+ }\n+\ndef baseFit(X_mb: MatrixBlock, y_mb: MatrixBlock, sc: SparkContext): MLResults = {\nval isSingleNode = true\nval ml = new MLContext(sc)\n@@ -61,6 +72,18 @@ trait BaseSystemMLRegressor extends BaseSystemMLEstimator {\ntrait BaseSystemMLRegressorModel extends BaseSystemMLEstimatorModel {\n+ def baseTransform(X_file: String, sc: SparkContext, predictionVar: String): String = {\n+ val isSingleNode = false\n+ val ml = new MLContext(sc)\n+ updateML(ml)\n+ val readScript = dml(dmlRead(\"X\", X_file)).out(\"X\")\n+ val res = ml.execute(readScript)\n+ val script = getPredictionScript(isSingleNode)\n+ val modelPredict = ml.execute(script._1.in(script._2, res.getMatrix(\"X\")))\n+ val writeScript = dml(dmlWrite(\"X\")).in(\"X\", modelPredict.getMatrix(predictionVar))\n+ ml.execute(writeScript)\n+ return \"output.mtx\"\n+ }\ndef baseTransform(X: MatrixBlock, sc: SparkContext, predictionVar: String): MatrixBlock = {\nval isSingleNode = true\nval ml = new MLContext(sc)\n" }, { "change_type": "MODIFY", "old_path": "src/main/scala/org/apache/sysml/api/ml/LinearRegression.scala", "new_path": "src/main/scala/org/apache/sysml/api/ml/LinearRegression.scala", "diff": "@@ -77,6 +77,11 @@ class LinearRegression(override val uid: String, val sc: SparkContext, val solve\n(script, \"X\", \"y\")\n}\n+ def fit(X_file: String, y_file: String): LinearRegressionModel = {\n+ mloutput = baseFit(X_file, y_file, sc)\n+ new LinearRegressionModel(this)\n+ }\n+\ndef fit(X_mb: MatrixBlock, y_mb: MatrixBlock): LinearRegressionModel = {\nmloutput = baseFit(X_mb, y_mb, sc)\nnew LinearRegressionModel(this)\n@@ -102,6 +107,7 @@ class LinearRegressionModel(override val uid: String)(estimator: LinearRegressio\n}\ndef transform_probability(X: MatrixBlock): MatrixBlock = throw new DMLRuntimeException(\"Unsupported method\")\n+ def transform_probability(X_file: String): String = throw new DMLRuntimeException(\"Unsupported method\")\ndef baseEstimator(): BaseSystemMLEstimator = estimator\n@@ -115,7 +121,6 @@ class LinearRegressionModel(override val uid: String)(estimator: LinearRegressio\ndef modelVariables(): List[String] = List[String](\"beta_out\")\ndef transform(df: ScriptsUtils.SparkDataType): DataFrame = baseTransform(df, sc, \"means\")\n-\ndef transform(X: MatrixBlock): MatrixBlock = baseTransform(X, sc, \"means\")\n-\n+ def transform(X_file: String): String = baseTransform(X_file, sc, \"means\")\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/scala/org/apache/sysml/api/ml/LogisticRegression.scala", "new_path": "src/main/scala/org/apache/sysml/api/ml/LogisticRegression.scala", "diff": "@@ -60,6 +60,11 @@ class LogisticRegression(override val uid: String, val sc: SparkContext)\ncopyValues(that, extra)\n}\n+ def fit(X_file: String, y_file: String): LogisticRegressionModel = {\n+ mloutput = baseFit(X_file, y_file, sc)\n+ new LogisticRegressionModel(this)\n+ }\n+\n// Note: will update the y_mb as this will be called by Python mllearn\ndef fit(X_mb: MatrixBlock, y_mb: MatrixBlock): LogisticRegressionModel = {\nmloutput = baseFit(X_mb, y_mb, sc)\n@@ -116,7 +121,9 @@ class LogisticRegressionModel(override val uid: String)(estimator: LogisticRegre\ndef modelVariables(): List[String] = List[String](\"B_out\")\ndef transform(X: MatrixBlock): MatrixBlock = baseTransform(X, sc, \"means\")\n+ def transform(X: String): String = baseTransform(X, sc, \"means\")\ndef transform_probability(X: MatrixBlock): MatrixBlock = baseTransformProbability(X, sc, \"means\")\n+ def transform_probability(X: String): String = baseTransformProbability(X, sc, \"means\")\ndef transform(df: ScriptsUtils.SparkDataType): DataFrame = baseTransform(df, sc, \"means\")\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/scala/org/apache/sysml/api/ml/NaiveBayes.scala", "new_path": "src/main/scala/org/apache/sysml/api/ml/NaiveBayes.scala", "diff": "@@ -44,6 +44,11 @@ class NaiveBayes(override val uid: String, val sc: SparkContext) extends Estimat\n}\ndef setLaplace(value: Double) = set(laplace, value)\n+ def fit(X_file: String, y_file: String): NaiveBayesModel = {\n+ mloutput = baseFit(X_file, y_file, sc)\n+ new NaiveBayesModel(this)\n+ }\n+\n// Note: will update the y_mb as this will be called by Python mllearn\ndef fit(X_mb: MatrixBlock, y_mb: MatrixBlock): NaiveBayesModel = {\nmloutput = baseFit(X_mb, y_mb, sc)\n@@ -108,7 +113,9 @@ class NaiveBayesModel(override val uid: String)(estimator: NaiveBayes, val sc: S\ndef baseEstimator(): BaseSystemMLEstimator = estimator\ndef transform(X: MatrixBlock): MatrixBlock = baseTransform(X, sc, \"probs\")\n+ def transform(X: String): String = baseTransform(X, sc, \"probs\")\ndef transform_probability(X: MatrixBlock): MatrixBlock = baseTransformProbability(X, sc, \"probs\")\n+ def transform_probability(X: String): String = baseTransformProbability(X, sc, \"probs\")\ndef transform(df: ScriptsUtils.SparkDataType): DataFrame = baseTransform(df, sc, \"probs\")\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/scala/org/apache/sysml/api/ml/SVM.scala", "new_path": "src/main/scala/org/apache/sysml/api/ml/SVM.scala", "diff": "@@ -70,6 +70,11 @@ class SVM(override val uid: String, val sc: SparkContext, val isMultiClass: Bool\n(script, \"X\", \"Y\")\n}\n+ def fit(X_file: String, y_file: String): SVMModel = {\n+ mloutput = baseFit(X_file, y_file, sc)\n+ new SVMModel(this, isMultiClass)\n+ }\n+\n// Note: will update the y_mb as this will be called by Python mllearn\ndef fit(X_mb: MatrixBlock, y_mb: MatrixBlock): SVMModel = {\nmloutput = baseFit(X_mb, y_mb, sc)\n@@ -121,5 +126,7 @@ class SVMModel(override val uid: String)(estimator: SVM, val sc: SparkContext, v\ndef transform(X: MatrixBlock): MatrixBlock = baseTransform(X, sc, \"scores\")\ndef transform_probability(X: MatrixBlock): MatrixBlock = baseTransformProbability(X, sc, \"scores\")\n+ def transform(X: String): String = baseTransform(X, sc, \"scores\")\n+ def transform_probability(X: String): String = baseTransformProbability(X, sc, \"scores\")\ndef transform(df: ScriptsUtils.SparkDataType): DataFrame = baseTransform(df, sc, \"scores\")\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-445] Allow users to pass the file paths to the binary blocked, csv and ijv datasets to mllearn classes. - This allows the advance users who already have data materialized in binary blocked formats to avoid conversion overhead. - Also, this facility is useful for benchmarking the performance of Keras2DML and Caffe2DML.
49,698
03.03.2018 20:13:38
28,800
162a5b0f6441942c478a8061a968fec1a85410bf
Extended sparse block validation for COO format Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCOO.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCOO.java", "diff": "@@ -194,7 +194,50 @@ public class SparseBlockCOO extends SparseBlock\n@Override\npublic boolean checkValidity(int rlen, int clen, long nnz, boolean strict) {\n- //empty implementation\n+ //1. correct meta data\n+ if(rlen < 0 || clen < 0) {\n+ throw new RuntimeException(\"Invalid block dimensions: \"+rlen+\" \"+clen);\n+ }\n+\n+ //2. correct array lengths\n+ if(_size != nnz && _cindexes.length < nnz && _rindexes.length < nnz && _values.length < nnz) {\n+ throw new RuntimeException(\"Incorrect array lengths.\");\n+ }\n+\n+ //3.1. sort order of row indices\n+ for( int i=1; i<=nnz; i++ ) {\n+ if(_rindexes[i] < _rindexes[i-1])\n+ throw new RuntimeException(\"Wrong sorted order of row indices\");\n+ }\n+\n+ //3.2. sorted values wrt to col indexes wrt to a given row index\n+ for( int i=0; i<rlen; i++ ) {\n+ int apos = pos(i);\n+ int alen = size(i);\n+ for(int k=apos+i; k<apos+alen; k++)\n+ if( _cindexes[k+1] >= _cindexes[k] )\n+ throw new RuntimeException(\"Wrong sparse row ordering: \"\n+ + k + \" \"+_cindexes[k-1]+\" \"+_cindexes[k]);\n+ for( int k=apos; k<apos+alen; k++ )\n+ if(_values[k] == 0)\n+ throw new RuntimeException(\"Wrong sparse row: zero at \"\n+ + k + \" at col index \" + _cindexes[k]);\n+ }\n+\n+ //4. non-existing zero values\n+ for( int i=0; i<_size; i++ ) {\n+ if( _values[i] == 0)\n+ throw new RuntimeException(\"The values array should not contain zeros.\"\n+ + \" The \" + i + \"th value is \"+_values[i]);\n+ }\n+\n+ //5. a capacity that is no larger than nnz times the resize factor\n+ int capacity = _values.length;\n+ if( capacity > nnz*RESIZE_FACTOR1 ) {\n+ throw new RuntimeException(\"Capacity is larger than the nnz times a resize factor.\"\n+ + \" Current size: \"+capacity+ \", while Expected size:\"+nnz*RESIZE_FACTOR1);\n+ }\n+\nreturn true;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2130] Extended sparse block validation for COO format Closes #735.
49,738
04.03.2018 13:13:28
28,800
bc097fcd7bcfeb90bce208c448a8610694a73c71
[HOTFIX] Update function call tests wrt UDF support in expressions
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/misc/InvalidFunctionAssignmentTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/misc/InvalidFunctionAssignmentTest.java", "diff": "@@ -25,9 +25,6 @@ import org.apache.sysml.api.DMLException;\nimport org.apache.sysml.test.integration.AutomatedTestBase;\nimport org.apache.sysml.test.integration.TestConfiguration;\n-/**\n- *\n- */\npublic class InvalidFunctionAssignmentTest extends AutomatedTestBase\n{\nprivate final static String TEST_DIR = \"functions/misc/\";\n@@ -52,7 +49,8 @@ public class InvalidFunctionAssignmentTest extends AutomatedTestBase\n@Test\npublic void testInvalidFunctionAssignmentInlined() {\n- runTest( TEST_NAME2, true );\n+ //MB: we now support UDFs in expressions and hence it's valid\n+ runTest( TEST_NAME2, false );\n}\n@Test\n@@ -62,23 +60,16 @@ public class InvalidFunctionAssignmentTest extends AutomatedTestBase\n@Test\npublic void testInvalidFunctionAssignment() {\n- runTest( TEST_NAME4, true );\n+ //MB: we now support UDFs in expressions and hence it's valid\n+ runTest( TEST_NAME4, false );\n}\n- /**\n- *\n- * @param testName\n- */\n- private void runTest( String testName, boolean exceptionExpected )\n- {\n+ private void runTest( String testName, boolean exceptionExpected ) {\nTestConfiguration config = getTestConfiguration(testName);\nloadTestConfiguration(config);\n-\nString HOME = SCRIPT_DIR + TEST_DIR;\nfullDMLScriptName = HOME + testName + \".dml\";\nprogramArgs = new String[]{};\n-\n- //run tests\nrunTest(true, exceptionExpected, DMLException.class, -1);\n}\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Update function call tests wrt UDF support in expressions
49,698
04.03.2018 22:51:29
28,800
cf556f2070b81625c928a9540a9cd10e924df714
Additional tests for external UDFs in expressions Closes
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/misc/FunctionInExpressionTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/misc/FunctionInExpressionTest.java", "diff": "@@ -33,6 +33,8 @@ public class FunctionInExpressionTest extends AutomatedTestBase\nprivate final static String TEST_NAME2 = \"FunInExpression2\";\nprivate final static String TEST_NAME3 = \"FunInExpression3\";\nprivate final static String TEST_NAME4 = \"FunInExpression4\";\n+ private final static String TEST_NAME5 = \"FunInExpression5\";\n+ private final static String TEST_NAME6 = \"FunInExpression6\";\nprivate final static String TEST_DIR = \"functions/misc/\";\nprivate final static String TEST_CLASS_DIR = TEST_DIR + FunctionInExpressionTest.class.getSimpleName() + \"/\";\n@@ -44,6 +46,8 @@ public class FunctionInExpressionTest extends AutomatedTestBase\naddTestConfiguration( TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] { \"R\" }) );\naddTestConfiguration( TEST_NAME3, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME3, new String[] { \"R\" }) );\naddTestConfiguration( TEST_NAME4, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME4, new String[] { \"R\" }) );\n+ addTestConfiguration( TEST_NAME5, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME5, new String[] { \"R\" }) );\n+ addTestConfiguration( TEST_NAME6, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME6, new String[] { \"R\" }) );\n}\n@Test\n@@ -66,6 +70,16 @@ public class FunctionInExpressionTest extends AutomatedTestBase\nrunFunInExpressionTest( TEST_NAME4 );\n}\n+ @Test\n+ public void testFunInExpression5() {\n+ runFunInExpressionTest( TEST_NAME5 );\n+ }\n+\n+ @Test\n+ public void testFunInExpression6() {\n+ runFunInExpressionTest( TEST_NAME6 );\n+ }\n+\nprivate void runFunInExpressionTest( String testName )\n{\nTestConfiguration config = getTestConfiguration(testName);\n@@ -83,6 +97,6 @@ public class FunctionInExpressionTest extends AutomatedTestBase\n//compare results\ndouble val = readDMLMatrixFromHDFS(\"R\").get(new CellIndex(1,1));\n- Assert.assertTrue(\"Wrong result: 7 vs \"+val, Math.abs(val-7)<Math.pow(10, -14));\n+ Assert.assertTrue(\"Wrong result: 7 vs \"+val, Math.abs(val-7)<Math.pow(10, -13));\n}\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/misc/FunInExpression5.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+orderExternal = externalFunction(Matrix[Double] A, Integer col, Boolean desc) return (Matrix[Double] B)\n+ implemented in (classname=\"org.apache.sysml.udf.lib.OrderWrapper\",exectype=\"mem\")\n+\n+foo = function( Matrix[Double] A ) return (Matrix[Double] B) {\n+ for( i in 1:ncol(A) ) {\n+ B = orderExternal(A, i, TRUE);\n+ }\n+}\n+\n+A = matrix( 0.07, rows=10, cols=10 );\n+R = foo(A) * foo(A) + 7;\n+R = as.matrix( sum( sqrt(R-7) ) );\n+\n+write( R, $1 ); #ordered input\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/misc/FunInExpression6.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+orderExternal = externalFunction(Matrix[Double] A, Integer col, Boolean desc) return (Matrix[Double] B)\n+ implemented in (classname=\"org.apache.sysml.udf.lib.OrderWrapper\",exectype=\"mem\")\n+\n+A = matrix( 0.07, rows=10, cols=10 );\n+R = orderExternal(A*A, 7, TRUE) + 7;\n+R = as.matrix( sum( sqrt(R-7) ) );\n+\n+write( R, $1 ); #ordered input\n\\ No newline at end of file\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-1444] Additional tests for external UDFs in expressions Closes #727.
49,738
05.03.2018 13:12:59
28,800
727e69e2893fc376d721915dff4831261a6d90f8
[MINOR] Cleanup unnecessary indirections in dml/pydml parsers
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/common/CommonSyntacticValidator.java", "new_path": "src/main/java/org/apache/sysml/parser/common/CommonSyntacticValidator.java", "diff": "@@ -573,63 +573,51 @@ public abstract class CommonSyntacticValidator {\n*/\nprotected abstract Expression handleLanguageSpecificFunction(ParserRuleContext ctx, String functionName, ArrayList<ParameterExpression> paramExpressions);\n- /** Checks for builtin functions and does Action 'f'.\n- * <p>\n- * Constructs the\n- * appropriate {@link AssignmentStatement} from\n- * {@link CommonSyntacticValidator#functionCallAssignmentStatementHelper(ParserRuleContext, Set, Set, Expression, StatementInfo, Token, Token, String, String, ArrayList, boolean)}\n- * or Assign to {@link Expression} from\n- * DmlSyntacticValidator's exitBuiltinFunctionExpression(BuiltinFunctionExpressionContext).\n- * </p>\n+ /** Creates a builtin function expression.\n*\n* @param ctx antlr rule context\n* @param functionName Name of the builtin function\n* @param paramExpressions Array of parameter names and values\n- * @param f action to perform\n- * @return true if a builtin function was found\n+ * @return expression if found otherwise null\n*/\n- protected boolean buildForBuiltInFunction(ParserRuleContext ctx, String functionName, ArrayList<ParameterExpression> paramExpressions, Action f) {\n+ protected Expression buildForBuiltInFunction(ParserRuleContext ctx, String functionName, ArrayList<ParameterExpression> paramExpressions) {\n// In global namespace, so it can be a builtin function\n// Double verification: verify passed function name is a (non-parameterized) built-in function.\ntry {\nif (functions.contains(functionName)) {\n// It is a user function definition (which takes precedence if name same as built-in)\n- return false;\n+ return null;\n}\nExpression lsf = handleLanguageSpecificFunction(ctx, functionName, paramExpressions);\nif (lsf != null) {\nsetFileLineColumn(lsf, ctx);\n- f.execute(lsf);\n- return true;\n+ return lsf;\n}\nBuiltinFunctionExpression bife = BuiltinFunctionExpression.getBuiltinFunctionExpression(ctx, functionName, paramExpressions, currentFile);\nif (bife != null) {\n// It is a builtin function\n- f.execute(bife);\n- return true;\n+ return bife;\n}\nParameterizedBuiltinFunctionExpression pbife = ParameterizedBuiltinFunctionExpression\n.getParamBuiltinFunctionExpression(ctx, functionName, paramExpressions, currentFile);\nif (pbife != null){\n// It is a parameterized builtin function\n- f.execute(pbife);\n- return true;\n+ return pbife;\n}\n// built-in read, rand ...\nDataExpression dbife = DataExpression.getDataExpression(ctx, functionName, paramExpressions, currentFile, errorListener);\nif (dbife != null){\n- f.execute(dbife);\n- return true;\n+ return dbife;\n+ }\n}\n- } catch(Exception e) {\n+ catch(Exception e) {\nnotifyErrorListeners(\"unable to process builtin function expression \" + functionName + \":\" + e.getMessage(), ctx.start);\n- return true;\n}\n- return false;\n+ return null;\n}\n@@ -670,14 +658,12 @@ public abstract class CommonSyntacticValidator {\n// For builtin functions with LHS\nif(namespace.equals(DMLProgram.DEFAULT_NAMESPACE) && !functions.contains(functionName)){\n- final DataIdentifier ftarget = target;\n- Action f = new Action() {\n- @Override public void execute(Expression e) { setAssignmentStatement(ctx, info , ftarget, e); }\n- };\n- boolean validBIF = buildForBuiltInFunction(ctx, functionName, paramExpression, f);\n- if (validBIF)\n+ Expression e = buildForBuiltInFunction(ctx, functionName, paramExpression);\n+ if( e != null ) {\n+ setAssignmentStatement(ctx, info, target, e);\nreturn;\n}\n+ }\n// handle user-defined functions\nsetAssignmentStatement(ctx, info, target,\n@@ -695,14 +681,6 @@ public abstract class CommonSyntacticValidator {\nreturn functCall;\n}\n- /**\n- * To allow for different actions in\n- * {@link CommonSyntacticValidator#functionCallAssignmentStatementHelper(ParserRuleContext, Set, Set, Expression, StatementInfo, Token, Token, String, String, ArrayList, boolean)}\n- */\n- public static interface Action {\n- public void execute(Expression e);\n- }\n-\nprotected void setMultiAssignmentStatement(ArrayList<DataIdentifier> target, Expression expression, ParserRuleContext ctx, StatementInfo info) {\ninfo.stmt = new MultiAssignmentStatement(target, expression);\ninfo.stmt.setCtxValuesAndFilename(ctx, currentFile);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/dml/DmlSyntacticValidator.java", "new_path": "src/main/java/org/apache/sysml/parser/dml/DmlSyntacticValidator.java", "diff": "@@ -530,18 +530,14 @@ public class DmlSyntacticValidator extends CommonSyntacticValidator implements D\nfunctionName = convertedSyntax.functionName;\nparamExpression = convertedSyntax.paramExpression;\n}\n- final ExpressionInfo info = ctx.info;\n- Action f = new Action() {\n- @Override public void execute(Expression e) { info.expr = e; }\n- };\n// handle built-in functions\n- boolean validBIF = buildForBuiltInFunction(ctx, functionName, paramExpression, f);\n- if (validBIF)\n+ ctx.info.expr = buildForBuiltInFunction(ctx, functionName, paramExpression);\n+ if( ctx.info.expr != null )\nreturn;\n// handle user-defined functions\n- info.expr = createFunctionCall(ctx, namespace, functionName, paramExpression);\n+ ctx.info.expr = createFunctionCall(ctx, namespace, functionName, paramExpression);\n}\n@@ -583,14 +579,12 @@ public class DmlSyntacticValidator extends CommonSyntacticValidator implements D\n}\nif(namespace.equals(DMLProgram.DEFAULT_NAMESPACE)) {\n- final FunctionCallMultiAssignmentStatementContext fctx = ctx;\n- Action f = new Action() {\n- @Override public void execute(Expression e) { setMultiAssignmentStatement(targetList, e, fctx, fctx.info); }\n- };\n- boolean validBIF = buildForBuiltInFunction(ctx, functionName, paramExpression, f);\n- if (validBIF)\n+ Expression e = buildForBuiltInFunction(ctx, functionName, paramExpression);\n+ if( e != null ) {\n+ setMultiAssignmentStatement(targetList, e, ctx, ctx.info);\nreturn;\n}\n+ }\n// Override default namespace for imported non-built-in function\nString inferNamespace = (sourceNamespace != null && sourceNamespace.length() > 0 && DMLProgram.DEFAULT_NAMESPACE.equals(namespace)) ? sourceNamespace : namespace;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/pydml/PydmlSyntacticValidator.java", "new_path": "src/main/java/org/apache/sysml/parser/pydml/PydmlSyntacticValidator.java", "diff": "@@ -1145,18 +1145,13 @@ public class PydmlSyntacticValidator extends CommonSyntacticValidator implements\nparamExpression = convertedSyntax.paramExpression;\n}\n- final ExpressionInfo info = ctx.info;\n- Action f = new Action() {\n- @Override public void execute(Expression e) { info.expr = e; }\n- };\n-\n//handle builtin functions\n- boolean validBIF = buildForBuiltInFunction(ctx, functionName, paramExpression, f);\n- if (validBIF)\n+ ctx.info.expr= buildForBuiltInFunction(ctx, functionName, paramExpression);\n+ if( ctx.info.expr != null )\nreturn;\n// handle user-defined functions\n- info.expr = createFunctionCall(ctx, namespace, functionName, paramExpression);\n+ ctx.info.expr = createFunctionCall(ctx, namespace, functionName, paramExpression);\n}\n@Override\n@@ -1199,14 +1194,12 @@ public class PydmlSyntacticValidator extends CommonSyntacticValidator implements\n}\nif(namespace.equals(DMLProgram.DEFAULT_NAMESPACE)) {\n- final FunctionCallMultiAssignmentStatementContext fctx = ctx;\n- Action f = new Action() {\n- @Override public void execute(Expression e) { setMultiAssignmentStatement(targetList, e, fctx, fctx.info); }\n- };\n- boolean validBIF = buildForBuiltInFunction(ctx, functionName, paramExpression, f);\n- if (validBIF)\n+ Expression e = buildForBuiltInFunction(ctx, functionName, paramExpression);\n+ if( e != null ) {\n+ setMultiAssignmentStatement(targetList, e, ctx, ctx.info);\nreturn;\n}\n+ }\n// Override default namespace for imported non-built-in function\nString inferNamespace = (sourceNamespace != null && sourceNamespace.length() > 0 && DMLProgram.DEFAULT_NAMESPACE.equals(namespace)) ? sourceNamespace : namespace;\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Cleanup unnecessary indirections in dml/pydml parsers
49,738
05.03.2018 15:07:18
28,800
63be18a840f4b898c5e91aa2f3ff2efd02690a97
Simplify nn-lstm layer with UDFs in expressions
[ { "change_type": "MODIFY", "old_path": "scripts/nn/layers/lstm.dml", "new_path": "scripts/nn/layers/lstm.dml", "diff": "@@ -90,15 +90,12 @@ forward = function(matrix[double] X, matrix[double] W, matrix[double] b, int T,\nX_t = X[,(t-1)*D+1:t*D] # shape (N, D)\ninput = cbind(X_t, out_prev) # shape (N, D+M)\nifog = input %*% W + b # input, forget, output, and g gates; shape (N, 4M)\n- tmp = sigmoid::forward(ifog[,1:3*M]) # i,f,o gates squashed with sigmoid\n- ifog[,1:3*M] = tmp\n- tmp = tanh::forward(ifog[,3*M+1:4*M]) # g gate squashed with tanh\n- ifog[,3*M+1:4*M] = tmp\n+ ifog[,1:3*M] = sigmoid::forward(ifog[,1:3*M]) # i,f,o gates squashed with sigmoid\n+ ifog[,3*M+1:4*M] = tanh::forward(ifog[,3*M+1:4*M]) # g gate squashed with tanh\n# c_t = f*prev_c + i*g\nc = ifog[,M+1:2*M]*c_prev + ifog[,1:M]*ifog[,3*M+1:4*M] # shape (N, M)\n# out_t = o*tanh(c)\n- tmp = tanh::forward(c)\n- out_t = ifog[,2*M+1:3*M] * tmp # shape (N, M)\n+ out_t = ifog[,2*M+1:3*M] * tanh::forward(c) # shape (N, M)\n# store\nif (return_sequences) {\n@@ -202,10 +199,8 @@ backward = function(matrix[double] dout, matrix[double] dc,\no = ifog[,2*M+1:3*M] # output gate, shape (N, M)\ng = ifog[,3*M+1:4*M] # g gate, shape (N, M)\n- tmp = tanh::backward(dout_t, ct)\n- dct = dct + o*tmp # shape (N, M)\n- tmp = tanh::forward(ct)\n- do = tmp * dout_t # output gate, shape (N, M)\n+ dct = dct + o*tanh::backward(dout_t, ct) # shape (N, M)\n+ do = tanh::forward(ct) * dout_t # output gate, shape (N, M)\ndf = c_prev * dct # forget gate, shape (N, M)\ndc_prev = f * dct # shape (N, M)\ndi = g * dct # input gate, shape (N, M)\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-1444] Simplify nn-lstm layer with UDFs in expressions
49,698
07.03.2018 14:38:16
28,800
52b1b5716a5f6b157a9b868db8104a34d6c3d3fb
Test for JMLC scalar string value types Uncomment test for automatically treating scalar strings as having string as the value type. Closes
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/jmlc/JMLCInputOutputTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/jmlc/JMLCInputOutputTest.java", "diff": "@@ -108,23 +108,21 @@ public class JMLCInputOutputTest extends AutomatedTestBase {\nconn.close();\n}\n- // See: https://issues.apache.org/jira/browse/SYSTEMML-658\n- // @Test\n- // public void testScalarInputString() throws IOException, DMLException {\n- // Connection conn = new Connection();\n- // String str = conn.readScript(baseDirectory + File.separator +\n- // \"scalar-input.dml\");\n- // PreparedScript script = conn.prepareScript(str, new String[] {\n- // \"inScalar1\", \"inScalar2\" }, new String[] {},\n- // false);\n- // String inScalar1 = \"hello\";\n- // String inScalar2 = \"goodbye\";\n- // script.setScalar(\"inScalar1\", inScalar1);\n- // script.setScalar(\"inScalar2\", inScalar2);\n- //\n- // setExpectedStdOut(\"total:hellogoodbye\");\n- // script.executeScript();\n- // }\n+ @Test\n+ public void testScalarInputString() throws IOException, DMLException {\n+ Connection conn = new Connection();\n+ String str = conn.readScript(baseDirectory + File.separator + \"scalar-input.dml\");\n+ PreparedScript script = conn.prepareScript(str, new String[] { \"inScalar1\", \"inScalar2\" }, new String[] {},\n+ false);\n+ String inScalar1 = \"Plant\";\n+ String inScalar2 = \" Trees\";\n+ script.setScalar(\"inScalar1\", inScalar1);\n+ script.setScalar(\"inScalar2\", inScalar2);\n+\n+ setExpectedStdOut(\"total:Plant Trees\");\n+ script.executeScript();\n+ conn.close();\n+ }\n@Test\npublic void testScalarInputStringExplicitValueType() throws IOException, DMLException {\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-658] Test for JMLC scalar string value types Uncomment test for automatically treating scalar strings as having string as the value type. Closes #739.
49,738
08.03.2018 18:25:43
28,800
437e9d6618b197f07a70b35df32dae5b6bb301a4
Performance spark cpmm (set join parallelism) This patch makes a minor performance improvement to spark cpmm operations by computing and setting the preferred degree of parallelism according to data and cluster characteristics. Since cpmm anyway changes keys before the join, the changed number of partitions does not affect a potentially exiting partitioner.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CpmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CpmmSPInstruction.java", "diff": "@@ -34,6 +34,8 @@ import org.apache.sysml.runtime.instructions.InstructionUtils;\nimport org.apache.sysml.runtime.instructions.cp.CPOperand;\nimport org.apache.sysml.runtime.instructions.spark.functions.FilterNonEmptyBlocksFunction;\nimport org.apache.sysml.runtime.instructions.spark.utils.RDDAggregateUtils;\n+import org.apache.sysml.runtime.instructions.spark.utils.SparkUtils;\n+import org.apache.sysml.runtime.matrix.MatrixCharacteristics;\nimport org.apache.sysml.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysml.runtime.matrix.data.MatrixIndexes;\nimport org.apache.sysml.runtime.matrix.mapred.IndexedMatrixValue;\n@@ -85,17 +87,24 @@ public class CpmmSPInstruction extends BinarySPInstruction {\n//get rdd inputs\nJavaPairRDD<MatrixIndexes,MatrixBlock> in1 = sec.getBinaryBlockRDDHandleForVariable(input1.getName());\nJavaPairRDD<MatrixIndexes,MatrixBlock> in2 = sec.getBinaryBlockRDDHandleForVariable(input2.getName());\n+ MatrixCharacteristics mc1 = sec.getMatrixCharacteristics(input1.getName());\n+ MatrixCharacteristics mc2 = sec.getMatrixCharacteristics(input2.getName());\n+\nif( _aggtype == SparkAggType.SINGLE_BLOCK ) {\n//prune empty blocks of ultra-sparse matrices\nin1 = in1.filter(new FilterNonEmptyBlocksFunction());\nin2 = in2.filter(new FilterNonEmptyBlocksFunction());\n}\n+ //compute preferred join degree of parallelism\n+ int numPreferred = getPreferredParJoin(mc1, mc2, in1.getNumPartitions(), in2.getNumPartitions());\n+ int numPartJoin = Math.min(getMaxParJoin(mc1, mc2), numPreferred);\n+\n//process core cpmm matrix multiply\nJavaPairRDD<Long, IndexedMatrixValue> tmp1 = in1.mapToPair(new CpmmIndexFunction(true));\nJavaPairRDD<Long, IndexedMatrixValue> tmp2 = in2.mapToPair(new CpmmIndexFunction(false));\nJavaPairRDD<MatrixIndexes,MatrixBlock> out = tmp1\n- .join(tmp2) // join over common dimension\n+ .join(tmp2, numPartJoin) // join over common dimension\n.mapToPair(new CpmmMultiplyFunction()); // compute block multiplications\n//process cpmm aggregation and handle outputs\n@@ -121,6 +130,22 @@ public class CpmmSPInstruction extends BinarySPInstruction {\n}\n}\n+ private static int getPreferredParJoin(MatrixCharacteristics mc1, MatrixCharacteristics mc2, int numPar1, int numPar2) {\n+ int defPar = SparkExecutionContext.getDefaultParallelism(true);\n+ int maxParIn = Math.max(numPar1, numPar2);\n+ int maxSizeIn = SparkUtils.getNumPreferredPartitions(mc1) +\n+ SparkUtils.getNumPreferredPartitions(mc2);\n+ int tmp = (mc1.dimsKnown(true) && mc2.dimsKnown(true)) ?\n+ Math.max(maxSizeIn, maxParIn) : maxParIn;\n+ return (tmp > defPar/2) ? Math.max(tmp, defPar) : tmp;\n+ }\n+\n+ private static int getMaxParJoin(MatrixCharacteristics mc1, MatrixCharacteristics mc2) {\n+ return mc1.colsKnown() ? (int)mc1.getNumColBlocks() :\n+ mc2.rowsKnown() ? (int)mc2.getNumRowBlocks() :\n+ Integer.MAX_VALUE;\n+ }\n+\nprivate static class CpmmIndexFunction implements PairFunction<Tuple2<MatrixIndexes, MatrixBlock>, Long, IndexedMatrixValue>\n{\nprivate static final long serialVersionUID = -1187183128301671162L;\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2177] Performance spark cpmm (set join parallelism) This patch makes a minor performance improvement to spark cpmm operations by computing and setting the preferred degree of parallelism according to data and cluster characteristics. Since cpmm anyway changes keys before the join, the changed number of partitions does not affect a potentially exiting partitioner.
49,698
08.03.2018 20:34:59
28,800
a26957e16f7e73181deea0e42b86701ee443cf96
Extended sparse block validation for MCSR format Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockMCSR.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockMCSR.java", "diff": "@@ -160,7 +160,38 @@ public class SparseBlockMCSR extends SparseBlock\n@Override\npublic boolean checkValidity(int rlen, int clen, long nnz, boolean strict) {\n- // empty implementation\n+\n+ //1. Correct meta data\n+ if( rlen < 0 || clen < 0 )\n+ throw new RuntimeException(\"Invalid block dimensions: (\"+rlen+\", \"+clen+\").\");\n+\n+ //2. Correct array lengths\n+ if( size() < nnz )\n+ throw new RuntimeException(\"Incorrect size: \"+size()+\" (expected: \"+nnz+\").\");\n+\n+ //3. Sorted column indices per row\n+ for( int i=0; i<rlen; i++ ) {\n+ if( isEmpty(i) ) continue;\n+ int apos = pos(i);\n+ int alen = size(i);\n+ int[] aix = indexes(i);\n+ double[] avals = values(i);\n+ for (int k = apos + 1; k < apos + alen; k++) {\n+ if (aix[k-1] >= aix[k])\n+ throw new RuntimeException(\"Wrong sparse row ordering, at row: \"\n+ + k + \"with \" + aix[k-1] + \">=\" + aix[k]);\n+ if (avals[k] == 0)\n+ throw new RuntimeException(\"The values are expected to be non zeros \"\n+ + \"but zero at row: \"+ i + \", col pos: \" + k);\n+ }\n+ }\n+\n+ //3. A capacity that is no larger than nnz times resize factor\n+ for( int i=0; i<rlen; i++ )\n+ if( !isEmpty(i) && values(i).length > nnz*RESIZE_FACTOR1 )\n+ throw new RuntimeException(\"The capacity is larger than nnz times a resize factor(=2). \"\n+ + \"Actual length = \" + values(i).length+\", should not exceed \"+nnz*RESIZE_FACTOR1);\n+\nreturn true;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2130] Extended sparse block validation for MCSR format Closes #738.
49,737
08.03.2018 23:11:10
28,800
91b040d60cf8bf38000871747801ca7247326869
Add an ELU activation function. This adds an "exponential linear unit" (ELU) to the `nn` deep learning library. Closes
[ { "change_type": "MODIFY", "old_path": "scripts/nn/test/grad_check.dml", "new_path": "scripts/nn/test/grad_check.dml", "diff": "@@ -57,6 +57,7 @@ source(\"nn/test/conv2d_simple.dml\") as conv2d_simple\nsource(\"nn/test/max_pool2d_simple.dml\") as max_pool2d_simple\nsource(\"nn/test/util.dml\") as test_util\nsource(\"nn/util.dml\") as util\n+source(\"nn/layers/elu.dml\") as elu\naffine = function() {\n/*\n@@ -2458,3 +2459,42 @@ two_layer_affine_l2_net_backward = function(matrix[double] X, matrix[double] y,\n[dX, dW1, db1] = affine::backward(dhout, X, W1, b1)\n}\n+elu = function() {\n+ /*\n+ * Gradient check for ELU nonlinearity\n+ * layer.\n+ */\n+ print(\"Grad checking ELU nonlinearity layer with L2 loss.\")\n+ # Generate data\n+ N = 3 # num examples\n+ M = 10 # num neurons\n+\n+ X = rand(rows=N, cols=M)\n+ y = rand(rows=N, cols=M)\n+\n+ out = elu::forward(X, 1)\n+ dout = l2_loss::backward(out, y)\n+ dX = elu::backward(dout, X, 1)\n+\n+ # Grad check\n+ h = 1e-6\n+ print(\" - Grad checking X.\")\n+ for (i in 1:nrow(X)) {\n+ for (j in 1:ncol(X)) {\n+ # Compute numerical derivative\n+ old = as.scalar(X[i,j])\n+ X[i,j] = old - h\n+ outmh = elu::forward(X, 1)\n+ lossmh = l2_loss::forward(outmh, y)\n+ X[i,j] = old + h\n+ outph = elu::forward(X, 1)\n+ lossph = l2_loss::forward(outph, y)\n+ X[i,j] = old # reset\n+ dX_num = (lossph-lossmh) / (2*h) # numerical derivative\n+\n+ # Check error\n+ rel_error = test_util::check_rel_grad_error(as.scalar(dX[i,j]), dX_num, lossph, lossmh)\n+ }\n+ }\n+}\n+\n" }, { "change_type": "MODIFY", "old_path": "scripts/nn/test/run_tests.dml", "new_path": "scripts/nn/test/run_tests.dml", "diff": "@@ -51,6 +51,7 @@ grad_check::conv2d_depthwise()\ngrad_check::conv2d_transpose()\ngrad_check::conv2d_transpose_depthwise()\ngrad_check::dropout()\n+grad_check::elu()\ngrad_check::fm()\ngrad_check::lstm()\ngrad_check::max_pool2d()\n@@ -99,6 +100,7 @@ test::conv2d_transpose()\ntest::conv2d_transpose_depthwise()\ntest::cross_entropy_loss()\ntest::cross_entropy_loss2d()\n+test::elu()\ntest::im2col()\ntest::max_pool2d()\ntest::padding()\n" }, { "change_type": "MODIFY", "old_path": "scripts/nn/test/test.dml", "new_path": "scripts/nn/test/test.dml", "diff": "@@ -40,6 +40,8 @@ source(\"nn/test/max_pool2d_simple.dml\") as max_pool2d_simple\nsource(\"nn/test/util.dml\") as test_util\nsource(\"nn/util.dml\") as util\nsource(\"nn/layers/sigmoid.dml\") as sigmoid\n+source(\"nn/layers/elu.dml\") as elu\n+\nbatch_norm1d = function() {\n/*\n@@ -1093,3 +1095,34 @@ softmax2d = function() {\n}\n}\n+elu = function() {\n+ /*\n+ * Test for ELU function.\n+ */\n+ print(\"Testing ELU function.\")\n+\n+ X = matrix(\"0.3923 -0.2236 -0.3195 -1.2050 1.0445 -0.6332 0.5731 0.5409 -0.3919 -1.0427\", rows = 10, cols = 1)\n+\n+ print(\" - Testing forward\")\n+ out = elu::forward(X, 1)\n+ out_ref = matrix(\"0.3923 -0.2003 -0.2735 -0.7003 1.0445 -0.4691 0.5731 0.5409 -0.3242 -0.6475\", rows = 10, cols = 1)\n+\n+ for (i in 1:nrow(out)) {\n+ for(j in 1:ncol(out)) {\n+ rel_error = test_util::check_rel_error(as.scalar(out[i,j]),\n+ as.scalar(out_ref[i,j]), 1e-3, 1e-3)\n+ }\n+ }\n+\n+ print(\" - Testing backward\")\n+ out = elu::backward(X, X, 1)\n+ out_ref = matrix(\"0.3923 -0.1788 -0.2321 -0.3611 1.0445 -0.3362 0.5731 0.5409 -0.2648 -0.3676\", rows = 10, cols = 1)\n+\n+ for (i in 1:nrow(out)) {\n+ for(j in 1:ncol(out)) {\n+ rel_error = test_util::check_rel_error(as.scalar(out[i,j]),\n+ as.scalar(out_ref[i,j]), 1e-3, 1e-3)\n+ }\n+ }\n+}\n+\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-1491] Add an ELU activation function. This adds an "exponential linear unit" (ELU) to the `nn` deep learning library. Closes #721.
49,772
08.03.2018 23:19:38
28,800
2cee9bb9f5d8ad43759e747397ba517b0675a7d3
Improve stability of the ELU grad check test. Previously, the input value variance was small enough that an incorrect implementation of the ELU function could have been masked. This increases the variance of X in order to improve the stability and utility of this gradient test case.
[ { "change_type": "MODIFY", "old_path": "scripts/nn/test/grad_check.dml", "new_path": "scripts/nn/test/grad_check.dml", "diff": "@@ -2469,7 +2469,7 @@ elu = function() {\nN = 3 # num examples\nM = 10 # num neurons\n- X = rand(rows=N, cols=M)\n+ X = rand(rows=N, cols=M, min=-5, max=5)\ny = rand(rows=N, cols=M)\nout = elu::forward(X, 1)\n@@ -2477,7 +2477,7 @@ elu = function() {\ndX = elu::backward(dout, X, 1)\n# Grad check\n- h = 1e-6\n+ h = 1e-5\nprint(\" - Grad checking X.\")\nfor (i in 1:nrow(X)) {\nfor (j in 1:ncol(X)) {\n" } ]
Java
Apache License 2.0
apache/systemds
Improve stability of the ELU grad check test. Previously, the input value variance was small enough that an incorrect implementation of the ELU function could have been masked. This increases the variance of X in order to improve the stability and utility of this gradient test case.
49,727
08.03.2018 22:49:42
28,800
2af84960095b2648f10b5a211ad849b3e6366fef
New second-order eval builtin function Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/Hop.java", "new_path": "src/main/java/org/apache/sysml/hops/Hop.java", "diff": "@@ -1099,7 +1099,7 @@ public abstract class Hop implements ParseInfo\n// Operations that require a variable number of operands\npublic enum OpOpN {\n- PRINTF, CBIND, RBIND,\n+ PRINTF, CBIND, RBIND, EVAL\n}\npublic enum AggOp {\n@@ -1383,6 +1383,7 @@ public abstract class Hop implements ParseInfo\nHopsOpOpNLops.put(OpOpN.PRINTF, Nary.OperationType.PRINTF);\nHopsOpOpNLops.put(OpOpN.CBIND, Nary.OperationType.CBIND);\nHopsOpOpNLops.put(OpOpN.RBIND, Nary.OperationType.RBIND);\n+ HopsOpOpNLops.put(OpOpN.EVAL, Nary.OperationType.EVAL);\n}\nprotected static final HashMap<Hop.OpOp1, String> HopsOpOp12String;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/NaryOp.java", "new_path": "src/main/java/org/apache/sysml/hops/NaryOp.java", "diff": "@@ -159,7 +159,7 @@ public class NaryOp extends Hop {\nsetRequiresRecompileIfNecessary();\n//ensure cp exec type for single-node operations\n- if ( _op == OpOpN.PRINTF )\n+ if ( _op == OpOpN.PRINTF || _op == OpOpN.EVAL)\n_etype = ExecType.CP;\nreturn _etype;\n@@ -187,6 +187,7 @@ public class NaryOp extends Hop {\nsetDim2(HopRewriteUtils.getMaxInputDim(this, false));\nbreak;\ncase PRINTF:\n+ case EVAL:\n//do nothing:\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/ipa/InterProceduralAnalysis.java", "new_path": "src/main/java/org/apache/sysml/hops/ipa/InterProceduralAnalysis.java", "diff": "@@ -89,7 +89,7 @@ public class InterProceduralAnalysis\nprotected static final boolean INTRA_PROCEDURAL_ANALYSIS = true; //propagate statistics across statement blocks (main/functions)\nprotected static final boolean PROPAGATE_KNOWN_UDF_STATISTICS = true; //propagate statistics for known external functions\nprotected static final boolean ALLOW_MULTIPLE_FUNCTION_CALLS = true; //propagate consistent statistics from multiple calls\n- protected static final boolean REMOVE_UNUSED_FUNCTIONS = true; //remove unused functions (inlined or never called)\n+ protected static final boolean REMOVE_UNUSED_FUNCTIONS = false; //remove unused functions (inlined or never called)\nprotected static final boolean FLAG_FUNCTION_RECOMPILE_ONCE = true; //flag functions which require recompilation inside a loop for full function recompile\nprotected static final boolean REMOVE_UNNECESSARY_CHECKPOINTS = true; //remove unnecessary checkpoints (unconditionally overwritten intermediates)\nprotected static final boolean REMOVE_CONSTANT_BINARY_OPS = true; //remove constant binary operations (e.g., X*ones, where ones=matrix(1,...))\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/lops/Nary.java", "new_path": "src/main/java/org/apache/sysml/lops/Nary.java", "diff": "@@ -32,7 +32,7 @@ import org.apache.sysml.parser.Expression.ValueType;\npublic class Nary extends Lop {\npublic enum OperationType {\n- PRINTF, CBIND, RBIND,\n+ PRINTF, CBIND, RBIND, EVAL\n}\nprivate OperationType operationType;\n@@ -119,6 +119,7 @@ public class Nary extends Lop {\ncase PRINTF:\ncase CBIND:\ncase RBIND:\n+ case EVAL:\nreturn operationType.name().toLowerCase();\ndefault:\nthrow new UnsupportedOperationException(\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/BuiltinFunctionExpression.java", "new_path": "src/main/java/org/apache/sysml/parser/BuiltinFunctionExpression.java", "diff": "@@ -24,6 +24,7 @@ import java.util.HashMap;\nimport java.util.HashSet;\nimport org.antlr.v4.runtime.ParserRuleContext;\n+import org.apache.sysml.conf.ConfigurationManager;\nimport org.apache.sysml.parser.LanguageException.LanguageErrorCodes;\nimport org.apache.sysml.runtime.util.ConvolutionUtils;\nimport org.apache.sysml.runtime.util.UtilFunctions;\n@@ -379,6 +380,15 @@ public class BuiltinFunctionExpression extends DataIdentifier\nthis.setOutput(output);\nswitch (this.getOpCode()) {\n+ case EVAL:\n+ if (_args.length == 0)\n+ raiseValidateError(\"Function eval should provide at least one argument, i.e., the function name.\", false);\n+ checkValueTypeParam(_args[0], ValueType.STRING);\n+ output.setDataType(DataType.MATRIX);\n+ output.setValueType(ValueType.DOUBLE);\n+ output.setBlockDimensions(ConfigurationManager.getBlocksize(),\n+ ConfigurationManager.getBlocksize());\n+ break;\ncase COLSUM:\ncase COLMAX:\ncase COLMIN:\n@@ -1792,6 +1802,9 @@ public class BuiltinFunctionExpression extends DataIdentifier\nbifop = Expression.BuiltinFunctionOp.BITWSHIFTR;\nelse if ( functionName.equals(\"ifelse\") )\nbifop = Expression.BuiltinFunctionOp.IFELSE;\n+ else if (functionName.equals(\"eval\")) {\n+ bifop = Expression.BuiltinFunctionOp.EVAL;\n+ }\nelse\nreturn null;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/DMLTranslator.java", "new_path": "src/main/java/org/apache/sysml/parser/DMLTranslator.java", "diff": "@@ -2381,6 +2381,10 @@ public class DMLTranslator\n// Construct the hop based on the type of Builtin function\nswitch (source.getOpCode()) {\n+ case EVAL:\n+ currBuiltinOp = new NaryOp(target.getName(), target.getDataType(), target.getValueType(), OpOpN.EVAL, processAllExpressions(source.getAllExpr(), hops));\n+ break;\n+\ncase COLSUM:\ncurrBuiltinOp = new AggUnaryOp(target.getName(), target.getDataType(), target.getValueType(), AggOp.SUM,\nDirection.Col, expr);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/Expression.java", "new_path": "src/main/java/org/apache/sysml/parser/Expression.java", "diff": "@@ -86,6 +86,7 @@ public abstract class Expression implements ParseInfo\nCUMSUM,\nDIAG,\nEIGEN,\n+ EVAL,\nCONV2D, CONV2D_BACKWARD_FILTER, CONV2D_BACKWARD_DATA, BIAS_ADD, BIAS_MULTIPLY,\nMAX_POOL, AVG_POOL, MAX_POOL_BACKWARD, AVG_POOL_BACKWARD,\nEXP,\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/dml/DmlSyntacticValidator.java", "new_path": "src/main/java/org/apache/sysml/parser/dml/DmlSyntacticValidator.java", "diff": "@@ -519,7 +519,6 @@ public class DmlSyntacticValidator extends CommonSyntacticValidator implements D\nString functionName = names[1];\nArrayList<ParameterExpression> paramExpression = getParameterExpressionList(ctx.paramExprs);\n-\ncastAsScalarDeprecationCheck(functionName, ctx);\nConvertedDMLSyntax convertedSyntax = convertToDMLSyntax(ctx, namespace, functionName, paramExpression, ctx.name);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/functionobjects/Builtin.java", "new_path": "src/main/java/org/apache/sysml/runtime/functionobjects/Builtin.java", "diff": "@@ -51,7 +51,7 @@ public class Builtin extends ValueFunction\npublic enum BuiltinCode { SIN, COS, TAN, SINH, COSH, TANH, ASIN, ACOS, ATAN, LOG, LOG_NZ, MIN,\nMAX, ABS, SIGN, SQRT, EXP, PLOGP, PRINT, PRINTF, NROW, NCOL, LENGTH, ROUND, MAXINDEX, MININDEX,\n- STOP, CEIL, FLOOR, CUMSUM, CUMPROD, CUMMIN, CUMMAX, INVERSE, SPROP, SIGMOID }\n+ STOP, CEIL, FLOOR, CUMSUM, CUMPROD, CUMMIN, CUMMAX, INVERSE, SPROP, SIGMOID, EVAL }\npublic BuiltinCode bFunc;\nprivate static final boolean FASTMATH = true;\n@@ -81,6 +81,7 @@ public class Builtin extends ValueFunction\nString2BuiltinCode.put( \"plogp\" , BuiltinCode.PLOGP);\nString2BuiltinCode.put( \"print\" , BuiltinCode.PRINT);\nString2BuiltinCode.put( \"printf\" , BuiltinCode.PRINTF);\n+ String2BuiltinCode.put( \"eval\" , BuiltinCode.EVAL);\nString2BuiltinCode.put( \"nrow\" , BuiltinCode.NROW);\nString2BuiltinCode.put( \"ncol\" , BuiltinCode.NCOL);\nString2BuiltinCode.put( \"length\" , BuiltinCode.LENGTH);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/CPInstructionParser.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/CPInstructionParser.java", "diff": "@@ -182,6 +182,7 @@ public class CPInstructionParser extends InstructionParser\nString2CPInstructionType.put( \"printf\" , CPType.BuiltinNary);\nString2CPInstructionType.put( \"cbind\" , CPType.BuiltinNary);\nString2CPInstructionType.put( \"rbind\" , CPType.BuiltinNary);\n+ String2CPInstructionType.put( \"eval\" , CPType.BuiltinNary);\n// Parameterized Builtin Functions\nString2CPInstructionType.put( \"cdf\" , CPType.ParameterizedBuiltin);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/BuiltinNaryCPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/BuiltinNaryCPInstruction.java", "diff": "@@ -67,6 +67,9 @@ public abstract class BuiltinNaryCPInstruction extends CPInstruction\nreturn new MatrixBuiltinNaryCPInstruction(null,\nopcode, str, outputOperand, inputOperands);\n}\n+ else if (Nary.OperationType.EVAL.name().equalsIgnoreCase(opcode)) {\n+ return new EvalNaryCPInstruction(null, opcode, str, outputOperand, inputOperands);\n+ }\nthrow new DMLRuntimeException(\"Opcode (\" + opcode + \") not recognized in BuiltinMultipleCPInstruction\");\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/EvalNaryCPInstruction.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.sysml.runtime.instructions.cp;\n+\n+import org.apache.sysml.runtime.DMLRuntimeException;\n+import org.apache.sysml.runtime.controlprogram.Program;\n+import org.apache.sysml.runtime.controlprogram.caching.FrameObject;\n+import org.apache.sysml.runtime.controlprogram.caching.MatrixObject;\n+import org.apache.sysml.runtime.controlprogram.context.ExecutionContext;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\n+import org.apache.sysml.runtime.matrix.operators.Operator;\n+import org.apache.sysml.runtime.util.DataConverter;\n+\n+import java.util.ArrayList;\n+import java.util.Arrays;\n+\n+/**\n+ * Eval built-in function instruction\n+ * Note: it supports only single matrix[double] output\n+ */\n+public class EvalNaryCPInstruction extends BuiltinNaryCPInstruction {\n+\n+ public EvalNaryCPInstruction(Operator op, String opcode, String istr, CPOperand output, CPOperand... inputs) {\n+ super(op, opcode, istr, output, inputs);\n+ }\n+\n+ @Override\n+ public void processInstruction(ExecutionContext ec) throws DMLRuntimeException {\n+ //1. get the namespace and func\n+ String funcName = ec.getScalarInput(inputs[0]).getStringValue();\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+\n+ // bound the inputs to avoiding being deleted after the function call\n+ CPOperand[] boundInputs = Arrays.copyOfRange(inputs, 1, inputs.length);\n+ ArrayList<String> boundOutputNames = new ArrayList<>();\n+ boundOutputNames.add(output.getName());\n+ ArrayList<String> boundInputNames = new ArrayList<>();\n+ for (CPOperand input : boundInputs) {\n+ boundInputNames.add(input.getName());\n+ }\n+\n+ //2. copy the created output matrix\n+ MatrixObject outputMO = new MatrixObject(ec.getMatrixObject(output.getName()));\n+\n+ //3. call the function\n+ FunctionCallCPInstruction fcpi = new FunctionCallCPInstruction(\n+ null, funcName, boundInputs, boundInputNames, boundOutputNames, \"eval func\");\n+ fcpi.processInstruction(ec);\n+\n+ //4. convert the result to matrix\n+ Data newOutput = ec.getVariable(output);\n+ if (newOutput instanceof MatrixObject) {\n+ return;\n+ }\n+ MatrixBlock mb = null;\n+ if (newOutput instanceof ScalarObject) {\n+ //convert scalar to matrix\n+ mb = new MatrixBlock(((ScalarObject) newOutput).getDoubleValue());\n+ } else if (newOutput instanceof FrameObject) {\n+ //convert frame to matrix\n+ mb = DataConverter.convertToMatrixBlock(((FrameObject) newOutput).acquireRead());\n+ ec.cleanupCacheableData((FrameObject) newOutput);\n+ }\n+ outputMO.acquireModify(mb);\n+ outputMO.release();\n+ ec.setVariable(output.getName(), outputMO);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/FunctionCallCPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/FunctionCallCPInstruction.java", "diff": "@@ -45,7 +45,7 @@ public class FunctionCallCPInstruction extends CPInstruction {\nprivate final ArrayList<String> _boundInputNames;\nprivate final ArrayList<String> _boundOutputNames;\n- private FunctionCallCPInstruction(String namespace, String functName, CPOperand[] boundInputs,\n+ public FunctionCallCPInstruction(String namespace, String functName, CPOperand[] boundInputs,\nArrayList<String> boundInputNames, ArrayList<String> boundOutputNames, String istr) {\nsuper(CPType.External, null, functName, istr);\n_functionName = functName;\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/mlcontext/MLContextTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/mlcontext/MLContextTest.java", "diff": "@@ -88,6 +88,14 @@ import scala.collection.Seq;\npublic class MLContextTest extends MLContextTestBase {\n+ @Test\n+ public void testCreateDMLScriptBasedOnFileAndExecuteEvalTest() {\n+ System.out.println(\"MLContextTest - create DML script based on file and execute\");\n+ setExpectedStdOut(\"10\");\n+ Script script = dmlFromFile(baseDirectory + File.separator + \"eval-test.dml\");\n+ ml.execute(script);\n+ }\n+\n@Test\npublic void testCreateDMLScriptBasedOnStringAndExecute() {\nSystem.out.println(\"MLContextTest - create DML script based on string and execute\");\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/org/apache/sysml/api/mlcontext/eval-test.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+# product between matrix and scalar\n+f1 = function (matrix[double] M, double factor) return (double res) {\n+ res = prod(M) * factor\n+}\n+\n+# replace the matrix with a scalar and then use calculate the product\n+f2 = function (matrix[double] M, double r) return (double res) {\n+ R = replace(target=M, pattern=1, replacement=r)\n+ res = f1(R, 10)\n+}\n+\n+# production of two matrix\n+f3 = function (matrix[double] M1, matrix[double] M2) return (matrix[double] res) {\n+ res = M1 %*% M2\n+}\n+\n+f4 = function (matrix[double] M1, matrix[double] M2) return (matrix[double] res) {\n+ res = M1 %*% M2\n+}\n+\n+# some variables\n+X = matrix(\"1 2 3 4\", rows=2, cols=2)\n+y = 10\n+\n+R1 = eval(\"f1\", X, y)\n+R2 = eval(\"f2\", X, y)\n+R3 = eval(\"f3\", X, X)\n+for(i in 3:4)\n+ R4 = eval(\"f\"+i, X, X);\n+\n+print(toString(R1))\n+print(toString(R2))\n+print(toString(R3))\n+print(toString(R4))\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2077] New second-order eval builtin function Closes #740.
49,738
09.03.2018 18:50:35
28,800
48b1da332402e71e31c52bab15ced06223bf2573
Update ANTLR version and include codgenalg tests
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<properties>\n<hadoop.version>2.6.0</hadoop.version>\n- <antlr.version>4.5.3</antlr.version>\n+ <antlr.version>4.7.1</antlr.version>\n<spark.version>2.1.0</spark.version>\n<scala.version>2.11.8</scala.version>\n<scala.binary.version>2.11</scala.binary.version>\n<include>**/integration/functions/data/*Suite.java</include>\n<include>**/integration/functions/gdfo/*Suite.java</include>\n<include>**/integration/functions/sparse/*Suite.java</include>\n+ <include>**/integration/functions/codegenalg/*Suite.java</include>\n<include>**/integration/functions/**/*Test*.java</include>\n<include>**/integration/mlcontext/*Suite.java</include>\n<include>**/integration/mlcontext/algorithms/*Suite.java</include>\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2178] Update ANTLR version and include codgenalg tests
49,738
10.03.2018 00:54:40
28,800
1df744d777506c6805db68dc22e8421bf9dd00a7
[HOTFIX] Exclude new ANTLR-generated *.interp files from rat check
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<exclude>**/*.ipynb</exclude>\n<!-- Generated antlr files -->\n<exclude>src/main/java/*.tokens</exclude>\n+ <exclude>**/*.interp</exclude>\n<!-- Generated python files -->\n<exclude>src/main/python/systemml.egg-info/**</exclude>\n<!-- Sphinx reStructuredText files -->\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Exclude new ANTLR-generated *.interp files from rat check
49,738
10.03.2018 16:23:34
28,800
8dad38d23fe02d74dcd8d23c1f292ff1689a3823
[HOTFIX] Extended codegen pruning of invalid fusion plans This patch hardens the cleanup of invalid fusion plans for issues with the fuse-no-redundancy heuristic. Furthermore, this also fixes some warnings introduced with the recent update to ANTLR 4.7.1.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/SpoofCompiler.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/SpoofCompiler.java", "diff": "@@ -690,6 +690,10 @@ public class SpoofCompiler\nCNodeTpl tpl = e.getValue().getValue();\nHop[] inHops = e.getValue().getKey();\n+ //remove invalid plans with null inputs\n+ if( Arrays.stream(inHops).anyMatch(h -> (h==null)) )\n+ continue;\n+\n//perform simplifications and cse rewrites\ntpl = rewriter.simplifyCPlan(tpl);\ntpl = cse.eliminateCommonSubexpressions(tpl);\n@@ -697,7 +701,7 @@ public class SpoofCompiler\n//update input hops (order-preserving)\nHashSet<Long> inputHopIDs = tpl.getInputHopIDs(false);\ninHops = Arrays.stream(inHops)\n- .filter(p -> inputHopIDs.contains(p.getHopID()))\n+ .filter(p -> p != null && inputHopIDs.contains(p.getHopID()))\n.toArray(Hop[]::new);\ncplans2.put(e.getKey(), new Pair<>(inHops, tpl));\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/dml/DMLParserWrapper.java", "new_path": "src/main/java/org/apache/sysml/parser/dml/DMLParserWrapper.java", "diff": "@@ -71,6 +71,7 @@ import org.apache.sysml.parser.dml.DmlParser.StatementContext;\n* If in future we intend to make it multi-threaded, look at cleanUpState method and resolve the dependency accordingly.\n*\n*/\n+@SuppressWarnings(\"deprecation\")\npublic class DMLParserWrapper extends ParserWrapper\n{\nprivate static final Log LOG = LogFactory.getLog(DMLScript.class.getName());\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/pydml/PyDMLParserWrapper.java", "new_path": "src/main/java/org/apache/sysml/parser/pydml/PyDMLParserWrapper.java", "diff": "@@ -54,6 +54,7 @@ import org.apache.sysml.parser.pydml.PydmlParser.StatementContext;\n* Note: ExpressionInfo and StatementInfo are simply wrapper objects and are reused in both DML and PyDML parsers.\n*\n*/\n+@SuppressWarnings(\"deprecation\")\npublic class PyDMLParserWrapper extends ParserWrapper\n{\nprivate static final Log LOG = LogFactory.getLog(DMLScript.class.getName());\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Extended codegen pruning of invalid fusion plans This patch hardens the cleanup of invalid fusion plans for issues with the fuse-no-redundancy heuristic. Furthermore, this also fixes some warnings introduced with the recent update to ANTLR 4.7.1.
49,738
15.03.2018 13:57:20
25,200
bcaa140d5b43bf75fd97ae036f15863a154021b0
Improved dag-split rewrite (avoid redundant cuts) This patch cleans up unnecessary redundancy (i.e., unnecessary artificial dag-cut twrite/tread pairs) if multiple operators consume the same input and the input is split into another dag. For example, on stratstats, this patch reduced the number of cuts by more than 2x.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/rewrite/RewriteSplitDagDataDependentOperators.java", "new_path": "src/main/java/org/apache/sysml/hops/rewrite/RewriteSplitDagDataDependentOperators.java", "diff": "@@ -21,6 +21,7 @@ package org.apache.sysml.hops.rewrite;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n+import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\n@@ -112,8 +113,8 @@ public class RewriteSplitDagDataDependentOperators extends StatementBlockRewrite\n//unless there are transient reads w/ the same variable name in the current dag which can\n//lead to invalid reordering if variable consumers are not feeding into the candidate op.\nboolean hasTWrites = hasTransientWriteParents(c);\n- boolean moveTWrite = hasTWrites ? HopRewriteUtils.rHasSimpleReadChain(c,\n- getFirstTransientWriteParent(c).getName()) : false;\n+ boolean moveTWrite = hasTWrites ? HopRewriteUtils.rHasSimpleReadChain(\n+ c, getFirstTransientWriteParent(c).getName()) : false;\nString varname = null;\nlong rlen = c.getDim1();\n@@ -170,8 +171,8 @@ public class RewriteSplitDagDataDependentOperators extends StatementBlockRewrite\n}\n//add data-dependent operator sub dag to first statement block\n- DataOp twrite = new DataOp(varname, c.getDataType(), c.getValueType(),\n- c, DataOpTypes.TRANSIENTWRITE, null);\n+ DataOp twrite = new DataOp(varname, c.getDataType(),\n+ c.getValueType(), c, DataOpTypes.TRANSIENTWRITE, null);\ntwrite.setVisited();\ntwrite.setOutputParams(rlen, clen, nnz, update, brlen, bclen);\nHopRewriteUtils.copyLineNumbers(c, twrite);\n@@ -349,29 +350,27 @@ public class RewriteSplitDagDataDependentOperators extends StatementBlockRewrite\nfor( Hop h : rootsSB2 )\nrProbeAndAddHopsToCandidateSet(h, probeSet, candSet);\n- //step 3: create additional cuts\n- for( Pair<Hop,Hop> p : candSet )\n- {\n- String varname = createCutVarName(false);\n-\n+ //step 3: create additional cuts with reuse for common references\n+ HashMap<Long, DataOp> reuseTRead = new HashMap<>();\n+ for( Pair<Hop,Hop> p : candSet ) {\nHop hop = p.getKey();\nHop c = p.getValue();\n- DataOp tread = new DataOp(varname, c.getDataType(), c.getValueType(), DataOpTypes.TRANSIENTREAD,\n- null, c.getDim1(), c.getDim2(), c.getNnz(), c.getUpdateType(), c.getRowsInBlock(), c.getColsInBlock());\n+ DataOp tread = reuseTRead.get(c.getHopID());\n+ if( tread == null ) {\n+ String varname = createCutVarName(false);\n+\n+ tread = new DataOp(varname, c.getDataType(), c.getValueType(), DataOpTypes.TRANSIENTREAD, null,\n+ c.getDim1(), c.getDim2(), c.getNnz(), c.getUpdateType(), c.getRowsInBlock(), c.getColsInBlock());\ntread.setVisited();\nHopRewriteUtils.copyLineNumbers(c, tread);\n+ reuseTRead.put(c.getHopID(), tread);\nDataOp twrite = new DataOp(varname, c.getDataType(), c.getValueType(), c, DataOpTypes.TRANSIENTWRITE, null);\ntwrite.setVisited();\ntwrite.setOutputParams(c.getDim1(), c.getDim2(), c.getNnz(), c.getUpdateType(), c.getRowsInBlock(), c.getColsInBlock());\nHopRewriteUtils.copyLineNumbers(c, twrite);\n- //create additional cut by rewriting both hop dags\n- int pos = HopRewriteUtils.getChildReferencePos(hop, c);\n- HopRewriteUtils.removeChildReferenceByPos(hop, c, pos);\n- HopRewriteUtils.addChildReference(hop, tread, pos);\n-\n//update live in and out of new statement block (for piggybacking)\nDataIdentifier diVar = new DataIdentifier(varname);\ndiVar.setDimensions(c.getDim1(), c.getDim2());\n@@ -383,6 +382,12 @@ public class RewriteSplitDagDataDependentOperators extends StatementBlockRewrite\nrootsSB1.add(twrite);\n}\n+\n+ //create additional cut by rewriting both hop dags\n+ int pos = HopRewriteUtils.getChildReferencePos(hop, c);\n+ HopRewriteUtils.removeChildReferenceByPos(hop, c, pos);\n+ HopRewriteUtils.addChildReference(hop, tread, pos);\n+ }\n}\nprivate void rAddHopsToProbeSet( Hop hop, HashSet<Hop> probeSet )\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2185] Improved dag-split rewrite (avoid redundant cuts) This patch cleans up unnecessary redundancy (i.e., unnecessary artificial dag-cut twrite/tread pairs) if multiple operators consume the same input and the input is split into another dag. For example, on stratstats, this patch reduced the number of cuts by more than 2x.
49,738
16.03.2018 15:50:28
25,200
878430c9f7e9320c462bd377e9fd9d12eb0f5dff
[HOTFIX] Fix literal replacement test (for new rewrite phase order)
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/recompile/LiteralReplaceCastScalarReadTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/recompile/LiteralReplaceCastScalarReadTest.java", "diff": "@@ -21,7 +21,7 @@ package org.apache.sysml.test.integration.functions.recompile;\nimport org.junit.Assert;\nimport org.junit.Test;\n-\n+import org.apache.sysml.hops.OptimizerUtils;\nimport org.apache.sysml.lops.UnaryCP;\nimport org.apache.sysml.parser.Expression.ValueType;\nimport org.apache.sysml.test.integration.AutomatedTestBase;\n@@ -29,51 +29,42 @@ import org.apache.sysml.test.integration.TestConfiguration;\nimport org.apache.sysml.test.utils.TestUtils;\nimport org.apache.sysml.utils.Statistics;\n-/**\n- *\n- */\npublic class LiteralReplaceCastScalarReadTest extends AutomatedTestBase\n{\n-\nprivate final static String TEST_NAME = \"LiteralReplaceCastScalar\";\nprivate final static String TEST_DIR = \"functions/recompile/\";\nprivate final static String TEST_CLASS_DIR = TEST_DIR +\nLiteralReplaceCastScalarReadTest.class.getSimpleName() + \"/\";\n@Override\n- public void setUp()\n- {\n+ public void setUp() {\nTestUtils.clearAssertionInformation();\naddTestConfiguration(TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] { \"R\" }));\n}\n@Test\n- public void testRemoveCastsInputInteger()\n- {\n+ public void testRemoveCastsInputInteger() {\nrunScalarCastTest(ValueType.INT);\n}\n@Test\n- public void testRemoveCastsInputDouble()\n- {\n+ public void testRemoveCastsInputDouble() {\nrunScalarCastTest(ValueType.DOUBLE);\n}\n@Test\n- public void testRemoveCastsInputBoolean()\n- {\n+ public void testRemoveCastsInputBoolean() {\nrunScalarCastTest(ValueType.BOOLEAN);\n}\n+ private void runScalarCastTest( ValueType vt ) {\n+ boolean oldCF = OptimizerUtils.ALLOW_CONSTANT_FOLDING;\n- /**\n- *\n- * @param vt\n- */\n- private void runScalarCastTest( ValueType vt )\n- {\n+ try {\nTestConfiguration config = getTestConfiguration(TEST_NAME);\n+ loadTestConfiguration(config);\n+ OptimizerUtils.ALLOW_CONSTANT_FOLDING = false;\n// input value\nString val = null;\n@@ -90,8 +81,6 @@ public class LiteralReplaceCastScalarReadTest extends AutomatedTestBase\n//note: stats required for runtime check of rewrite\nprogramArgs = new String[]{\"-explain\",\"-stats\",\"-args\", val };\n- loadTestConfiguration(config);\n-\nrunTest(true, false, null, -1);\n//CHECK cast replacement and sum replacement\n@@ -100,5 +89,8 @@ public class LiteralReplaceCastScalarReadTest extends AutomatedTestBase\nAssert.assertEquals(false, Statistics.getCPHeavyHitterOpCodes().contains(UnaryCP.CAST_AS_BOOLEAN_OPCODE));\nAssert.assertEquals(false, Statistics.getCPHeavyHitterOpCodes().contains(\"uak+\")); //sum\n}\n-\n+ finally {\n+ OptimizerUtils.ALLOW_CONSTANT_FOLDING = oldCF;\n+ }\n+ }\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix literal replacement test (for new rewrite phase order)
49,719
19.03.2018 10:57:51
25,200
cca2de2c0c05fe326f755a0c8f9351732b8c1f2c
[MINOR] update notice files for all assemblies to change year from 2017 to 2018
[ { "change_type": "MODIFY", "old_path": "src/assembly/bin/NOTICE", "new_path": "src/assembly/bin/NOTICE", "diff": "Apache SystemML\n-Copyright [2015-2017] The Apache Software Foundation\n+Copyright [2015-2018] The Apache Software Foundation\nThis product includes software developed at\nThe Apache Software Foundation (http://www.apache.org/).\n" }, { "change_type": "MODIFY", "old_path": "src/assembly/extra/NOTICE", "new_path": "src/assembly/extra/NOTICE", "diff": "Apache SystemML\n-Copyright [2015-2017] The Apache Software Foundation\n+Copyright [2015-2018] The Apache Software Foundation\nThis product includes software developed at\nThe Apache Software Foundation (http://www.apache.org/).\n" }, { "change_type": "MODIFY", "old_path": "src/assembly/jar/NOTICE", "new_path": "src/assembly/jar/NOTICE", "diff": "Apache SystemML\n-Copyright [2015-2017] The Apache Software Foundation\n+Copyright [2015-2018] The Apache Software Foundation\nThis product includes software developed at\nThe Apache Software Foundation (http://www.apache.org/).\n" }, { "change_type": "MODIFY", "old_path": "src/assembly/lite/NOTICE", "new_path": "src/assembly/lite/NOTICE", "diff": "Apache SystemML\n-Copyright [2015-2017] The Apache Software Foundation\n+Copyright [2015-2018] The Apache Software Foundation\nThis product includes software developed at\nThe Apache Software Foundation (http://www.apache.org/).\n" }, { "change_type": "MODIFY", "old_path": "src/assembly/standalone-jar/NOTICE", "new_path": "src/assembly/standalone-jar/NOTICE", "diff": "Apache SystemML\n-Copyright [2015-2017] The Apache Software Foundation\n+Copyright [2015-2018] The Apache Software Foundation\nThis product includes software developed at\nThe Apache Software Foundation (http://www.apache.org/).\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] update notice files for all assemblies to change year from 2017 to 2018
49,738
22.03.2018 14:47:19
25,200
81e17152c66c1ab465c87e78d42b9a8c64734051
Fix deregistration of parallelized RDDs on cleanup This patch fixes the meta data handling of parallelized RDDs to allow for proper deregistration during cleanup (e.g., on rmvar). With this patch, we avoid unnecessarily conservative guarded parallelize by correctly reflecting the currently consumed memory of live RDDs in the driver.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "diff": "@@ -380,6 +380,7 @@ public class SparkExecutionContext extends ExecutionContext\n//keep rdd handle for future operations on it\nRDDObject rddhandle = new RDDObject(rdd);\nrddhandle.setHDFSFile(fromFile);\n+ rddhandle.setParallelizedRDD(!fromFile);\nmo.setRDDHandle(rddhandle);\n}\n//CASE 3: non-dirty (file exists on HDFS)\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2204] Fix deregistration of parallelized RDDs on cleanup This patch fixes the meta data handling of parallelized RDDs to allow for proper deregistration during cleanup (e.g., on rmvar). With this patch, we avoid unnecessarily conservative guarded parallelize by correctly reflecting the currently consumed memory of live RDDs in the driver.
49,738
22.03.2018 15:27:50
25,200
c6a8715eebf2f55b83d14e4bdaaa02dbe2f2d5d7
Multi-threaded matrix blocking on RDD parallelize This patch improves the performance for CP to Spark data exchange by parallelizing the matrix blocking on RDD parallelize. For a scenario of 10 x 800MB matrix parallelization (incl blocking),this patch improved performance from 8.1s to 3.8s.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "diff": "package org.apache.sysml.runtime.controlprogram.context;\nimport java.io.IOException;\n+import java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.LinkedList;\nimport java.util.List;\n+import java.util.stream.Collectors;\n+import java.util.stream.LongStream;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n@@ -684,37 +687,17 @@ public class SparkExecutionContext extends ExecutionContext\nthrows DMLRuntimeException\n{\nlong t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;\n- LinkedList<Tuple2<MatrixIndexes,MatrixBlock>> list = new LinkedList<>();\n+ List<Tuple2<MatrixIndexes,MatrixBlock>> list = null;\n- if( src.getNumRows() <= brlen\n- && src.getNumColumns() <= bclen )\n- {\n- list.addLast(new Tuple2<>(new MatrixIndexes(1,1), src));\n- }\n- else\n- {\n- boolean sparse = src.isInSparseFormat();\n-\n- //create and write subblocks of matrix\n- for(int blockRow = 0; blockRow < (int)Math.ceil(src.getNumRows()/(double)brlen); blockRow++)\n- for(int blockCol = 0; blockCol < (int)Math.ceil(src.getNumColumns()/(double)bclen); blockCol++)\n- {\n- int maxRow = (blockRow*brlen + brlen < src.getNumRows()) ? brlen : src.getNumRows() - blockRow*brlen;\n- int maxCol = (blockCol*bclen + bclen < src.getNumColumns()) ? bclen : src.getNumColumns() - blockCol*bclen;\n-\n- MatrixBlock block = new MatrixBlock(maxRow, maxCol, sparse);\n-\n- int row_offset = blockRow*brlen;\n- int col_offset = blockCol*bclen;\n-\n- //copy submatrix to block\n- src.slice( row_offset, row_offset+maxRow-1,\n- col_offset, col_offset+maxCol-1, block );\n-\n- //append block to sequence file\n- MatrixIndexes indexes = new MatrixIndexes(blockRow+1, blockCol+1);\n- list.addLast(new Tuple2<>(indexes, block));\n+ if( src.getNumRows() <= brlen && src.getNumColumns() <= bclen ) {\n+ list = Arrays.asList(new Tuple2<>(new MatrixIndexes(1,1), src));\n}\n+ else {\n+ MatrixCharacteristics mc = new MatrixCharacteristics(\n+ src.getNumRows(), src.getNumColumns(), brlen, bclen, src.getNonZeros());\n+ list = LongStream.range(0, mc.getNumBlocks()).parallel()\n+ .mapToObj(i -> createIndexedBlock(src, mc, i))\n+ .collect(Collectors.toList());\n}\nJavaPairRDD<MatrixIndexes,MatrixBlock> result = sc.parallelizePairs(list);\n@@ -726,6 +709,28 @@ public class SparkExecutionContext extends ExecutionContext\nreturn result;\n}\n+ private static Tuple2<MatrixIndexes,MatrixBlock> createIndexedBlock(MatrixBlock mb, MatrixCharacteristics mc, long ix) {\n+ try {\n+ //compute block indexes\n+ long blockRow = ix / mc.getNumColBlocks();\n+ long blockCol = ix % mc.getNumColBlocks();\n+ //compute block sizes\n+ int maxRow = UtilFunctions.computeBlockSize(mc.getRows(), blockRow+1, mc.getRowsPerBlock());\n+ int maxCol = UtilFunctions.computeBlockSize(mc.getCols(), blockCol+1, mc.getColsPerBlock());\n+ //copy sub-matrix to block\n+ MatrixBlock block = new MatrixBlock(maxRow, maxCol, mb.isInSparseFormat());\n+ int row_offset = (int)blockRow*mc.getRowsPerBlock();\n+ int col_offset = (int)blockCol*mc.getColsPerBlock();\n+ block = mb.slice( row_offset, row_offset+maxRow-1,\n+ col_offset, col_offset+maxCol-1, block );\n+ //create key-value pair\n+ return new Tuple2<>(new MatrixIndexes(blockRow+1, blockCol+1), block);\n+ }\n+ catch(DMLRuntimeException ex) {\n+ throw new RuntimeException(ex);\n+ }\n+ }\n+\npublic static JavaPairRDD<Long,FrameBlock> toFrameJavaPairRDD(JavaSparkContext sc, FrameBlock src)\nthrows DMLRuntimeException\n{\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2196] Multi-threaded matrix blocking on RDD parallelize This patch improves the performance for CP to Spark data exchange by parallelizing the matrix blocking on RDD parallelize. For a scenario of 10 x 800MB matrix parallelization (incl blocking),this patch improved performance from 8.1s to 3.8s.
49,719
23.03.2018 16:45:32
25,200
deddaee1fd3f8e87ff3a4403edf06cdb022ba949
[maven-release-plugin] prepare release v1.1.0-rc2
[ { "change_type": "MODIFY", "old_path": "pom.xml", "new_path": "pom.xml", "diff": "<version>18</version>\n</parent>\n<groupId>org.apache.systemml</groupId>\n- <version>1.2.0-SNAPSHOT</version>\n+ <version>1.1.0</version>\n<artifactId>systemml</artifactId>\n<packaging>jar</packaging>\n<name>SystemML</name>\n<connection>scm:git:[email protected]:apache/systemml</connection>\n<developerConnection>scm:git:https://git-wip-us.apache.org/repos/asf/systemml</developerConnection>\n<url>https://git-wip-us.apache.org/repos/asf?p=systemml.git</url>\n- <tag>HEAD</tag>\n+ <tag>v1.1.0-rc2</tag>\n</scm>\n<issueManagement>\n<system>JIRA</system>\n" } ]
Java
Apache License 2.0
apache/systemds
[maven-release-plugin] prepare release v1.1.0-rc2
49,738
23.03.2018 22:32:06
25,200
ad41c3a4630faa57903a71cf880f3a731bef310e
[MINOR][SYSTEMML-2202] Fix MLContext ScriptExecutor javadoc consistency
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/mlcontext/ScriptExecutor.java", "new_path": "src/main/java/org/apache/sysml/api/mlcontext/ScriptExecutor.java", "diff": "@@ -93,22 +93,7 @@ import org.apache.sysml.utils.Statistics;\n* </ol>\n* <p>\n* Modifications to these steps can be accomplished by subclassing\n- * ScriptExecutor. For example, the following code will turn off the global data\n- * flow optimization check by subclassing ScriptExecutor and overriding the\n- * globalDataFlowOptimization method.\n- * </p>\n- *\n- * <code>ScriptExecutor scriptExecutor = new ScriptExecutor() {\n- * <br>&nbsp;&nbsp;// turn off global data flow optimization check\n- * <br>&nbsp;&nbsp;@Override\n- * <br>&nbsp;&nbsp;protected void globalDataFlowOptimization() {\n- * <br>&nbsp;&nbsp;&nbsp;&nbsp;return;\n- * <br>&nbsp;&nbsp;}\n- * <br>};\n- * <br>ml.execute(script, scriptExecutor);</code>\n- * <p>\n- *\n- * For more information, please see the {@link #execute} method.\n+ * ScriptExecutor. For more information, please see the {@link #execute} method.\n*/\npublic class ScriptExecutor {\n@@ -307,7 +292,6 @@ public class ScriptExecutor {\n* <li>{@link #constructLops()}</li>\n* <li>{@link #generateRuntimeProgram()}</li>\n* <li>{@link #showExplanation()}</li>\n- * <li>{@link #globalDataFlowOptimization()}</li>\n* <li>{@link #countCompiledMRJobsAndSparkInstructions()}</li>\n* <li>{@link #initializeCachingAndScratchSpace()}</li>\n* <li>{@link #cleanupRuntimeProgram()}</li>\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR][SYSTEMML-2202] Fix MLContext ScriptExecutor javadoc consistency
49,738
24.03.2018 22:49:31
25,200
88a52eb044ecba2e00503339028e8342053f9bf4
Simplify JMLC/DMLScript APIs (unnecessary exceptions) This patch cleans up the JMLC and DMLScript APIs by removing unnecessary DMLExceptions from the public API because. We refrain from removing checked exceptions (e.g., IOException) for backwards compatibility of existing applications.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/DMLScript.java", "new_path": "src/main/java/org/apache/sysml/api/DMLScript.java", "diff": "@@ -235,10 +235,9 @@ public class DMLScript\n*\n* @param args command-line arguments\n* @throws IOException if an IOException occurs\n- * @throws DMLException if a DMLException occurs\n*/\npublic static void main(String[] args)\n- throws IOException, DMLException\n+ throws IOException\n{\nConfiguration conf = new Configuration(ConfigurationManager.getCachedJobConf());\nString[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();\n@@ -452,11 +451,8 @@ public class DMLScript\n* @param conf Hadoop configuration\n* @param args arguments\n* @return true if success, false otherwise\n- * @throws DMLException if DMLException occurs\n*/\n- public static boolean executeScript( Configuration conf, String[] args )\n- throws DMLException\n- {\n+ public static boolean executeScript( Configuration conf, String[] args ) {\n//parse arguments and set execution properties\nRUNTIME_PLATFORM oldrtplatform = rtplatform; //keep old rtplatform\nExplainType oldexplain = EXPLAIN; //keep old explain\n@@ -956,9 +952,7 @@ public class DMLScript\nreturn dateFormat.format(date);\n}\n- private static void cleanSystemMLWorkspace()\n- throws DMLException\n- {\n+ private static void cleanSystemMLWorkspace() {\ntry\n{\n//read the default config\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/jmlc/Connection.java", "new_path": "src/main/java/org/apache/sysml/api/jmlc/Connection.java", "diff": "@@ -186,11 +186,8 @@ public class Connection implements Closeable\n* @param inputs string array of input variables to register\n* @param outputs string array of output variables to register\n* @return PreparedScript object representing the precompiled script\n- * @throws DMLException if DMLException occurs\n*/\n- public PreparedScript prepareScript( String script, String[] inputs, String[] outputs)\n- throws DMLException\n- {\n+ public PreparedScript prepareScript( String script, String[] inputs, String[] outputs) {\nreturn prepareScript(script, inputs, outputs, false);\n}\n@@ -202,11 +199,8 @@ public class Connection implements Closeable\n* @param outputs string array of output variables to register\n* @param parsePyDML {@code true} if PyDML, {@code false} if DML\n* @return PreparedScript object representing the precompiled script\n- * @throws DMLException if DMLException occurs\n*/\n- public PreparedScript prepareScript( String script, String[] inputs, String[] outputs, boolean parsePyDML)\n- throws DMLException\n- {\n+ public PreparedScript prepareScript( String script, String[] inputs, String[] outputs, boolean parsePyDML) {\nreturn prepareScript(script, new HashMap<String,String>(), inputs, outputs, parsePyDML);\n}\n@@ -219,11 +213,8 @@ public class Connection implements Closeable\n* @param outputs string array of output variables to register\n* @param parsePyDML {@code true} if PyDML, {@code false} if DML\n* @return PreparedScript object representing the precompiled script\n- * @throws DMLException if DMLException occurs\n*/\n- public PreparedScript prepareScript( String script, Map<String, String> args, String[] inputs, String[] outputs, boolean parsePyDML)\n- throws DMLException\n- {\n+ public PreparedScript prepareScript( String script, Map<String, String> args, String[] inputs, String[] outputs, boolean parsePyDML) {\nDMLScript.SCRIPT_TYPE = parsePyDML ? ScriptType.PYDML : ScriptType.DML;\n//check for valid names of passed arguments\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/jmlc/JMLCUtils.java", "new_path": "src/main/java/org/apache/sysml/api/jmlc/JMLCUtils.java", "diff": "@@ -48,21 +48,16 @@ public class JMLCUtils\n* @param prog the DML/PyDML program\n* @param outputs registered output variables\n*/\n- public static void cleanupRuntimeProgram( Program prog, String[] outputs)\n- {\n+ public static void cleanupRuntimeProgram( Program prog, String[] outputs) {\nMap<String, FunctionProgramBlock> funcMap = prog.getFunctionProgramBlocks();\nHashSet<String> blacklist = new HashSet<>(Arrays.asList(outputs));\n-\n- if( funcMap != null && !funcMap.isEmpty() )\n- {\n- for( Entry<String, FunctionProgramBlock> e : funcMap.entrySet() )\n- {\n+ if( funcMap != null && !funcMap.isEmpty() ) {\n+ for( Entry<String, FunctionProgramBlock> e : funcMap.entrySet() ) {\nFunctionProgramBlock fpb = e.getValue();\nfor( ProgramBlock pb : fpb.getChildBlocks() )\nrCleanupRuntimeProgram(pb, blacklist);\n}\n}\n-\nfor( ProgramBlock pb : prog.getProgramBlocks() )\nrCleanupRuntimeProgram(pb, blacklist);\n}\n@@ -73,24 +68,20 @@ public class JMLCUtils\n* @param pb program block\n* @param outputs registered output variables\n*/\n- public static void rCleanupRuntimeProgram( ProgramBlock pb, HashSet<String> outputs )\n- {\n- if( pb instanceof WhileProgramBlock )\n- {\n+ public static void rCleanupRuntimeProgram( ProgramBlock pb, HashSet<String> outputs ) {\n+ if( pb instanceof WhileProgramBlock ) {\nWhileProgramBlock wpb = (WhileProgramBlock)pb;\nfor( ProgramBlock pbc : wpb.getChildBlocks() )\nrCleanupRuntimeProgram(pbc,outputs);\n}\n- else if( pb instanceof IfProgramBlock )\n- {\n+ else if( pb instanceof IfProgramBlock ) {\nIfProgramBlock ipb = (IfProgramBlock)pb;\nfor( ProgramBlock pbc : ipb.getChildBlocksIfBody() )\nrCleanupRuntimeProgram(pbc,outputs);\nfor( ProgramBlock pbc : ipb.getChildBlocksElseBody() )\nrCleanupRuntimeProgram(pbc,outputs);\n}\n- else if( pb instanceof ForProgramBlock )\n- {\n+ else if( pb instanceof ForProgramBlock ) {\nForProgramBlock fpb = (ForProgramBlock)pb;\nfor( ProgramBlock pbc : fpb.getChildBlocks() )\nrCleanupRuntimeProgram(pbc,outputs);\n@@ -121,13 +112,10 @@ public class JMLCUtils\n* @param outputs registered output variables\n* @return list of instructions\n*/\n- public static ArrayList<Instruction> cleanupRuntimeInstructions( ArrayList<Instruction> insts, HashSet<String> outputs )\n- {\n+ public static ArrayList<Instruction> cleanupRuntimeInstructions( ArrayList<Instruction> insts, HashSet<String> outputs ) {\nArrayList<Instruction> ret = new ArrayList<>();\n-\nfor( Instruction inst : insts ) {\n- if( inst instanceof VariableCPInstruction && ((VariableCPInstruction)inst).isRemoveVariable() )\n- {\n+ if( inst instanceof VariableCPInstruction && ((VariableCPInstruction)inst).isRemoveVariable() ) {\nArrayList<String> currRmVar = new ArrayList<>();\nfor( CPOperand input : ((VariableCPInstruction)inst).getInputs() )\nif( !outputs.contains(input.getName()) )\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/jmlc/PreparedScript.java", "new_path": "src/main/java/org/apache/sysml/api/jmlc/PreparedScript.java", "diff": "@@ -103,8 +103,7 @@ public class PreparedScript implements ConfigurableAPI\n* @param dmlconf dml configuration\n* @param cconf compiler configuration\n*/\n- protected PreparedScript( Program prog, String[] inputs, String[] outputs, DMLConfig dmlconf, CompilerConfig cconf )\n- {\n+ protected PreparedScript( Program prog, String[] inputs, String[] outputs, DMLConfig dmlconf, CompilerConfig cconf ) {\n_prog = prog;\n_vars = new LocalVariableMap();\n@@ -164,9 +163,8 @@ public class PreparedScript implements ConfigurableAPI\n*\n* @param varname input variable name\n* @param scalar boolean value\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, boolean scalar) throws DMLException {\n+ public void setScalar(String varname, boolean scalar) {\nsetScalar(varname, scalar, false);\n}\n@@ -176,9 +174,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param scalar boolean value\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, boolean scalar, boolean reuse) throws DMLException {\n+ public void setScalar(String varname, boolean scalar, boolean reuse) {\nsetScalar(varname, new BooleanObject(scalar), reuse);\n}\n@@ -187,9 +184,8 @@ public class PreparedScript implements ConfigurableAPI\n*\n* @param varname input variable name\n* @param scalar long value\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, long scalar) throws DMLException {\n+ public void setScalar(String varname, long scalar) {\nsetScalar(varname, scalar, false);\n}\n@@ -199,9 +195,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param scalar long value\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, long scalar, boolean reuse) throws DMLException {\n+ public void setScalar(String varname, long scalar, boolean reuse) {\nsetScalar(varname, new IntObject(scalar), reuse);\n}\n@@ -209,9 +204,8 @@ public class PreparedScript implements ConfigurableAPI\n*\n* @param varname input variable name\n* @param scalar double value\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, double scalar) throws DMLException {\n+ public void setScalar(String varname, double scalar) {\nsetScalar(varname, scalar, false);\n}\n@@ -221,9 +215,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param scalar double value\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, double scalar, boolean reuse) throws DMLException {\n+ public void setScalar(String varname, double scalar, boolean reuse) {\nsetScalar(varname, new DoubleObject(scalar), reuse);\n}\n@@ -232,9 +225,8 @@ public class PreparedScript implements ConfigurableAPI\n*\n* @param varname input variable name\n* @param scalar string value\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, String scalar) throws DMLException {\n+ public void setScalar(String varname, String scalar) {\nsetScalar(varname, scalar, false);\n}\n@@ -244,9 +236,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param scalar string value\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, String scalar, boolean reuse) throws DMLException {\n+ public void setScalar(String varname, String scalar, boolean reuse) {\nsetScalar(varname, new StringObject(scalar), reuse);\n}\n@@ -258,14 +249,10 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param scalar scalar object\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setScalar(String varname, ScalarObject scalar, boolean reuse)\n- throws DMLException\n- {\n+ public void setScalar(String varname, ScalarObject scalar, boolean reuse) {\nif( !_inVarnames.contains(varname) )\nthrow new DMLException(\"Unspecified input variable: \"+varname);\n-\n_vars.put(varname, scalar);\n}\n@@ -274,9 +261,8 @@ public class PreparedScript implements ConfigurableAPI\n*\n* @param varname input variable name\n* @param matrix two-dimensional double array matrix representation\n- * @throws DMLException if DMLException occurs\n*/\n- public void setMatrix(String varname, double[][] matrix) throws DMLException {\n+ public void setMatrix(String varname, double[][] matrix) {\nsetMatrix(varname, matrix, false);\n}\n@@ -286,9 +272,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param matrix two-dimensional double array matrix representation\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setMatrix(String varname, double[][] matrix, boolean reuse) throws DMLException {\n+ public void setMatrix(String varname, double[][] matrix, boolean reuse) {\nsetMatrix(varname, DataConverter.convertToMatrixBlock(matrix), reuse);\n}\n@@ -300,11 +285,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param matrix matrix represented as a MatrixBlock\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setMatrix(String varname, MatrixBlock matrix, boolean reuse)\n- throws DMLException\n- {\n+ public void setMatrix(String varname, MatrixBlock matrix, boolean reuse) {\nif( !_inVarnames.contains(varname) )\nthrow new DMLException(\"Unspecified input variable: \"+varname);\n@@ -330,9 +312,8 @@ public class PreparedScript implements ConfigurableAPI\n*\n* @param varname input variable name\n* @param frame two-dimensional string array frame representation\n- * @throws DMLException if DMLException occurs\n*/\n- public void setFrame(String varname, String[][] frame) throws DMLException {\n+ public void setFrame(String varname, String[][] frame) {\nsetFrame(varname, frame, false);\n}\n@@ -342,9 +323,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param frame two-dimensional string array frame representation\n* @param schema list representing the types of the frame columns\n- * @throws DMLException if DMLException occurs\n*/\n- public void setFrame(String varname, String[][] frame, List<ValueType> schema) throws DMLException {\n+ public void setFrame(String varname, String[][] frame, List<ValueType> schema) {\nsetFrame(varname, frame, schema, false);\n}\n@@ -355,9 +335,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param frame two-dimensional string array frame representation\n* @param schema list representing the types of the frame columns\n* @param colnames frame column names\n- * @throws DMLException if DMLException occurs\n*/\n- public void setFrame(String varname, String[][] frame, List<ValueType> schema, List<String> colnames) throws DMLException {\n+ public void setFrame(String varname, String[][] frame, List<ValueType> schema, List<String> colnames) {\nsetFrame(varname, frame, schema, colnames, false);\n}\n@@ -367,9 +346,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param frame two-dimensional string array frame representation\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setFrame(String varname, String[][] frame, boolean reuse) throws DMLException {\n+ public void setFrame(String varname, String[][] frame, boolean reuse) {\nsetFrame(varname, DataConverter.convertToFrameBlock(frame), reuse);\n}\n@@ -380,9 +358,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param frame two-dimensional string array frame representation\n* @param schema list representing the types of the frame columns\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setFrame(String varname, String[][] frame, List<ValueType> schema, boolean reuse) throws DMLException {\n+ public void setFrame(String varname, String[][] frame, List<ValueType> schema, boolean reuse) {\nsetFrame(varname, DataConverter.convertToFrameBlock(frame, schema.toArray(new ValueType[0])), reuse);\n}\n@@ -394,9 +371,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param schema list representing the types of the frame columns\n* @param colnames frame column names\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setFrame(String varname, String[][] frame, List<ValueType> schema, List<String> colnames, boolean reuse) throws DMLException {\n+ public void setFrame(String varname, String[][] frame, List<ValueType> schema, List<String> colnames, boolean reuse) {\nsetFrame(varname, DataConverter.convertToFrameBlock( frame,\nschema.toArray(new ValueType[0]), colnames.toArray(new String[0])), reuse);\n}\n@@ -409,11 +385,8 @@ public class PreparedScript implements ConfigurableAPI\n* @param varname input variable name\n* @param frame frame represented as a FrameBlock\n* @param reuse if {@code true}, preserve value over multiple {@code executeScript} calls\n- * @throws DMLException if DMLException occurs\n*/\n- public void setFrame(String varname, FrameBlock frame, boolean reuse)\n- throws DMLException\n- {\n+ public void setFrame(String varname, FrameBlock frame, boolean reuse) {\nif( !_inVarnames.contains(varname) )\nthrow new DMLException(\"Unspecified input variable: \"+varname);\n@@ -445,11 +418,8 @@ public class PreparedScript implements ConfigurableAPI\n* result variables according to bound and registered outputs.\n*\n* @return ResultVariables object encapsulating output results\n- * @throws DMLException if DMLException occurs\n*/\n- public ResultVariables executeScript()\n- throws DMLException\n- {\n+ public ResultVariables executeScript() {\n//add reused variables\n_vars.putAll(_inVarReuse);\n@@ -484,9 +454,8 @@ public class PreparedScript implements ConfigurableAPI\n* Explain the DML/PyDML program and view result as a string.\n*\n* @return string results of explain\n- * @throws DMLException if DMLException occurs\n*/\n- public String explain() throws DMLException {\n+ public String explain() {\nreturn Explain.explain(_prog);\n}\n@@ -501,11 +470,8 @@ public class PreparedScript implements ConfigurableAPI\n*\n* @param fnamespace function namespace, null for default namespace\n* @param fnames function name\n- * @throws DMLException if any compilation error occurs\n*/\n- public void enableFunctionRecompile(String fnamespace, String... fnames)\n- throws DMLException\n- {\n+ public void enableFunctionRecompile(String fnamespace, String... fnames) {\n//handle default name space\nif( fnamespace == null )\nfnamespace = DMLProgram.DEFAULT_NAMESPACE;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/jmlc/ResultVariables.java", "new_path": "src/main/java/org/apache/sysml/api/jmlc/ResultVariables.java", "diff": "@@ -68,9 +68,8 @@ public class ResultVariables\n*\n* @param varname output variable name\n* @return matrix as a two-dimensional double array\n- * @throws DMLException if DMLException occurs\n*/\n- public double[][] getMatrix(String varname) throws DMLException {\n+ public double[][] getMatrix(String varname) {\nreturn DataConverter.convertToDoubleMatrix(getMatrixBlock(varname));\n}\n@@ -80,9 +79,8 @@ public class ResultVariables\n*\n* @param varname output variable name\n* @return matrix as matrix block\n- * @throws DMLException if DMLException occurs\n*/\n- public MatrixBlock getMatrixBlock(String varname) throws DMLException {\n+ public MatrixBlock getMatrixBlock(String varname) {\nData dat = _out.get(varname);\nif( dat == null )\nthrow new DMLException(\"Non-existent output variable: \"+varname);\n@@ -103,9 +101,8 @@ public class ResultVariables\n*\n* @param varname output variable name\n* @return frame as a two-dimensional string array\n- * @throws DMLException if DMLException occurs\n*/\n- public String[][] getFrame(String varname) throws DMLException {\n+ public String[][] getFrame(String varname) {\nreturn DataConverter.convertToStringFrame(getFrameBlock(varname));\n}\n@@ -115,11 +112,8 @@ public class ResultVariables\n*\n* @param varname output variable name\n* @return frame as a frame block\n- * @throws DMLException if DMLException occurs\n*/\n- public FrameBlock getFrameBlock(String varname)\n- throws DMLException\n- {\n+ public FrameBlock getFrameBlock(String varname) {\nData dat = _out.get(varname);\nif( dat == null )\nthrow new DMLException(\"Non-existent output variable: \"+varname);\n@@ -141,9 +135,8 @@ public class ResultVariables\n* @param varname\n* output variable name\n* @return double value\n- * @throws DMLException if DMLException occurs\n*/\n- public double getDouble(String varname) throws DMLException {\n+ public double getDouble(String varname) {\nreturn getScalarObject(varname).getDoubleValue();\n}\n@@ -153,9 +146,8 @@ public class ResultVariables\n* @param varname\n* output variable name\n* @return boolean value\n- * @throws DMLException if DMLException occurs\n*/\n- public boolean getBoolean(String varname) throws DMLException {\n+ public boolean getBoolean(String varname) {\nreturn getScalarObject(varname).getBooleanValue();\n}\n@@ -165,9 +157,8 @@ public class ResultVariables\n* @param varname\n* output variable name\n* @return long value\n- * @throws DMLException if DMLException occurs\n*/\n- public long getLong(String varname) throws DMLException {\n+ public long getLong(String varname) {\nreturn getScalarObject(varname).getLongValue();\n}\n@@ -177,9 +168,8 @@ public class ResultVariables\n* @param varname\n* output variable name\n* @return string value\n- * @throws DMLException if DMLException occurs\n*/\n- public String getString(String varname) throws DMLException {\n+ public String getString(String varname) {\nreturn getScalarObject(varname).getStringValue();\n}\n@@ -189,9 +179,8 @@ public class ResultVariables\n* @param varname\n* output variable name\n* @return ScalarObject\n- * @throws DMLException if DMLException occurs\n*/\n- public ScalarObject getScalarObject(String varname) throws DMLException {\n+ public ScalarObject getScalarObject(String varname) {\nData dat = _out.get(varname);\nif( dat == null )\nthrow new DMLException(\"Non-existent output variable: \" + varname);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/codegen/SpoofCompiler.java", "new_path": "src/main/java/org/apache/sysml/hops/codegen/SpoofCompiler.java", "diff": "@@ -32,7 +32,6 @@ import org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.log4j.Level;\nimport org.apache.log4j.Logger;\n-import org.apache.sysml.api.DMLException;\nimport org.apache.sysml.api.DMLScript;\nimport org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;\nimport org.apache.sysml.conf.ConfigurationManager;\n@@ -489,9 +488,7 @@ public class SpoofCompiler\n////////////////////\n// Codegen plan construction\n- private static void rExploreCPlans(Hop hop, CPlanMemoTable memo, boolean compileLiterals)\n- throws DMLException\n- {\n+ private static void rExploreCPlans(Hop hop, CPlanMemoTable memo, boolean compileLiterals) {\n//top-down memoization of processed dag nodes\nif( memo.contains(hop.getHopID()) || memo.containsHop(hop) )\nreturn;\n@@ -545,9 +542,7 @@ public class SpoofCompiler\nreturn P;\n}\n- private static void rConstructCPlans(Hop hop, CPlanMemoTable memo, HashMap<Long, Pair<Hop[],CNodeTpl>> cplans, boolean compileLiterals, HashSet<Long> visited)\n- throws DMLException\n- {\n+ private static void rConstructCPlans(Hop hop, CPlanMemoTable memo, HashMap<Long, Pair<Hop[],CNodeTpl>> cplans, boolean compileLiterals, HashSet<Long> visited) {\n//top-down memoization of processed dag nodes\nif( hop == null || visited.contains(hop.getHopID()) )\nreturn;\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-616] Simplify JMLC/DMLScript APIs (unnecessary exceptions) This patch cleans up the JMLC and DMLScript APIs by removing unnecessary DMLExceptions from the public API because. We refrain from removing checked exceptions (e.g., IOException) for backwards compatibility of existing applications.
49,738
26.03.2018 12:19:34
25,200
6f9e1cf9c402d4811e00d0a924a9eba5974342d5
[HOTFIX] Fix tolerance in compression par unary aggregate tests This patch changes the absolute tolerance of unary aggregate tests from 1e-12 to 1e-9 for consistency with the large unary aggregate tests and due account for new multi-threaded unary aggregate thresholds.
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/compress/ParUnaryAggregateTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/compress/ParUnaryAggregateTest.java", "diff": "@@ -1092,7 +1092,7 @@ public class ParUnaryAggregateTest extends AutomatedTestBase\n|| aggtype == AggType.ROWMINS || aggtype == AggType.ROWMINS)?rows:1;\nint dim2 = (aggtype == AggType.COLSUMS || aggtype == AggType.COLSUMSSQ\n|| aggtype == AggType.COLMAXS || aggtype == AggType.COLMINS)?cols1:1;\n- TestUtils.compareMatrices(d1, d2, dim1, dim2, 0.00000000001);\n+ TestUtils.compareMatrices(d1, d2, dim1, dim2, 0.000000001);\n}\ncatch(Exception ex) {\nthrow new RuntimeException(ex);\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix tolerance in compression par unary aggregate tests This patch changes the absolute tolerance of unary aggregate tests from 1e-12 to 1e-9 for consistency with the large unary aggregate tests and due account for new multi-threaded unary aggregate thresholds.
49,738
26.03.2018 22:03:03
25,200
0d858347d5a8d1630b78bb353361b9fa7ea6d629
Improved exists builtin function (data-dep ordering) This patch improves the exists builtin function for scenarios where the input matrix is created in the same DAG (or ends of in the same DAG after rewrites) by ordering the instruction schedule according to existing data dependencies and generalizing the runtime.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/DMLTranslator.java", "new_path": "src/main/java/org/apache/sysml/parser/DMLTranslator.java", "diff": "@@ -2443,7 +2443,7 @@ public class DMLTranslator\ncase EXISTS:\ncurrBuiltinOp = new UnaryOp(target.getName(), target.getDataType(),\n- target.getValueType(), Hop.OpOp1.EXISTS, new LiteralOp(expr.getName()));\n+ target.getValueType(), Hop.OpOp1.EXISTS, expr);\nbreak;\ncase SUM:\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/AggregateUnaryCPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/AggregateUnaryCPInstruction.java", "diff": "@@ -122,9 +122,10 @@ public class AggregateUnaryCPInstruction extends UnaryCPInstruction\nec.setScalarOutput(output_name, new IntObject(rval));\n}\nelse if( _type == AUType.EXISTS ) {\n- //probe existing of variable in symbol table w/o error\n- boolean rval = ec.getVariables().keySet()\n- .contains(ec.getScalarInput(input1).getStringValue());\n+ //probe existence of variable in symbol table w/o error\n+ String varName = input1.isMatrix() ? input1.getName() :\n+ ec.getScalarInput(input1).getStringValue();\n+ boolean rval = ec.getVariables().keySet().contains(varName);\n//create and set output scalar\nec.setScalarOutput(output_name, new BooleanObject(rval));\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/CPOperand.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/CPOperand.java", "diff": "@@ -69,6 +69,10 @@ public class CPOperand\nreturn _dataType.isMatrix();\n}\n+ public boolean isScalar() {\n+ return _dataType.isScalar();\n+ }\n+\npublic boolean isLiteral() {\nreturn _isLiteral;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/VariableCPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/VariableCPInstruction.java", "diff": "@@ -802,12 +802,10 @@ public class VariableCPInstruction extends CPInstruction {\n*/\npublic static void processRemoveVariableInstruction( ExecutionContext ec, String varname ) {\n// remove variable from symbol table\n- Data input1_data = ec.removeVariable(varname);\n- if ( input1_data == null )\n- throw new DMLRuntimeException(\"Unexpected error: could not find a data object for variable name:\" + varname + \", while processing rmvar instruction.\");\n+ Data dat = ec.removeVariable(varname);\n//cleanup matrix data on fs/hdfs (if necessary)\n- if ( input1_data instanceof CacheableData ) {\n- ec.cleanupCacheableData( (CacheableData<?>) input1_data );\n+ if ( dat != null && dat instanceof CacheableData ) {\n+ ec.cleanupCacheableData((CacheableData<?>) dat);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/misc/ExistsVariableTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/misc/ExistsVariableTest.java", "diff": "@@ -29,27 +29,39 @@ import org.apache.sysml.test.utils.TestUtils;\npublic class ExistsVariableTest extends AutomatedTestBase\n{\n- private final static String TEST_NAME1 = \"Exists\";\n+ private final static String TEST_NAME1 = \"Exists1\"; //for var names\n+ private final static String TEST_NAME2 = \"Exists2\"; //for vars\n+\nprivate final static String TEST_DIR = \"functions/misc/\";\nprivate final static String TEST_CLASS_DIR = TEST_DIR + ExistsVariableTest.class.getSimpleName() + \"/\";\n- //TODO additional test with variable creation in same DAG, requires better data dependency handling\n@Override\npublic void setUp() {\nTestUtils.clearAssertionInformation();\naddTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[]{\"R\"}));\n+ addTestConfiguration( TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[]{\"R\"}));\n}\n@Test\n- public void testExistsPositive() {\n+ public void testExistsVarnamePositive() {\nrunExistsTest(TEST_NAME1, true);\n}\n@Test\n- public void testExistsNegative() {\n+ public void testExistsVarnameNegative() {\nrunExistsTest(TEST_NAME1, false);\n}\n+ @Test\n+ public void testExistsVarPositive() {\n+ runExistsTest(TEST_NAME2, true);\n+ }\n+\n+ @Test\n+ public void testExistsVarNegative() {\n+ runExistsTest(TEST_NAME2, false);\n+ }\n+\nprivate void runExistsTest(String testName, boolean pos) {\nTestConfiguration config = getTestConfiguration(testName);\nloadTestConfiguration(config);\n" }, { "change_type": "RENAME", "old_path": "src/test/scripts/functions/misc/Exists.dml", "new_path": "src/test/scripts/functions/misc/Exists1.dml", "diff": "" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/misc/Exists2.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( $1 == 1 )\n+ X = matrix(1,10,10);\n+\n+R = as.matrix(as.double(exists(X)));\n+\n+write(R, $2);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2210] Improved exists builtin function (data-dep ordering) This patch improves the exists builtin function for scenarios where the input matrix is created in the same DAG (or ends of in the same DAG after rewrites) by ordering the instruction schedule according to existing data dependencies and generalizing the runtime.
49,738
28.03.2018 11:04:37
25,200
5ef4f5ac2e76cff253a847ee6765ec49379d6ac4
[HOTFIX] Fix case-sensitivity of lower/upper.tri test names While on windows platforms the capitalization of test names does not matter, linux platforms such as our jenkins infrastructure are case-sensitive.
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/unary/matrix/ExtractTriangularTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/unary/matrix/ExtractTriangularTest.java", "diff": "@@ -33,8 +33,8 @@ import org.apache.sysml.test.utils.TestUtils;\npublic class ExtractTriangularTest extends AutomatedTestBase\n{\n- private final static String TEST_NAME1 = \"extractLowerTri\";\n- private final static String TEST_NAME2 = \"extractUpperTri\";\n+ private final static String TEST_NAME1 = \"ExtractLowerTri\";\n+ private final static String TEST_NAME2 = \"ExtractUpperTri\";\nprivate final static String TEST_DIR = \"functions/unary/matrix/\";\nprivate static final String TEST_CLASS_DIR = TEST_DIR + ExtractTriangularTest.class.getSimpleName() + \"/\";\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix case-sensitivity of lower/upper.tri test names While on windows platforms the capitalization of test names does not matter, linux platforms such as our jenkins infrastructure are case-sensitive.
49,738
30.03.2018 18:54:47
25,200
c16738d22c0e7c0917e413f3c8cf5db16d76d045
Improved spark mapmm (avoid parallelize-repartition) This patch improves the spark mapmm instruction (broadcast-based matrix multiply) by avoiding unnecessary shuffle for repartitioning - which is used to guarantee output partition size - if the input is a parallelized RDD. For this scenario, we now create the parallelized RDD with right number of partitions.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "diff": "@@ -291,7 +291,13 @@ public class SparkExecutionContext extends ExecutionContext\n@SuppressWarnings(\"unchecked\")\npublic JavaPairRDD<MatrixIndexes,MatrixBlock> getBinaryBlockRDDHandleForVariable( String varname ) {\nreturn (JavaPairRDD<MatrixIndexes,MatrixBlock>)\n- getRDDHandleForVariable( varname, InputInfo.BinaryBlockInputInfo);\n+ getRDDHandleForVariable( varname, InputInfo.BinaryBlockInputInfo, -1);\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ public JavaPairRDD<MatrixIndexes,MatrixBlock> getBinaryBlockRDDHandleForVariable( String varname, int numParts ) {\n+ return (JavaPairRDD<MatrixIndexes,MatrixBlock>)\n+ getRDDHandleForVariable( varname, InputInfo.BinaryBlockInputInfo, numParts);\n}\n/**\n@@ -304,15 +310,19 @@ public class SparkExecutionContext extends ExecutionContext\n@SuppressWarnings(\"unchecked\")\npublic JavaPairRDD<Long,FrameBlock> getFrameBinaryBlockRDDHandleForVariable( String varname ) {\nJavaPairRDD<Long,FrameBlock> out = (JavaPairRDD<Long,FrameBlock>)\n- getRDDHandleForVariable( varname, InputInfo.BinaryBlockInputInfo);\n+ getRDDHandleForVariable( varname, InputInfo.BinaryBlockInputInfo, -1);\nreturn out;\n}\npublic JavaPairRDD<?,?> getRDDHandleForVariable( String varname, InputInfo inputInfo ) {\n+ return getRDDHandleForVariable(varname, inputInfo, -1);\n+ }\n+\n+ public JavaPairRDD<?,?> getRDDHandleForVariable( String varname, InputInfo inputInfo, int numParts ) {\nData dat = getVariable(varname);\nif( dat instanceof MatrixObject ) {\nMatrixObject mo = getMatrixObject(varname);\n- return getRDDHandleForMatrixObject(mo, inputInfo);\n+ return getRDDHandleForMatrixObject(mo, inputInfo, numParts);\n}\nelse if( dat instanceof FrameObject ) {\nFrameObject fo = getFrameObject(varname);\n@@ -323,16 +333,12 @@ public class SparkExecutionContext extends ExecutionContext\n}\n}\n- /**\n- * This call returns an RDD handle for a given matrix object. This includes\n- * the creation of RDDs for in-memory or binary-block HDFS data.\n- *\n- * @param mo matrix object\n- * @param inputInfo input info\n- * @return JavaPairRDD handle for a matrix object\n- */\n- @SuppressWarnings(\"unchecked\")\npublic JavaPairRDD<?,?> getRDDHandleForMatrixObject( MatrixObject mo, InputInfo inputInfo ) {\n+ return getRDDHandleForMatrixObject(mo, inputInfo, -1);\n+ }\n+\n+ @SuppressWarnings(\"unchecked\")\n+ public JavaPairRDD<?,?> getRDDHandleForMatrixObject( MatrixObject mo, InputInfo inputInfo, int numParts ) {\n//NOTE: MB this logic should be integrated into MatrixObject\n//However, for now we cannot assume that spark libraries are\n//always available and hence only store generic references in\n@@ -366,7 +372,7 @@ public class SparkExecutionContext extends ExecutionContext\n}\nelse { //default case\nMatrixBlock mb = mo.acquireRead(); //pin matrix in memory\n- rdd = toMatrixJavaPairRDD(sc, mb, (int)mo.getNumRowsPerBlock(), (int)mo.getNumColumnsPerBlock());\n+ rdd = toMatrixJavaPairRDD(sc, mb, (int)mo.getNumRowsPerBlock(), (int)mo.getNumColumnsPerBlock(), numParts);\nmo.release(); //unpin matrix\n_parRDDs.registerRDD(rdd.id(), OptimizerUtils.estimatePartitionedSizeExactSparsity(mc), true);\n}\n@@ -657,16 +663,11 @@ public class SparkExecutionContext extends ExecutionContext\nobj.setRDDHandle( rddhandle );\n}\n- /**\n- * Utility method for creating an RDD out of an in-memory matrix block.\n- *\n- * @param sc java spark context\n- * @param src matrix block\n- * @param brlen block row length\n- * @param bclen block column length\n- * @return JavaPairRDD handle to matrix block\n- */\npublic static JavaPairRDD<MatrixIndexes,MatrixBlock> toMatrixJavaPairRDD(JavaSparkContext sc, MatrixBlock src, int brlen, int bclen) {\n+ return toMatrixJavaPairRDD(sc, src, brlen, bclen, -1);\n+ }\n+\n+ public static JavaPairRDD<MatrixIndexes,MatrixBlock> toMatrixJavaPairRDD(JavaSparkContext sc, MatrixBlock src, int brlen, int bclen, int numParts) {\nlong t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;\nList<Tuple2<MatrixIndexes,MatrixBlock>> list = null;\n@@ -681,7 +682,9 @@ public class SparkExecutionContext extends ExecutionContext\n.collect(Collectors.toList());\n}\n- JavaPairRDD<MatrixIndexes,MatrixBlock> result = sc.parallelizePairs(list);\n+ JavaPairRDD<MatrixIndexes,MatrixBlock> result = (numParts > 1) ?\n+ sc.parallelizePairs(list, numParts) : sc.parallelizePairs(list);\n+\nif (DMLScript.STATISTICS) {\nStatistics.accSparkParallelizeTime(System.nanoTime() - t0);\nStatistics.incSparkParallelizeCount(1);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MapmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MapmmSPInstruction.java", "diff": "@@ -97,8 +97,11 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixCharacteristics mcRdd = sec.getMatrixCharacteristics(rddVar);\nMatrixCharacteristics mcBc = sec.getMatrixCharacteristics(bcastVar);\n- //get input rdd\n- JavaPairRDD<MatrixIndexes,MatrixBlock> in1 = sec.getBinaryBlockRDDHandleForVariable(rddVar);\n+ //get input rdd with preferred number of partitions to avoid unnecessary repartition\n+ JavaPairRDD<MatrixIndexes,MatrixBlock> in1 = sec.getBinaryBlockRDDHandleForVariable(rddVar,\n+ (requiresFlatMapFunction(type, mcBc) && requiresRepartitioning(\n+ type, mcRdd, mcBc, sec.getSparkContext().defaultParallelism())) ?\n+ getNumRepartitioning(type, mcRdd, mcBc) : -1);\n//investigate if a repartitioning - including a potential flip of broadcast and rdd\n//inputs - is required to ensure moderately sized output partitions (2GB limitation)\n@@ -216,7 +219,8 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nboolean isLargeOutput = (OptimizerUtils.estimatePartitionedSizeExactSparsity(isLeft?mcBc.getRows():mcRdd.getRows(),\nisLeft?mcRdd.getCols():mcBc.getCols(), isLeft?mcBc.getRowsPerBlock():mcRdd.getRowsPerBlock(),\nisLeft?mcRdd.getColsPerBlock():mcBc.getColsPerBlock(), 1.0) / numPartitions) > 1024*1024*1024;\n- return isOuter && isLargeOutput && mcRdd.dimsKnown() && mcBc.dimsKnown();\n+ return isOuter && isLargeOutput && mcRdd.dimsKnown() && mcBc.dimsKnown()\n+ && numPartitions < getNumRepartitioning(type, mcRdd, mcBc);\n}\n/**\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2218] Improved spark mapmm (avoid parallelize-repartition) This patch improves the spark mapmm instruction (broadcast-based matrix multiply) by avoiding unnecessary shuffle for repartitioning - which is used to guarantee output partition size - if the input is a parallelized RDD. For this scenario, we now create the parallelized RDD with right number of partitions.
49,738
30.03.2018 20:57:48
25,200
022e046d3c47386d5020b45c57e61e3e0ee306e7
Performance checkpointing of ultra-sparse matrices This patch improves the checkpointing (i.e., distributed in-memory caching) of ultra-sparse matrices by avoiding unnecessary MCSR-to-CSR conversion for empty blocks, which is unnecessary and causes substantial GC overhead if the fraction of empty 1kx1k blocks is very large.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/functions/CreateSparseBlockFunction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/functions/CreateSparseBlockFunction.java", "diff": "@@ -45,7 +45,8 @@ public class CreateSparseBlockFunction implements Function<MatrixBlock,MatrixBlo\n{\n//convert given block to CSR representation if in sparse format\n//but allow shallow pass-through if already in CSR representation.\n- if( arg0.isInSparseFormat() && !(arg0 instanceof CompressedMatrixBlock) )\n+ if( arg0.isInSparseFormat() && !arg0.isEmptyBlock(false)\n+ && !(arg0 instanceof CompressedMatrixBlock) )\nreturn new MatrixBlock(arg0, _stype, false);\nelse //pass through dense\nreturn arg0;\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2221] Performance checkpointing of ultra-sparse matrices This patch improves the checkpointing (i.e., distributed in-memory caching) of ultra-sparse matrices by avoiding unnecessary MCSR-to-CSR conversion for empty blocks, which is unnecessary and causes substantial GC overhead if the fraction of empty 1kx1k blocks is very large.
49,738
31.03.2018 14:54:28
25,200
015b2731893b5f630a0bdfb8cb0efdf86e84fd05
Repartition ultra-sparse matrices to preferred #parts This patch improves the spark checkpointing (i.e., distributed caching) logic by repartitioning ultra-sparse matrices to the preferred number of partitions as multiple of the default parallelism. Furthermore, this also makes a minor improvement for empty block handling on aggregating ultra-sparse matrices to avoid unnecessary GC overhead.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CheckpointSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CheckpointSPInstruction.java", "diff": "@@ -41,6 +41,7 @@ import org.apache.sysml.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysml.runtime.matrix.data.MatrixIndexes;\nimport org.apache.sysml.runtime.matrix.data.SparseBlock;\nimport org.apache.sysml.runtime.matrix.operators.Operator;\n+import org.apache.sysml.runtime.util.UtilFunctions;\npublic class CheckpointSPInstruction extends UnarySPInstruction {\n// default storage level\n@@ -100,19 +101,28 @@ public class CheckpointSPInstruction extends UnarySPInstruction {\nJavaPairRDD<?,?> out = null;\nif( !in.getStorageLevel().equals( _level ) )\n{\n- //(trigger coalesce if intended number of partitions exceeded by 20%\n- //and not hash partitioned to avoid losing the existing partitioner)\n+ //determine need for coalesce or repartition, and csr conversion\nint numPartitions = SparkUtils.getNumPreferredPartitions(mcIn, in);\nboolean coalesce = ( 1.2*numPartitions < in.getNumPartitions()\n&& !SparkUtils.isHashPartitioned(in) && in.getNumPartitions()\n> SparkExecutionContext.getDefaultParallelism(true));\n+ boolean repartition = mcIn.dimsKnown(true) && mcIn.isUltraSparse()\n+ && numPartitions > in.getNumPartitions();\n+ boolean mcsr2csr = input1.getDataType()==DataType.MATRIX\n+ && OptimizerUtils.checkSparseBlockCSRConversion(mcIn)\n+ && !_level.equals(Checkpoint.SER_STORAGE_LEVEL);\n//checkpoint pre-processing rdd operations\nif( coalesce ) {\n//merge partitions without shuffle if too many partitions\nout = in.coalesce( numPartitions );\n}\n- else {\n+ else if( repartition ) {\n+ //repartition to preferred size as multiple of default parallelism\n+ out = in.repartition(UtilFunctions.roundToNext(numPartitions,\n+ SparkExecutionContext.getDefaultParallelism(true)));\n+ }\n+ else if( !mcsr2csr ) {\n//since persist is an in-place marker for a storage level, we\n//apply a narrow shallow copy to allow for short-circuit collects\nif( input1.getDataType() == DataType.MATRIX )\n@@ -122,11 +132,12 @@ public class CheckpointSPInstruction extends UnarySPInstruction {\nout = ((JavaPairRDD<Long,FrameBlock>)in)\n.mapValues(new CopyFrameBlockFunction(false));\n}\n+ else {\n+ out = in;\n+ }\n//convert mcsr into memory-efficient csr if potentially sparse\n- if( input1.getDataType()==DataType.MATRIX\n- && OptimizerUtils.checkSparseBlockCSRConversion(mcIn)\n- && !_level.equals(Checkpoint.SER_STORAGE_LEVEL) ) {\n+ if( mcsr2csr ) {\nout = ((JavaPairRDD<MatrixIndexes,MatrixBlock>)out)\n.mapValues(new CreateSparseBlockFunction(SparseBlock.Type.CSR));\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/utils/RDDAggregateUtils.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/utils/RDDAggregateUtils.java", "diff": "@@ -262,14 +262,16 @@ public class RDDAggregateUtils\npublic CorrMatrixBlock call(CorrMatrixBlock arg0, MatrixBlock arg1)\nthrows Exception\n{\n+ if( arg1.isEmptyBlock(false) )\n+ return arg0;\n+\n//get current block and correction\nMatrixBlock value = arg0.getValue();\nMatrixBlock corr = arg0.getCorrection();\n//correction block allocation on demand\n- if( corr == null ){\n+ if( corr == null )\ncorr = new MatrixBlock(value.getNumRows(), value.getNumColumns(), false);\n- }\n//aggregate other input and maintain corrections\n//(existing value and corr are used in place)\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/MatrixCharacteristics.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/MatrixCharacteristics.java", "diff": "@@ -24,6 +24,7 @@ import java.io.Serializable;\nimport java.util.Arrays;\nimport java.util.HashMap;\n+import org.apache.sysml.hops.OptimizerUtils;\nimport org.apache.sysml.lops.MMTSJ.MMTSJType;\nimport org.apache.sysml.runtime.instructions.mr.AggregateBinaryInstruction;\nimport org.apache.sysml.runtime.instructions.mr.AggregateInstruction;\n@@ -61,6 +62,7 @@ import org.apache.sysml.runtime.instructions.mr.UaggOuterChainInstruction;\nimport org.apache.sysml.runtime.instructions.mr.UnaryInstruction;\nimport org.apache.sysml.runtime.instructions.mr.UnaryMRInstructionBase;\nimport org.apache.sysml.runtime.instructions.mr.ZeroOutInstruction;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysml.runtime.matrix.operators.AggregateBinaryOperator;\nimport org.apache.sysml.runtime.matrix.operators.AggregateUnaryOperator;\nimport org.apache.sysml.runtime.matrix.operators.ReorgOperator;\n@@ -225,6 +227,11 @@ public class MatrixCharacteristics implements Serializable\nreturn ( !ubNnz && nonZero >= 0 );\n}\n+ public boolean isUltraSparse() {\n+ return dimsKnown(true) && OptimizerUtils.getSparsity(this)\n+ < MatrixBlock.ULTRA_SPARSITY_TURN_POINT;\n+ }\n+\npublic boolean mightHaveEmptyBlocks() {\nlong singleBlk = Math.max(Math.min(numRows, numRowsPerBlock),1)\n* Math.max(Math.min(numColumns, numColumnsPerBlock),1);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2223] Repartition ultra-sparse matrices to preferred #parts This patch improves the spark checkpointing (i.e., distributed caching) logic by repartitioning ultra-sparse matrices to the preferred number of partitions as multiple of the default parallelism. Furthermore, this also makes a minor improvement for empty block handling on aggregating ultra-sparse matrices to avoid unnecessary GC overhead.
49,738
31.03.2018 15:05:59
25,200
2b3aefe79446b3b1ab13640566a37e11f620ee96
[HOTFIX][SYSTEMML-2219] Fix ultra-sparse/ultra-sparse matrix multiply This patch fixes the improved ultra-sparse matrix multiply for special cases of ultra-sparse x ultra-sparse matrix multiply where the rhs has entirely empty rows.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixMult.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixMult.java", "diff": "@@ -1512,17 +1512,18 @@ public class LibMatrixMult\nif( alen==1 ) {\n//row selection (now aggregation) with potential scaling\nint aix = aixs[apos];\n+ int lnnz = 0;\nif( rightSparse ) { //sparse right matrix (full row copy)\nif( !m2.sparseBlock.isEmpty(aix) ) {\nret.rlen=m;\nret.allocateSparseRowsBlock(false); //allocation on demand\nboolean ldeep = (m2.sparseBlock instanceof SparseBlockMCSR);\nret.sparseBlock.set(i, m2.sparseBlock.get(aix), ldeep);\n- ret.nonZeros += ret.sparseBlock.size(i);\n+ ret.nonZeros += (lnnz = ret.sparseBlock.size(i));\n}\n}\nelse { //dense right matrix (append all values)\n- int lnnz = (int)m2.recomputeNonZeros(aix, aix, 0, n-1);\n+ lnnz = (int)m2.recomputeNonZeros(aix, aix, 0, n-1);\nif( lnnz > 0 ) {\nc.allocate(i, lnnz); //allocate once\ndouble[] bvals = m2.getDenseBlock().values(aix);\n@@ -1532,7 +1533,7 @@ public class LibMatrixMult\n}\n}\n//optional scaling if not pure selection\n- if( avals[apos] != 1 )\n+ if( avals[apos] != 1 && lnnz > 0 )\nvectMultiplyInPlace(avals[apos], c.values(i), c.pos(i), c.size(i));\n}\nelse //GENERAL CASE\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/FullMatrixMultiplicationUltraSparseTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/binary/matrix_full_other/FullMatrixMultiplicationUltraSparseTest.java", "diff": "@@ -24,7 +24,7 @@ import java.util.HashMap;\nimport org.junit.AfterClass;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n-\n+import org.apache.sysml.api.DMLScript;\nimport org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;\nimport org.apache.sysml.lops.LopProperties.ExecType;\nimport org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;\n@@ -34,7 +34,6 @@ import org.apache.sysml.test.utils.TestUtils;\npublic class FullMatrixMultiplicationUltraSparseTest extends AutomatedTestBase\n{\n-\nprivate final static String TEST_NAME = \"FullMatrixMultiplication\";\nprivate final static String TEST_DIR = \"functions/binary/matrix_full_other/\";\nprivate final static String TEST_CLASS_DIR = TEST_DIR + FullMatrixMultiplicationUltraSparseTest.class.getSimpleName() + \"/\";\n@@ -83,62 +82,77 @@ public class FullMatrixMultiplicationUltraSparseTest extends AutomatedTestBase\n}\n@Test\n- public void testMMDenseUltraSparseCP()\n- {\n+ public void testMMDenseUltraSparseCP() {\nrunMatrixMatrixMultiplicationTest(SparsityType.DENSE, SparsityType.ULTRA_SPARSE, ExecType.CP);\n}\n@Test\n- public void testMMSparseUltraSparseCP()\n- {\n+ public void testMMSparseUltraSparseCP() {\nrunMatrixMatrixMultiplicationTest(SparsityType.SPARSE, SparsityType.ULTRA_SPARSE, ExecType.CP);\n}\n@Test\n- public void testMMUltraSparseDenseCP()\n- {\n+ public void testMMUltraSparseDenseCP() {\nrunMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.DENSE, ExecType.CP);\n}\n@Test\n- public void testMMUltraSparseSparseCP()\n- {\n+ public void testMMUltraSparseSparseCP() {\nrunMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.SPARSE, ExecType.CP);\n}\n@Test\n- public void testMMUltraSparseUltraSparseCP()\n- {\n+ public void testMMUltraSparseUltraSparseCP() {\nrunMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.ULTRA_SPARSE, ExecType.CP);\n}\n@Test\n- public void testMMDenseUltraSparseMR()\n- {\n+ public void testMMDenseUltraSparseSP() {\n+ runMatrixMatrixMultiplicationTest(SparsityType.DENSE, SparsityType.ULTRA_SPARSE, ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testMMSparseUltraSparseSP() {\n+ runMatrixMatrixMultiplicationTest(SparsityType.SPARSE, SparsityType.ULTRA_SPARSE, ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testMMUltraSparseDenseSP() {\n+ runMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.DENSE, ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testMMUltraSparseSparseSP() {\n+ runMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.SPARSE, ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testMMUltraSparseUltraSparseSP() {\n+ runMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.ULTRA_SPARSE, ExecType.SPARK);\n+ }\n+\n+ @Test\n+ public void testMMDenseUltraSparseMR() {\nrunMatrixMatrixMultiplicationTest(SparsityType.DENSE, SparsityType.ULTRA_SPARSE, ExecType.MR);\n}\n@Test\n- public void testMMSparseUltraSparseMR()\n- {\n+ public void testMMSparseUltraSparseMR() {\nrunMatrixMatrixMultiplicationTest(SparsityType.SPARSE, SparsityType.ULTRA_SPARSE, ExecType.MR);\n}\n@Test\n- public void testMMUltraSparseDenseMR()\n- {\n+ public void testMMUltraSparseDenseMR() {\nrunMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.DENSE, ExecType.MR);\n}\n@Test\n- public void testMMUltraSparseSparseMR()\n- {\n+ public void testMMUltraSparseSparseMR() {\nrunMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.SPARSE, ExecType.MR);\n}\n@Test\n- public void testMMUltraSparseUltraSparseMR()\n- {\n+ public void testMMUltraSparseUltraSparseMR() {\nrunMatrixMatrixMultiplicationTest(SparsityType.ULTRA_SPARSE, SparsityType.ULTRA_SPARSE, ExecType.MR);\n}\n@@ -150,11 +164,16 @@ public class FullMatrixMultiplicationUltraSparseTest extends AutomatedTestBase\n*/\nprivate void runMatrixMatrixMultiplicationTest( SparsityType sparseM1, SparsityType sparseM2, ExecType instType)\n{\n- //setup exec type, rows, cols\n-\n- //rtplatform for MR\nRUNTIME_PLATFORM platformOld = rtplatform;\n- rtplatform = (instType==ExecType.MR) ? RUNTIME_PLATFORM.HADOOP : RUNTIME_PLATFORM.HYBRID;\n+ switch( instType ){\n+ case MR: rtplatform = RUNTIME_PLATFORM.HADOOP; break;\n+ case SPARK: rtplatform = RUNTIME_PLATFORM.SPARK; break;\n+ default: rtplatform = RUNTIME_PLATFORM.HYBRID; break;\n+ }\n+\n+ boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\n+ if( rtplatform == RUNTIME_PLATFORM.SPARK )\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\ntry\n{\n@@ -194,8 +213,8 @@ public class FullMatrixMultiplicationUltraSparseTest extends AutomatedTestBase\nHashMap<CellIndex, Double> rfile = readRMatrixFromFS(\"C\");\nTestUtils.compareMatrices(dmlfile, rfile, eps, \"Stat-DML\", \"Stat-R\");\n}\n- finally\n- {\n+ finally {\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\nrtplatform = platformOld;\n}\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX][SYSTEMML-2219] Fix ultra-sparse/ultra-sparse matrix multiply This patch fixes the improved ultra-sparse matrix multiply for special cases of ultra-sparse x ultra-sparse matrix multiply where the rhs has entirely empty rows.
49,738
31.03.2018 19:06:19
25,200
addd6e121ac8d81af0f90859666b9ac1ec1e5009
Fix reblock ultra-sparse, incl mem efficiency read This patch fixes the robustness of reblocking ultra-sparse matrices by hardening the CSR index lookups, and better handling of empty blocks on reblock. Furthermore, this also includes a fix for avoiding unnecessary csr block creation on initial read for empty blocks.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/functions/ExtractBlockForBinaryReblock.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/functions/ExtractBlockForBinaryReblock.java", "diff": "@@ -70,28 +70,26 @@ public class ExtractBlockForBinaryReblock implements PairFlatMapFunction<Tuple2<\nlong endRowGlobalCellIndex = getEndGlobalIndex(ixIn.getRowIndex(), true, true);\nlong startColGlobalCellIndex = UtilFunctions.computeCellIndex(ixIn.getColumnIndex(), in_bclen, 0);\nlong endColGlobalCellIndex = getEndGlobalIndex(ixIn.getColumnIndex(), true, false);\n- assert(startRowGlobalCellIndex <= endRowGlobalCellIndex && startColGlobalCellIndex <= endColGlobalCellIndex);\nlong out_startRowBlockIndex = UtilFunctions.computeBlockIndex(startRowGlobalCellIndex, out_brlen);\nlong out_endRowBlockIndex = UtilFunctions.computeBlockIndex(endRowGlobalCellIndex, out_brlen);\nlong out_startColBlockIndex = UtilFunctions.computeBlockIndex(startColGlobalCellIndex, out_bclen);\nlong out_endColBlockIndex = UtilFunctions.computeBlockIndex(endColGlobalCellIndex, out_bclen);\n- assert(out_startRowBlockIndex <= out_endRowBlockIndex && out_startColBlockIndex <= out_endColBlockIndex);\nArrayList<Tuple2<MatrixIndexes, MatrixBlock>> retVal = new ArrayList<>();\nfor(long i = out_startRowBlockIndex; i <= out_endRowBlockIndex; i++) {\nfor(long j = out_startColBlockIndex; j <= out_endColBlockIndex; j++) {\nMatrixIndexes indx = new MatrixIndexes(i, j);\n- long rowLower = Math.max(UtilFunctions.computeCellIndex(i, out_brlen, 0), startRowGlobalCellIndex);\n- long rowUpper = Math.min(getEndGlobalIndex(i, false, true), endRowGlobalCellIndex);\n- long colLower = Math.max(UtilFunctions.computeCellIndex(j, out_bclen, 0), startColGlobalCellIndex);\n- long colUpper = Math.min(getEndGlobalIndex(j, false, false), endColGlobalCellIndex);\n-\nint new_lrlen = UtilFunctions.computeBlockSize(rlen, i, out_brlen);\nint new_lclen = UtilFunctions.computeBlockSize(clen, j, out_bclen);\nMatrixBlock blk = new MatrixBlock(new_lrlen, new_lclen, true);\n+ if( !in.isEmptyBlock(false) ) {\n+ long rowLower = Math.max(UtilFunctions.computeCellIndex(i, out_brlen, 0), startRowGlobalCellIndex);\n+ long rowUpper = Math.min(getEndGlobalIndex(i, false, true), endRowGlobalCellIndex);\n+ long colLower = Math.max(UtilFunctions.computeCellIndex(j, out_bclen, 0), startColGlobalCellIndex);\n+ long colUpper = Math.min(getEndGlobalIndex(j, false, false), endColGlobalCellIndex);\nint in_i1 = UtilFunctions.computeCellInBlock(rowLower, in_brlen);\nint out_i1 = UtilFunctions.computeCellInBlock(rowLower, out_brlen);\n@@ -99,10 +97,11 @@ public class ExtractBlockForBinaryReblock implements PairFlatMapFunction<Tuple2<\nint in_j1 = UtilFunctions.computeCellInBlock(colLower, in_bclen);\nint out_j1 = UtilFunctions.computeCellInBlock(colLower, out_bclen);\nfor(long j1 = colLower; j1 <= colUpper; j1++, in_j1++, out_j1++) {\n- double val = in.getValue(in_i1, in_j1);\n+ double val = in.quickGetValue(in_i1, in_j1);\nblk.appendValue(out_i1, out_j1, val);\n}\n}\n+ }\nretVal.add(new Tuple2<>(indx, blk));\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "diff": "@@ -184,11 +184,13 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab\nthrow new RuntimeException(\"Sparse matrix block expected.\");\n//deep copy and change sparse block type\n+ if( !that.isEmptyBlock(false) ) {\nnonZeros = that.nonZeros;\nestimatedNNzsPerRow = that.estimatedNNzsPerRow;\nsparseBlock = SparseBlockFactory\n.copySparseBlock(stype, that.sparseBlock, deep);\n}\n+ }\n////////\n// Initialization methods\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCSR.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseBlockCSR.java", "diff": "@@ -734,6 +734,8 @@ public class SparseBlockCSR extends SparseBlock\n@Override\npublic double get(int r, int c) {\n+ if( isEmpty(r) )\n+ return 0;\nint pos = pos(r);\nint len = size(r);\n@@ -744,6 +746,8 @@ public class SparseBlockCSR extends SparseBlock\n@Override\npublic SparseRow get(int r) {\n+ if( isEmpty(r) )\n+ return new SparseRowScalar();\nint pos = pos(r);\nint len = size(r);\n@@ -751,7 +755,6 @@ public class SparseBlockCSR extends SparseBlock\nSystem.arraycopy(_indexes, pos, row.indexes(), 0, len);\nSystem.arraycopy(_values, pos, row.values(), 0, len);\nrow.setSize(len);\n-\nreturn row;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2225] Fix reblock ultra-sparse, incl mem efficiency read This patch fixes the robustness of reblocking ultra-sparse matrices by hardening the CSR index lookups, and better handling of empty blocks on reblock. Furthermore, this also includes a fix for avoiding unnecessary csr block creation on initial read for empty blocks.
49,738
01.04.2018 13:53:10
25,200
0abeb60b3c70925adb1b4e3ee8e4e4e42aa5f316
[MINOR] Additional tests for row/col means/vars and matrix reshapes
[ { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysml/test/integration/functions/misc/RewriteNNIssueTest.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.sysml.test.integration.functions.misc;\n+\n+import org.junit.Test;\n+\n+import java.util.HashMap;\n+\n+import org.apache.sysml.hops.OptimizerUtils;\n+import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysml.test.integration.AutomatedTestBase;\n+import org.apache.sysml.test.integration.TestConfiguration;\n+import org.apache.sysml.test.utils.TestUtils;\n+\n+public class RewriteNNIssueTest extends AutomatedTestBase\n+{\n+ private static final String TEST_NAME = \"RewriteNNIssue\";\n+\n+ private static final String TEST_DIR = \"functions/misc/\";\n+ private static final String TEST_CLASS_DIR = TEST_DIR + RewriteNNIssueTest.class.getSimpleName() + \"/\";\n+\n+ private double eps = Math.pow(10, -10);\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration( TEST_NAME, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME, new String[] { \"R\" }) );\n+ }\n+\n+ @Test\n+ public void testNNIssueRewrite() {\n+ runNNIssueTest(true);\n+ }\n+\n+ @Test\n+ public void testNNIssueNoRewrite() {\n+ runNNIssueTest(false);\n+ }\n+\n+ private void runNNIssueTest(boolean rewrites)\n+ {\n+ boolean oldFlag = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+\n+ try {\n+ TestConfiguration config = getTestConfiguration(TEST_NAME);\n+ loadTestConfiguration(config);\n+\n+ String HOME = SCRIPT_DIR + TEST_DIR;\n+ fullDMLScriptName = HOME + TEST_NAME + \".dml\";\n+ programArgs = new String[]{ \"-stats\",\"-args\", output(\"R\") };\n+ fullRScriptName = HOME + TEST_NAME + \".R\";\n+ rCmd = getRCmd(expectedDir());\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewrites;\n+\n+ //run test\n+ runTest(true, false, null, -1);\n+ runRScript(true);\n+\n+ //compare matrices\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"R\");\n+ HashMap<CellIndex, Double> rfile = readRMatrixFromFS(\"R\");\n+ TestUtils.compareMatrices(dmlfile, rfile, eps, \"Stat-DML\", \"Stat-R\");\n+ }\n+ finally {\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = oldFlag;\n+ }\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/misc/RewriteNNIssue.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+options(digits=22)\n+library(Matrix)\n+library(matrixStats)\n+\n+N = 2\n+C = 2\n+Hin = 3\n+Win = 4\n+\n+X = matrix(cbind(seq(1,20),seq(1,20),seq(1,8)), nrow=2, ncol=24, byrow=TRUE)\n+gamma = matrix(c(1,2), byrow=TRUE, nrow=2, ncol=1)\n+beta = matrix(c(0,1), byrow=TRUE, nrow=2, ncol=1)\n+ema_mean = matrix(c(4,5), byrow=TRUE, nrow=2, ncol=1)\n+ema_var = matrix(c(2,3), byrow=TRUE, nrow=2, ncol=1)\n+mu = 0.95\n+epsilon = 1e-4\n+\n+subgrp_means = matrix(colMeans(X), nrow=C, ncol=Hin*Win, byrow=TRUE)\n+subgrp_vars = matrix(colVars(X) * ((N-1)/N), nrow=C, ncol=Hin*Win, byrow=TRUE)\n+mean = rowMeans(subgrp_means) # shape (C, 1)\n+var = rowMeans(subgrp_vars) + rowVars(subgrp_means)*(((Hin*Win)-1)/(Hin*Win))\n+ema_mean_upd = mu*ema_mean + (1-mu)*mean\n+ema_var_upd = mu*ema_var + (1-mu)*var\n+\n+R = cbind(mean, var, ema_mean_upd, ema_var_upd)\n+\n+writeMM(as(R, \"CsparseMatrix\"), paste(args[1], \"R\", sep=\"\"));\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/functions/misc/RewriteNNIssue.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 = 2\n+C = 2\n+Hin = 3\n+Win = 4\n+X = matrix(rbind(seq(1,20),seq(1,20),seq(1,8)), rows=2, cols=24)\n+gamma = matrix(\"1 2\", rows=2, cols=1)\n+beta = matrix(\"0 1\", rows=2, cols=1)\n+ema_mean = matrix(\"4 5\", rows=2, cols=1)\n+ema_var = matrix(\"2 3\", rows=2, cols=1)\n+mu = 0.95\n+epsilon = 1e-4\n+\n+subgrp_means = matrix(colMeans(X), rows=C, cols=Hin*Win)\n+subgrp_vars = matrix(colVars(X) * ((N-1)/N), rows=C, cols=Hin*Win)\n+mean = rowMeans(subgrp_means) # shape (C, 1)\n+var = rowMeans(subgrp_vars) + rowVars(subgrp_means)*(((Hin*Win)-1)/(Hin*Win))\n+ema_mean_upd = mu*ema_mean + (1-mu)*mean\n+ema_var_upd = mu*ema_var + (1-mu)*var\n+\n+R = cbind(mean, var, ema_mean_upd, ema_var_upd)\n+\n+write(R,$1)\n" }, { "change_type": "MODIFY", "old_path": "src/test_suites/java/org/apache/sysml/test/integration/functions/misc/ZPackageSuite.java", "new_path": "src/test_suites/java/org/apache/sysml/test/integration/functions/misc/ZPackageSuite.java", "diff": "@@ -65,6 +65,7 @@ import org.junit.runners.Suite;\nRewriteLoopVectorization.class,\nRewriteMatrixMultChainOptTest.class,\nRewriteMergeBlocksTest.class,\n+ RewriteNNIssueTest.class,\nRewritePushdownSumBinaryMult.class,\nRewritePushdownSumOnBinaryTest.class,\nRewritePushdownUaggTest.class,\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Additional tests for row/col means/vars and matrix reshapes
49,698
01.04.2018 16:18:19
25,200
607a402bcf809d951e9634479d0db635e19c28ce
Fix various stream resource leaks via auto closing Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/jmlc/Connection.java", "new_path": "src/main/java/org/apache/sysml/api/jmlc/Connection.java", "diff": "@@ -421,7 +421,9 @@ public class Connection implements Closeable\n* @throws IOException if IOException occurs\n*/\npublic double[][] convertToDoubleMatrix(String input, int rows, int cols) throws IOException {\n- return convertToDoubleMatrix(IOUtilFunctions.toInputStream(input), rows, cols);\n+ try( InputStream is = IOUtilFunctions.toInputStream(input) ) {\n+ return convertToDoubleMatrix(is, rows, cols);\n+ }\n}\n/**\n@@ -467,7 +469,9 @@ public class Connection implements Closeable\n* @throws IOException if IOException occurs\n*/\npublic MatrixBlock convertToMatrix(String input, String meta) throws IOException {\n- return convertToMatrix(IOUtilFunctions.toInputStream(input), meta);\n+ try( InputStream is = IOUtilFunctions.toInputStream(input) ) {\n+ return convertToMatrix(is, meta);\n+ }\n}\n/**\n@@ -509,7 +513,9 @@ public class Connection implements Closeable\n* @throws IOException if IOException occurs\n*/\npublic MatrixBlock convertToMatrix(String input, int rows, int cols) throws IOException {\n- return convertToMatrix(IOUtilFunctions.toInputStream(input), rows, cols);\n+ try( InputStream is = IOUtilFunctions.toInputStream(input) ) {\n+ return convertToMatrix(is, rows, cols);\n+ }\n}\n/**\n@@ -655,7 +661,9 @@ public class Connection implements Closeable\n* @throws IOException if IOException occurs\n*/\npublic String[][] convertToStringFrame(String input, int rows, int cols) throws IOException {\n- return convertToStringFrame(IOUtilFunctions.toInputStream(input), rows, cols);\n+ try( InputStream is = IOUtilFunctions.toInputStream(input) ) {\n+ return convertToStringFrame(is, rows, cols);\n+ }\n}\n/**\n@@ -701,7 +709,9 @@ public class Connection implements Closeable\n* @throws IOException if IOException occurs\n*/\npublic FrameBlock convertToFrame(String input, String meta) throws IOException {\n- return convertToFrame(IOUtilFunctions.toInputStream(input), meta);\n+ try( InputStream is = IOUtilFunctions.toInputStream(input) ) {\n+ return convertToFrame(is, meta);\n+ }\n}\n/**\n@@ -743,7 +753,9 @@ public class Connection implements Closeable\n* @throws IOException if IOException occurs\n*/\npublic FrameBlock convertToFrame(String input, int rows, int cols) throws IOException {\n- return convertToFrame(IOUtilFunctions.toInputStream(input), rows, cols);\n+ try( InputStream is = IOUtilFunctions.toInputStream(input) ) {\n+ return convertToFrame(is, rows, cols);\n+ }\n}\n/**\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/api/mlcontext/ScriptFactory.java", "new_path": "src/main/java/org/apache/sysml/api/mlcontext/ScriptFactory.java", "diff": "@@ -298,8 +298,11 @@ public class ScriptFactory {\nif (!resourcePath.startsWith(\"/\")) {\nresourcePath = \"/\" + resourcePath;\n}\n- InputStream inputStream = ScriptFactory.class.getResourceAsStream(resourcePath);\n+ try( InputStream inputStream = ScriptFactory.class.getResourceAsStream(resourcePath) ) {\nreturn scriptFromInputStream(inputStream, scriptType).setName(resourcePath);\n+ } catch (Exception e){\n+ throw new MLContextException(\"Error trying to read script from resource: \"+ resourcePath, e);\n+ }\n}\n/**\n@@ -425,8 +428,7 @@ public class ScriptFactory {\nif ((!urlString.toLowerCase().startsWith(\"http:\")) && (!urlString.toLowerCase().startsWith(\"https:\"))) {\nthrow new MLContextException(\"Currently only reading from http and https URLs is supported\");\n}\n- try {\n- InputStream is = url.openStream();\n+ try( InputStream is = url.openStream() ) {\nreturn IOUtils.toString(is);\n} catch (IOException e) {\nthrow new MLContextException(\"Error trying to read script string from URL: \" + url, e);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/ParserWrapper.java", "new_path": "src/main/java/org/apache/sysml/parser/ParserWrapper.java", "diff": "@@ -124,7 +124,9 @@ public abstract class ParserWrapper {\n{\nString resPath = scriptPathToResourcePath(script);\nLOG.debug(\"Looking for the following resource from the SystemML jar file: \" + resPath);\n- InputStream is = ParserWrapper.class.getResourceAsStream(resPath);\n+ InputStream is = null;\n+ try {\n+ is = ParserWrapper.class.getResourceAsStream(resPath);\nif (is == null) {\nif (resPath.startsWith(\"/scripts\")) {\nLOG.error(\"Failed to read from the file system ('\" + script + \"') or SystemML jar file ('\" + resPath + \"')\");\n@@ -143,6 +145,10 @@ public abstract class ParserWrapper {\nString s = IOUtils.toString(is);\nreturn s;\n}\n+ finally {\n+ IOUtilFunctions.closeSilently(is);\n+ }\n+ }\nfinally {\nIOUtilFunctions.closeSilently(in);\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/gpu/context/JCudaKernels.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/gpu/context/JCudaKernels.java", "diff": "@@ -125,10 +125,8 @@ public class JCudaKernels {\n* @return\n*/\nprivate static Pointer initKernels(String ptxFileName) {\n- InputStream in = null;\nByteArrayOutputStream out = null;\n- try {\n- in = JCudaKernels.class.getResourceAsStream(ptxFileName);\n+ try( InputStream in = JCudaKernels.class.getResourceAsStream(ptxFileName) ) {\nif (in != null) {\nout = new ByteArrayOutputStream();\nbyte buffer[] = new byte[8192];\n@@ -149,7 +147,6 @@ public class JCudaKernels {\nthrow new DMLRuntimeException(\"Could not initialize the kernels\", e);\n} finally {\nIOUtilFunctions.closeSilently(out);\n- IOUtilFunctions.closeSilently(in);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/transform/meta/TfMetaUtils.java", "new_path": "src/main/java/org/apache/sysml/runtime/transform/meta/TfMetaUtils.java", "diff": "@@ -216,7 +216,7 @@ public class TfMetaUtils\nthrows IOException\n{\n//read column names\n- String colnamesStr = IOUtilFunctions.toString(Connection.class.getResourceAsStream(metapath+\"/\"+TfUtils.TXMTD_COLNAMES));\n+ String colnamesStr = getStringFromResource(metapath+\"/\"+TfUtils.TXMTD_COLNAMES);\nString[] colnames = IOUtilFunctions.split(colnamesStr.trim(), colDelim);\n//read meta data (currently supported: recode, dummycode, bin, omit)\n@@ -228,22 +228,22 @@ public class TfMetaUtils\nString colName = colnames[j];\n//read recode maps for recoded or dummycoded columns\nString name = metapath+\"/\"+\"Recode\"+\"/\"+colName;\n- String map = IOUtilFunctions.toString(Connection.class.getResourceAsStream(name+TfUtils.TXMTD_RCD_MAP_SUFFIX));\n+ String map = getStringFromResource(name+TfUtils.TXMTD_RCD_MAP_SUFFIX);\nif( map != null ) {\nmeta.put(colName, map);\n- String ndistinct = IOUtilFunctions.toString(Connection.class.getResourceAsStream(name+TfUtils.TXMTD_RCD_DISTINCT_SUFFIX));\n+ String ndistinct = getStringFromResource(name+TfUtils.TXMTD_RCD_DISTINCT_SUFFIX);\nrows = Math.max(rows, Integer.parseInt(ndistinct));\n}\n//read binning map for binned columns\nString name2 = metapath+\"/\"+\"Bin\"+\"/\"+colName;\n- String map2 = IOUtilFunctions.toString(Connection.class.getResourceAsStream(name2+TfUtils.TXMTD_BIN_FILE_SUFFIX));\n+ String map2 = getStringFromResource(name2+TfUtils.TXMTD_BIN_FILE_SUFFIX);\nif( map2 != null ) {\nmeta.put(colName, map2);\nrows = Math.max(rows, Integer.parseInt(map2.split(TfUtils.TXMTD_SEP)[4]));\n}\n//read impute value for mv columns\nString name3 = metapath+File.separator+\"Impute\"+File.separator+colName;\n- String map3 = IOUtilFunctions.toString(Connection.class.getResourceAsStream(name3+TfUtils.TXMTD_MV_FILE_SUFFIX));\n+ String map3 = getStringFromResource(name3+TfUtils.TXMTD_MV_FILE_SUFFIX);\nif( map3 != null ) {\nmvmeta.put(colName, map3);\n}\n@@ -389,4 +389,10 @@ public class TfMetaUtils\nthrow new IOException(ex);\n}\n}\n+\n+ private static String getStringFromResource(String path) throws IOException {\n+ try(InputStream is = Connection.class.getResourceAsStream(path) ) {\n+ return IOUtilFunctions.toString(is);\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/utils/NativeHelper.java", "new_path": "src/main/java/org/apache/sysml/utils/NativeHelper.java", "diff": "@@ -37,6 +37,7 @@ import org.apache.sysml.conf.ConfigurationManager;\nimport org.apache.sysml.conf.DMLConfig;\nimport org.apache.sysml.hops.OptimizerUtils;\nimport org.apache.sysml.runtime.DMLRuntimeException;\n+import org.apache.sysml.runtime.io.IOUtilFunctions;\n/**\n* This class helps in loading native library.\n@@ -291,33 +292,25 @@ public class NativeHelper {\nprivate static boolean loadLibraryHelper(String path) {\n- InputStream in = null; OutputStream out = null;\n- try {\n+ OutputStream out = null;\n+ try( InputStream in = NativeHelper.class.getResourceAsStream(\"/lib/\"+path) ) {\n// This logic is added because Java does not allow to load library from a resource file.\n- in = NativeHelper.class.getResourceAsStream(\"/lib/\"+path);\nif(in != null) {\nFile temp = File.createTempFile(path, \"\");\ntemp.deleteOnExit();\nout = FileUtils.openOutputStream(temp);\nIOUtils.copy(in, out);\n- in.close(); in = null;\n- out.close(); out = null;\nSystem.load(temp.getAbsolutePath());\nreturn true;\n}\nelse\nLOG.warn(\"No lib available in the jar:\" + path);\n- } catch(IOException e) {\n+ }\n+ catch(IOException e) {\nLOG.warn(\"Unable to load library \" + path + \" from resource:\" + e.getMessage());\n- } finally {\n- if(out != null)\n- try {\n- out.close();\n- } catch (IOException e) {}\n- if(in != null)\n- try {\n- in.close();\n- } catch (IOException e) {}\n+ }\n+ finally {\n+ IOUtilFunctions.closeSilently(out);\n}\nreturn false;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-1738] Fix various stream resource leaks via auto closing Closes #749.
49,727
01.04.2018 17:14:36
25,200
4a822a22c88b579e935a1b09051c1fe236e18a4b
Add support for builtin constants (PI, INF, NaN) Closes
[ { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysml/parser/BuiltinConstant.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.sysml.parser;\n+\n+import org.apache.commons.lang3.EnumUtils;\n+\n+/**\n+ * These are the builtin constants\n+ */\n+public enum BuiltinConstant {\n+ PI(Math.PI),\n+ INF(Double.POSITIVE_INFINITY),\n+ NaN(Double.NaN);\n+\n+ private DoubleIdentifier _id;\n+\n+ private BuiltinConstant(double d) {\n+ this._id = new DoubleIdentifier(d);\n+ }\n+\n+ public DoubleIdentifier get() {\n+ return this._id;\n+ }\n+\n+ public static boolean contains(String name) {\n+ return EnumUtils.isValidEnum(BuiltinConstant.class, name);\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/StatementBlock.java", "new_path": "src/main/java/org/apache/sysml/parser/StatementBlock.java", "diff": "@@ -784,6 +784,12 @@ public class StatementBlock extends LiveVariableAnalysis implements ParseInfo\nDataIdentifier target = as.getTarget();\nExpression source = as.getSource();\n+ // check if target is builtin constant\n+ if (target != null && BuiltinConstant.contains(target.getName())) {\n+ target.raiseValidateError(String.format(\n+ \"Cannot assign a value to the builtin constant %s.\", target.getName()), false);\n+ }\n+\nif (source instanceof FunctionCallIdentifier) {\n((FunctionCallIdentifier) source).validateExpression(\ndmlProg, ids.getVariables(),currConstVars, conditional);\n@@ -900,6 +906,13 @@ public class StatementBlock extends LiveVariableAnalysis implements ParseInfo\nArrayList<DataIdentifier> targetList = mas.getTargetList();\nExpression source = mas.getSource();\n+ // check if target list contains builtin constant\n+ targetList.forEach(target -> {\n+ if (target != null && BuiltinConstant.contains(target.getName()))\n+ target.raiseValidateError(String.format(\n+ \"Cannot assign a value to the builtin constant %s.\", target.getName()), false);\n+ });\n+\n//MultiAssignmentStatments currently supports only External,\n//User-defined, and Multi-return Builtin function expressions\nif (!(source instanceof DataIdentifier)\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/common/CommonSyntacticValidator.java", "new_path": "src/main/java/org/apache/sysml/parser/common/CommonSyntacticValidator.java", "diff": "@@ -55,6 +55,7 @@ import org.apache.sysml.parser.Statement;\nimport org.apache.sysml.parser.StringIdentifier;\nimport org.apache.sysml.parser.dml.DmlSyntacticValidator;\nimport org.apache.sysml.parser.pydml.PydmlSyntacticValidator;\n+import org.apache.sysml.parser.BuiltinConstant;\n/**\n* Contains fields and (helper) methods common to {@link DmlSyntacticValidator} and {@link PydmlSyntacticValidator}\n@@ -328,6 +329,13 @@ public abstract class CommonSyntacticValidator {\n}\nprotected void exitDataIdExpressionHelper(ParserRuleContext ctx, ExpressionInfo me, ExpressionInfo dataInfo) {\n+ // inject builtin constant\n+ if (dataInfo.expr instanceof DataIdentifier) {\n+ DataIdentifier id = ((DataIdentifier) dataInfo.expr);\n+ if (BuiltinConstant.contains(id.getName())) {\n+ dataInfo.expr = BuiltinConstant.valueOf(id.getName()).get();\n+ }\n+ }\nme.expr = dataInfo.expr;\n// If \"The parameter $X either needs to be passed through commandline or initialized to default value\" validation\n// error occurs, then dataInfo.expr is null which would cause a null pointer exception with the following code.\n@@ -430,7 +438,7 @@ public abstract class CommonSyntacticValidator {\ninfo.stmt = new AssignmentStatement(ctx, target, source, currentFile);\n} catch (LanguageException e) {\n// TODO: extract more meaningful info from this exception.\n- notifyErrorListeners(\"invalid assignment\", lhsStart);\n+ notifyErrorListeners(\"invalid assignment: \" + e.getMessage(), lhsStart);\nreturn;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/mlcontext/MLContextTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/mlcontext/MLContextTest.java", "diff": "@@ -89,6 +89,14 @@ import scala.collection.Seq;\npublic class MLContextTest extends MLContextTestBase {\n+ @Test\n+ public void testBuiltinConstantsTest() {\n+ System.out.println(\"MLContextTest - basic builtin constants test\");\n+ Script script = dmlFromFile(baseDirectory + File.separator + \"builtin-constants-test.dml\");\n+ ml.execute(script);\n+ Assert.assertTrue(Statistics.getNoOfExecutedSPInst() == 0);\n+ }\n+\n@Test\npublic void testBasicExecuteEvalTest() {\nSystem.out.println(\"MLContextTest - basic eval test\");\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/org/apache/sysml/api/mlcontext/builtin-constants-test.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 func using builtin constant PI\n+f1 = function (double r) return (double res) {\n+ res = PI * r * r\n+}\n+\n+# use builtin constant PI in main func\n+res = PI * 1000\n+print(res)\n+\n+# use builtin constant NaN\n+print(NaN + 1)\n+\n+# use builtin constant INF\n+if (1 / 0 == INF) {\n+ print(\"1 / 0 is an infinity.\")\n+}\n+\n+print(f1(100))\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2078] Add support for builtin constants (PI, INF, NaN) Closes #752.
49,738
02.04.2018 15:28:31
25,200
847e5bcab97ed195fcbb33a7974564add4fdfdbd
[HOTFIX] Fix invalid assignments in ID3 to new builtin constants
[ { "change_type": "MODIFY", "old_path": "src/test/scripts/applications/id3/id3.R", "new_path": "src/test/scripts/applications/id3/id3.R", "diff": "@@ -87,9 +87,9 @@ id3_learn = function(X, y, X_subset, attributes, minsplit)\nhist_labels1 = as.matrix(hist_labels1_helper[,2])\nnum_samples1 = sum(Tj)\nzero_entries_in_hist = (hist_labels1 == 0)\n- pi = hist_labels1/num_samples1\n- log_term = zero_entries_in_hist*1 + (1-zero_entries_in_hist)*pi\n- entropy_vector = -pi*log(log_term)\n+ piv = hist_labels1/num_samples1\n+ log_term = zero_entries_in_hist*1 + (1-zero_entries_in_hist)*piv\n+ entropy_vector = -piv*log(log_term)\nentropy = sum(entropy_vector)\nhxt_vector[j,1] = sum(Tj)/sum(X_subset)*entropy\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/applications/id3/id3.dml", "new_path": "src/test/scripts/applications/id3/id3.dml", "diff": "@@ -150,9 +150,9 @@ id3_learn = function(Matrix[Double] X, Matrix[Double] y, Matrix[Double] X_subset\nhist_labels1 = aggregate(target=Tj, groups=y, fn=\"sum\")\nnum_samples1 = sum(Tj)\nzero_entries_in_hist = (hist_labels1 == 0)\n- pi = hist_labels1/num_samples1\n- log_term = zero_entries_in_hist*1 + (1-zero_entries_in_hist)*pi\n- entropy_vector = -pi*log(log_term)\n+ piv = hist_labels1/num_samples1\n+ log_term = zero_entries_in_hist*1 + (1-zero_entries_in_hist)*piv\n+ entropy_vector = -piv*log(log_term)\nentropy = sum(entropy_vector)\nhxt_vector[j,1] = sum(Tj)/sum(X_subset)*entropy\n" }, { "change_type": "MODIFY", "old_path": "src/test/scripts/applications/id3/id3.pydml", "new_path": "src/test/scripts/applications/id3/id3.pydml", "diff": "@@ -150,9 +150,9 @@ def id3_learn(X:matrix[float], y:matrix[float], X_subset:matrix[float], attribut\nhist_labels1 = aggregate(target=Tj, groups=y, fn=\"sum\")\nnum_samples1 = sum(Tj)\nzero_entries_in_hist = (hist_labels1 == 0)\n- pi = hist_labels1/num_samples1\n- log_term = zero_entries_in_hist*1 + (1-zero_entries_in_hist)*pi\n- entropy_vector = -pi*log(log_term)\n+ piv = hist_labels1/num_samples1\n+ log_term = zero_entries_in_hist*1 + (1-zero_entries_in_hist)*piv\n+ entropy_vector = -piv*log(log_term)\nentropy = sum(entropy_vector)\nhxt_vector[j-1,0] = sum(Tj)/sum(X_subset)*entropy\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix invalid assignments in ID3 to new builtin constants
49,738
04.04.2018 09:52:12
25,200
836086e1469c456f5748675dbcb46a30ccba6d74
[HOTFIX] Fix corrupted IQM and MEDIAN hops construction
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/DMLTranslator.java", "new_path": "src/main/java/org/apache/sysml/parser/DMLTranslator.java", "diff": "@@ -2611,6 +2611,7 @@ public class DMLTranslator\ncurrBuiltinOp = (expr2 == null) ? new UnaryOp(target.getName(), target.getDataType(), target.getValueType(),\nOpOp1.valueOf(source.getOpCode().name()), expr) : new BinaryOp(target.getName(), target.getDataType(),\ntarget.getValueType(), OpOp2.valueOf(source.getOpCode().name()), expr, expr2);\n+ break;\ncase IFELSE:\ncurrBuiltinOp=new TernaryOp(target.getName(), target.getDataType(), target.getValueType(),\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix corrupted IQM and MEDIAN hops construction
49,698
05.04.2018 18:01:54
25,200
f700df2c88e3f60c5603cccf83927738771f6d8b
Fix compiler/runtime dimension checks for solve Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/parser/BuiltinFunctionExpression.java", "new_path": "src/main/java/org/apache/sysml/parser/BuiltinFunctionExpression.java", "diff": "@@ -1096,7 +1096,8 @@ public class BuiltinFunctionExpression extends DataIdentifier\nraiseValidateError(\"Second input to solve() must be a vector\", conditional);\nif ( getFirstExpr().getOutput().dimsKnown() && getSecondExpr().getOutput().dimsKnown() &&\n- getFirstExpr().getOutput().getDim1() != getSecondExpr().getOutput().getDim1() )\n+ getFirstExpr().getOutput().getDim1() != getSecondExpr().getOutput().getDim1() &&\n+ getFirstExpr().getOutput().getDim1() != getFirstExpr().getOutput().getDim2())\nraiseValidateError(\"Dimension mismatch in a call to solve()\", conditional);\noutput.setDataType(DataType.MATRIX);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibCommonsMath.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibCommonsMath.java", "diff": "@@ -78,8 +78,11 @@ public class LibCommonsMath\n}\npublic static MatrixBlock matrixMatrixOperations(MatrixObject in1, MatrixObject in2, String opcode) {\n- if(opcode.equals(\"solve\"))\n+ if(opcode.equals(\"solve\")) {\n+ if (in1.getNumRows() != in1.getNumColumns())\n+ throw new DMLRuntimeException(\"The A matrix, in solve(A,b) should have squared dimensions.\");\nreturn computeSolve(in1, in2);\n+ }\nreturn null;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-1626] Fix compiler/runtime dimension checks for solve Closes #753.
49,738
06.04.2018 22:35:26
25,200
41526805241eafa1c454df830f1512b20d98dd2a
Improved spark cpmm (partitioning-preserving case) This patch adds a special case to the spark cpmm matrix multiply operator for the special case of matrix-vector multiply and existing matrix partitioning. In this case, we use a different approach that retains the original matrix keys and thus partitioning, which avoids unnecessary shuffle and stages.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CpmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CpmmSPInstruction.java", "diff": "package org.apache.sysml.runtime.instructions.spark;\nimport org.apache.spark.api.java.JavaPairRDD;\n+import org.apache.spark.api.java.JavaRDD;\n+import org.apache.spark.api.java.function.Function;\nimport org.apache.spark.api.java.function.PairFunction;\nimport scala.Tuple2;\n@@ -30,9 +32,12 @@ import org.apache.sysml.runtime.controlprogram.context.ExecutionContext;\nimport org.apache.sysml.runtime.controlprogram.context.SparkExecutionContext;\nimport org.apache.sysml.runtime.functionobjects.Multiply;\nimport org.apache.sysml.runtime.functionobjects.Plus;\n+import org.apache.sysml.runtime.functionobjects.SwapIndex;\nimport org.apache.sysml.runtime.instructions.InstructionUtils;\nimport org.apache.sysml.runtime.instructions.cp.CPOperand;\nimport org.apache.sysml.runtime.instructions.spark.functions.FilterNonEmptyBlocksFunction;\n+import org.apache.sysml.runtime.instructions.spark.functions.FilterNonEmptyBlocksFunction2;\n+import org.apache.sysml.runtime.instructions.spark.functions.ReorgMapFunction;\nimport org.apache.sysml.runtime.instructions.spark.utils.RDDAggregateUtils;\nimport org.apache.sysml.runtime.instructions.spark.utils.SparkUtils;\nimport org.apache.sysml.runtime.matrix.MatrixCharacteristics;\n@@ -42,6 +47,7 @@ import org.apache.sysml.runtime.matrix.mapred.IndexedMatrixValue;\nimport org.apache.sysml.runtime.matrix.operators.AggregateBinaryOperator;\nimport org.apache.sysml.runtime.matrix.operators.AggregateOperator;\nimport org.apache.sysml.runtime.matrix.operators.Operator;\n+import org.apache.sysml.runtime.matrix.operators.ReorgOperator;\n/**\n* Cpmm: cross-product matrix multiplication operation (distributed matrix multiply\n@@ -93,6 +99,23 @@ public class CpmmSPInstruction extends BinarySPInstruction {\nin2 = in2.filter(new FilterNonEmptyBlocksFunction());\n}\n+ if( SparkUtils.isHashPartitioned(in1) //ZIPMM-like CPMM\n+ && mc1.getNumRowBlocks()==1 && mc2.getCols()==1 ) {\n+ //note: if the major input is hash-partitioned and it's a matrix-vector\n+ //multiply, avoid the index mapping to preserve the partitioning similar\n+ //to a ZIPMM but with different transpose characteristics\n+ JavaRDD<MatrixBlock> out = in1\n+ .join(in2.mapToPair(new ReorgMapFunction(\"r'\")))\n+ .values().map(new Cpmm2MultiplyFunction())\n+ .filter(new FilterNonEmptyBlocksFunction2());\n+ MatrixBlock out2 = RDDAggregateUtils.sumStable(out);\n+\n+ //put output block into symbol table (no lineage because single block)\n+ //this also includes implicit maintenance of matrix characteristics\n+ sec.setMatrixOutput(output.getName(), out2, getExtendedOpcode());\n+ }\n+ else //GENERAL CPMM\n+ {\n//compute preferred join degree of parallelism\nint numPreferred = getPreferredParJoin(mc1, mc2, in1.getNumPartitions(), in2.getNumPartitions());\nint numPartJoin = Math.min(getMaxParJoin(mc1, mc2), numPreferred);\n@@ -128,6 +151,7 @@ public class CpmmSPInstruction extends BinarySPInstruction {\nupdateBinaryMMOutputMatrixCharacteristics(sec, true);\n}\n}\n+ }\nprivate static int getPreferredParJoin(MatrixCharacteristics mc1, MatrixCharacteristics mc2, int numPar1, int numPar2) {\nint defPar = SparkExecutionContext.getDefaultParallelism(true);\n@@ -190,4 +214,27 @@ public class CpmmSPInstruction extends BinarySPInstruction {\nreturn new Tuple2<>( ixOut, blkOut );\n}\n}\n+\n+ private static class Cpmm2MultiplyFunction implements Function<Tuple2<MatrixBlock,MatrixBlock>, MatrixBlock>\n+ {\n+ private static final long serialVersionUID = -3718880362385713416L;\n+ private AggregateBinaryOperator _op = null;\n+ private ReorgOperator _rop = null;\n+\n+ @Override\n+ public MatrixBlock call(Tuple2<MatrixBlock, MatrixBlock> arg0) throws Exception {\n+ //lazy operator construction\n+ if( _op == null ) {\n+ AggregateOperator agg = new AggregateOperator(0, Plus.getPlusFnObject());\n+ _op = new AggregateBinaryOperator(Multiply.getMultiplyFnObject(), agg);\n+ _rop = new ReorgOperator(SwapIndex.getSwapIndexFnObject());\n+ }\n+ //prepare inputs, including transpose of right-hand-side\n+ MatrixBlock in1 = arg0._1();\n+ MatrixBlock in2 = (MatrixBlock)arg0._2()\n+ .reorgOperations(_rop, new MatrixBlock(), 0, 0, 0);\n+ //core block matrix multiplication\n+ return in1.aggregateBinaryOperations(in1, in2, new MatrixBlock(), _op);\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/functions/FilterNonEmptyBlocksFunction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/functions/FilterNonEmptyBlocksFunction.java", "diff": "@@ -28,20 +28,14 @@ import org.apache.sysml.runtime.matrix.data.MatrixIndexes;\npublic class FilterNonEmptyBlocksFunction implements Function<Tuple2<MatrixIndexes,MatrixBlock>, Boolean>\n{\n-\nprivate static final long serialVersionUID = -8856829325565589854L;\n@Override\n- public Boolean call(Tuple2<MatrixIndexes, MatrixBlock> arg0)\n- throws Exception\n- {\n+ public Boolean call(Tuple2<MatrixIndexes, MatrixBlock> arg0) throws Exception {\n//always keep 1-1 block in order to prevent empty rdds\nboolean ix1 = (arg0._1().getRowIndex()==1\n&& arg0._1().getColumnIndex()==1);\n-\n//returns true for non-empty matrix blocks\nreturn !arg0._2().isEmptyBlock(false) || ix1;\n}\n-\n-\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/functions/FilterNonEmptyBlocksFunction2.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.sysml.runtime.instructions.spark.functions;\n+\n+import org.apache.spark.api.java.function.Function;\n+\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\n+\n+public class FilterNonEmptyBlocksFunction2 implements Function<MatrixBlock, Boolean>\n+{\n+ private static final long serialVersionUID = -8435900761521598692L;\n+\n+ @Override\n+ public Boolean call(MatrixBlock arg0) throws Exception {\n+ return !arg0.isEmptyBlock(false);\n+ }\n+}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2236] Improved spark cpmm (partitioning-preserving case) This patch adds a special case to the spark cpmm matrix multiply operator for the special case of matrix-vector multiply and existing matrix partitioning. In this case, we use a different approach that retains the original matrix keys and thus partitioning, which avoids unnecessary shuffle and stages.
49,738
08.04.2018 12:50:36
25,200
159522a1f08869c034ae6544be749e2695ab997a
[MINOR] Cleanup flaky l2svm application test (inconsistent tolerance)
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/applications/L2SVMTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/applications/L2SVMTest.java", "diff": "@@ -33,7 +33,6 @@ import org.apache.sysml.test.utils.TestUtils;\npublic abstract class L2SVMTest extends AutomatedTestBase\n{\n-\nprotected final static String TEST_DIR = \"applications/l2svm/\";\nprotected final static String TEST_NAME = \"L2SVM\";\nprotected String TEST_CLASS_DIR = TEST_DIR + L2SVMTest.class.getSimpleName() + \"/\";\n@@ -51,12 +50,11 @@ public abstract class L2SVMTest extends AutomatedTestBase\n@Parameters\npublic static Collection<Object[]> data() {\n- Object[][] data = new Object[][] {\n+ return Arrays.asList(new Object[][] {\n//sparse tests (sparsity=0.01)\n{100, 50, 0.01, false}, {1000, 500, 0.01, false}, {10000, 750, 0.01, false}, {10000, 750, 0.01, true}, {100000, 1000, 0.01, false},\n//dense tests (sparsity=0.7)\n- {100, 50, 0.7, false}, {1000, 500, 0.7, false}, {1000, 500, 0.7, true}, {10000, 750, 0.7, false} };\n- return Arrays.asList(data);\n+ {100, 50, 0.7, false}, {1000, 500, 0.7, false}, {1000, 500, 0.7, true}, {10000, 750, 0.7, false} });\n}\n@Override\n@@ -66,13 +64,13 @@ public abstract class L2SVMTest extends AutomatedTestBase\nprotected void testL2SVM(ScriptType scriptType)\n{\n- System.out.println(\"------------ BEGIN \" + TEST_NAME + \" \" + scriptType + \" TEST WITH {\" + numRecords + \", \" + numFeatures\n+ System.out.println(\"------------ BEGIN \" + TEST_NAME + \" \" + scriptType\n+ + \" TEST WITH {\" + numRecords + \", \" + numFeatures\n+ \", \" + sparsity + \", \" + intercept + \"} ------------\");\nthis.scriptType = scriptType;\n-\nint rows = numRecords;\nint cols = numFeatures;\n- double epsilon = 1.0e-8;\n+ double epsilon = 1e-10;\ndouble lambda = 1.0;\nint maxiterations = 3;\nint maxNumberOfMRJobs = 21;\n@@ -94,9 +92,7 @@ public abstract class L2SVMTest extends AutomatedTestBase\nproArgs.add(\"model=\" + output(\"w\"));\nproArgs.add(\"Log=\" + output(\"Log\"));\nprogramArgs = proArgs.toArray(new String[proArgs.size()]);\n-\nfullDMLScriptName = getScript();\n-\nrCmd = getRCmd(inputDir(), (intercept ? Integer.toString(1) : Integer.toString(0)), Double.toString(epsilon),\nDouble.toString(lambda), Integer.toString(maxiterations), expectedDir());\n@@ -107,13 +103,12 @@ public abstract class L2SVMTest extends AutomatedTestBase\nwriteInputMatrixWithMTD(\"X\", X, true);\nwriteInputMatrixWithMTD(\"Y\", Y, true);\n-\nrunTest(true, EXCEPTION_NOT_EXPECTED, null, maxNumberOfMRJobs);\nrunRScript(true);\nHashMap<CellIndex, Double> wR = readRMatrixFromFS(\"w\");\nHashMap<CellIndex, Double> wSYSTEMML= readDMLMatrixFromHDFS(\"w\");\n- TestUtils.compareMatrices(wR, wSYSTEMML, Math.pow(10, -12), \"wR\", \"wSYSTEMML\");\n+ TestUtils.compareMatrices(wR, wSYSTEMML, epsilon, \"wR\", \"wSYSTEMML\");\n}\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Cleanup flaky l2svm application test (inconsistent tolerance)
49,727
08.04.2018 15:10:47
25,200
8a51003ec9656f38f25e0e49d2180c49b2ffc6f7
Multi-threaded spark broadcast creation Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "diff": "@@ -52,6 +52,7 @@ import org.apache.sysml.parser.Expression.ValueType;\nimport org.apache.sysml.runtime.DMLRuntimeException;\nimport org.apache.sysml.runtime.compress.CompressedMatrixBlock;\nimport org.apache.sysml.runtime.controlprogram.Program;\n+import org.apache.sysml.runtime.controlprogram.caching.CacheBlock;\nimport org.apache.sysml.runtime.controlprogram.caching.CacheableData;\nimport org.apache.sysml.runtime.controlprogram.caching.FrameObject;\nimport org.apache.sysml.runtime.controlprogram.caching.MatrixObject;\n@@ -553,14 +554,7 @@ public class SparkExecutionContext extends ExecutionContext\n//create coarse-grained partitioned broadcasts\nif (numParts > 1) {\n- for( int i=0; i<numParts; i++ ) {\n- int offset = i * numPerPart;\n- int numBlks = Math.min(numPerPart, pmb.getNumRowBlocks()*pmb.getNumColumnBlocks()-offset);\n- PartitionedBlock<MatrixBlock> tmp = pmb.createPartition(offset, numBlks, new MatrixBlock());\n- ret[i] = getSparkContext().broadcast(tmp);\n- if( !isLocalMaster() )\n- tmp.clearBlocks();\n- }\n+ Arrays.parallelSetAll(ret, i -> createPartitionedBroadcast(pmb, numPerPart, i));\n}\nelse { //single partition\nret[0] = getSparkContext().broadcast(pmb);\n@@ -622,14 +616,7 @@ public class SparkExecutionContext extends ExecutionContext\n//create coarse-grained partitioned broadcasts\nif (numParts > 1) {\n- for( int i=0; i<numParts; i++ ) {\n- int offset = i * numPerPart;\n- int numBlks = Math.min(numPerPart, pmb.getNumRowBlocks()*pmb.getNumColumnBlocks()-offset);\n- PartitionedBlock<FrameBlock> tmp = pmb.createPartition(offset, numBlks, new FrameBlock());\n- ret[i] = getSparkContext().broadcast(tmp);\n- if( !isLocalMaster() )\n- tmp.clearBlocks();\n- }\n+ Arrays.parallelSetAll(ret, i -> createPartitionedBroadcast(pmb, numPerPart, i));\n}\nelse { //single partition\nret[0] = getSparkContext().broadcast(pmb);\n@@ -652,6 +639,17 @@ public class SparkExecutionContext extends ExecutionContext\nreturn bret;\n}\n+ private Broadcast<PartitionedBlock<? extends CacheBlock>> createPartitionedBroadcast(\n+ PartitionedBlock<? extends CacheBlock> pmb, int numPerPart, int pos) {\n+ int offset = pos * numPerPart;\n+ int numBlks = Math.min(numPerPart, pmb.getNumRowBlocks() * pmb.getNumColumnBlocks() - offset);\n+ PartitionedBlock<? extends CacheBlock> tmp = pmb.createPartition(offset, numBlks);\n+ Broadcast<PartitionedBlock<? extends CacheBlock>> ret = getSparkContext().broadcast(tmp);\n+ if (!isLocalMaster())\n+ tmp.clearBlocks();\n+ return ret;\n+ }\n+\n/**\n* Keep the output rdd of spark rdd operations as meta data of matrix/frame\n* objects in the symbol table.\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/data/PartitionedBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/data/PartitionedBlock.java", "diff": "@@ -29,6 +29,7 @@ import java.io.ObjectOutput;\nimport java.io.ObjectOutputStream;\nimport java.lang.reflect.Constructor;\nimport java.util.ArrayList;\n+import java.util.Arrays;\nimport org.apache.sysml.runtime.DMLRuntimeException;\nimport org.apache.sysml.runtime.controlprogram.caching.CacheBlock;\n@@ -76,18 +77,16 @@ public class PartitionedBlock<T extends CacheBlock> implements Externalizable\nint ncblks = getNumColumnBlocks();\nint code = CacheBlockFactory.getCode(block);\n- try\n- {\n+ try {\n_partBlocks = new CacheBlock[nrblks * ncblks];\n- for( int i=0, ix=0; i<nrblks; i++ )\n- for( int j=0; j<ncblks; j++, ix++ ) {\n+ Arrays.parallelSetAll(_partBlocks, index -> {\n+ int i = index % nrblks;\n+ int j = index % ncblks;\nT tmp = (T) CacheBlockFactory.newInstance(code);\n- block.slice(i*_brlen, Math.min((i+1)*_brlen, rlen)-1,\n+ return block.slice(i * _brlen, Math.min((i + 1) * _brlen, rlen) - 1,\nj * _bclen, Math.min((j + 1) * _bclen, clen) - 1, tmp);\n- _partBlocks[ix] = tmp;\n- }\n- }\n- catch(Exception ex) {\n+ });\n+ } catch(Exception ex) {\nthrow new RuntimeException(\"Failed partitioning of broadcast variable input.\", ex);\n}\n@@ -107,7 +106,7 @@ public class PartitionedBlock<T extends CacheBlock> implements Externalizable\n_partBlocks = new CacheBlock[nrblks * ncblks];\n}\n- public PartitionedBlock<T> createPartition( int offset, int numBlks, T block )\n+ public PartitionedBlock<T> createPartition( int offset, int numBlks)\n{\nPartitionedBlock<T> ret = new PartitionedBlock<>();\nret._rlen = _rlen;\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2197] Multi-threaded spark broadcast creation Closes #757.
49,738
09.04.2018 12:29:53
25,200
5ed2c30e645855df66f64d4262c2d04207e783b2
[HOTFIX] Fix multi-threaded broadcast creation indexing issue
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/data/PartitionedBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/data/PartitionedBlock.java", "diff": "@@ -80,7 +80,7 @@ public class PartitionedBlock<T extends CacheBlock> implements Externalizable\ntry {\n_partBlocks = new CacheBlock[nrblks * ncblks];\nArrays.parallelSetAll(_partBlocks, index -> {\n- int i = index % nrblks;\n+ int i = index / ncblks;\nint j = index % ncblks;\nT tmp = (T) CacheBlockFactory.newInstance(code);\nreturn block.slice(i * _brlen, Math.min((i + 1) * _brlen, rlen) - 1,\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix multi-threaded broadcast creation indexing issue
49,738
13.04.2018 14:10:23
25,200
80023787e9a4299468759c1a2a2e37fc6dd58054
Improved empty block filtering for spark operations This patch improves the analysis of safe empty block filtering for spark operations during hop compilation. We now handle mixed chains of matrix multiply and reorg operations.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/OptimizerUtils.java", "new_path": "src/main/java/org/apache/sysml/hops/OptimizerUtils.java", "diff": "@@ -33,6 +33,7 @@ import org.apache.sysml.conf.DMLConfig;\nimport org.apache.sysml.hops.Hop.DataOpTypes;\nimport org.apache.sysml.hops.Hop.FileFormatTypes;\nimport org.apache.sysml.hops.Hop.OpOp2;\n+import org.apache.sysml.hops.Hop.ReOrgOp;\nimport org.apache.sysml.hops.rewrite.HopRewriteUtils;\nimport org.apache.sysml.lops.Checkpoint;\nimport org.apache.sysml.lops.Lop;\n@@ -924,10 +925,10 @@ public class OptimizerUtils\np.optFindExecType(); //ensure exec type evaluated\nret &= ( p.getExecType()==ExecType.CP\n||(p instanceof AggBinaryOp && allowsToFilterEmptyBlockOutputs(p) )\n- ||(p instanceof DataOp && ((DataOp)p).getDataOpType()==DataOpTypes.PERSISTENTWRITE && ((DataOp)p).getInputFormatType()==FileFormatTypes.TEXT))\n+ ||(HopRewriteUtils.isReorg(p, ReOrgOp.RESHAPE, ReOrgOp.TRANS) && allowsToFilterEmptyBlockOutputs(p) )\n+ ||(HopRewriteUtils.isData(p, DataOpTypes.PERSISTENTWRITE) && ((DataOp)p).getInputFormatType()==FileFormatTypes.TEXT))\n&& !(p instanceof FunctionOp || (p instanceof DataOp && ((DataOp)p).getInputFormatType()!=FileFormatTypes.TEXT) ); //no function call or transient write\n}\n-\nreturn ret;\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2222] Improved empty block filtering for spark operations This patch improves the analysis of safe empty block filtering for spark operations during hop compilation. We now handle mixed chains of matrix multiply and reorg operations.
49,738
13.04.2018 17:08:37
25,200
6fa83d392cf0a5957dbd5035cdb1e9a96e823277
Fix robustness parfor worker cleanup w/o created pool
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/parfor/LocalParWorker.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/parfor/LocalParWorker.java", "diff": "@@ -138,7 +138,7 @@ public class LocalParWorker extends ParWorker implements Runnable\n}\nfinally {\n//cleanup fair scheduler pool for worker thread\n- if( OptimizerUtils.isSparkExecutionMode() ) {\n+ if( OptimizerUtils.isSparkExecutionMode() && pool != -1 ) {\nSparkExecutionContext sec = (SparkExecutionContext)_ec;\nsec.cleanupThreadLocalSchedulerPool(pool);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2238] Fix robustness parfor worker cleanup w/o created pool
49,738
14.04.2018 01:54:39
25,200
5d149a0af2a0921581b702a0da62d79279b6aab8
Fix handling of compressed blocks in few spark mm ops This patch fixes the missing handling of compressed right-hand-side blocks in spark cpmm, rmm, zipmm, and tsmm2 instructions. Similar to mapmm, tsmm, mapmmchain, we now use a common primitive that internally handles this case by calling binary operations on the compressed rhs.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CpmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CpmmSPInstruction.java", "diff": "@@ -43,6 +43,7 @@ import org.apache.sysml.runtime.instructions.spark.utils.SparkUtils;\nimport org.apache.sysml.runtime.matrix.MatrixCharacteristics;\nimport org.apache.sysml.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysml.runtime.matrix.data.MatrixIndexes;\n+import org.apache.sysml.runtime.matrix.data.OperationsOnMatrixValues;\nimport org.apache.sysml.runtime.matrix.mapred.IndexedMatrixValue;\nimport org.apache.sysml.runtime.matrix.operators.AggregateBinaryOperator;\nimport org.apache.sysml.runtime.matrix.operators.AggregateOperator;\n@@ -203,10 +204,10 @@ public class CpmmSPInstruction extends BinarySPInstruction {\nMatrixBlock blkIn1 = (MatrixBlock)arg0._2()._1().getValue();\nMatrixBlock blkIn2 = (MatrixBlock)arg0._2()._2().getValue();\nMatrixIndexes ixOut = new MatrixIndexes();\n- MatrixBlock blkOut = new MatrixBlock();\n//core block matrix multiplication\n- blkIn1.aggregateBinaryOperations(blkIn1, blkIn2, blkOut, _op);\n+ MatrixBlock blkOut = OperationsOnMatrixValues\n+ .performAggregateBinaryIgnoreIndexes(blkIn1, blkIn2, new MatrixBlock(), _op);\n//return target block\nixOut.setIndexes(arg0._2()._1().getIndexes().getRowIndex(),\n@@ -234,7 +235,8 @@ public class CpmmSPInstruction extends BinarySPInstruction {\nMatrixBlock in2 = (MatrixBlock)arg0._2()\n.reorgOperations(_rop, new MatrixBlock(), 0, 0, 0);\n//core block matrix multiplication\n- return in1.aggregateBinaryOperations(in1, in2, new MatrixBlock(), _op);\n+ return OperationsOnMatrixValues\n+ .performAggregateBinaryIgnoreIndexes(in1, in2, new MatrixBlock(), _op);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MapmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MapmmSPInstruction.java", "diff": "@@ -327,7 +327,7 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock left = _pbc.getBlock(1, (int)ixIn.getRowIndex());\n//execute matrix-vector mult\n- return (MatrixBlock) OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(\n+ return OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(\nleft, blkIn, new MatrixBlock(), _op);\n}\nelse //if( _type == CacheType.RIGHT )\n@@ -336,7 +336,7 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock right = _pbc.getBlock((int)ixIn.getColumnIndex(), 1);\n//execute matrix-vector mult\n- return (MatrixBlock) OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(\n+ return OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(\nblkIn, right, new MatrixBlock(), _op);\n}\n}\n@@ -392,7 +392,7 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock left = _pbc.getBlock(1, (int)ixIn.getRowIndex());\n//execute index preserving matrix multiplication\n- left.aggregateBinaryOperations(left, blkIn, blkOut, _op);\n+ OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(left, blkIn, blkOut, _op);\n}\nelse //if( _type == CacheType.RIGHT )\n{\n@@ -400,7 +400,7 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock right = _pbc.getBlock((int)ixIn.getColumnIndex(), 1);\n//execute index preserving matrix multiplication\n- blkIn.aggregateBinaryOperations(blkIn, right, blkOut, _op);\n+ OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(blkIn, right, blkOut, _op);\n}\nreturn new Tuple2<>(ixIn, blkOut);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/RmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/RmmSPInstruction.java", "diff": "@@ -43,6 +43,7 @@ import org.apache.sysml.runtime.instructions.spark.utils.SparkUtils;\nimport org.apache.sysml.runtime.matrix.MatrixCharacteristics;\nimport org.apache.sysml.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysml.runtime.matrix.data.MatrixIndexes;\n+import org.apache.sysml.runtime.matrix.data.OperationsOnMatrixValues;\nimport org.apache.sysml.runtime.matrix.data.TripleIndexes;\nimport org.apache.sysml.runtime.matrix.operators.AggregateBinaryOperator;\nimport org.apache.sysml.runtime.matrix.operators.AggregateOperator;\n@@ -188,10 +189,10 @@ public class RmmSPInstruction extends BinarySPInstruction {\nMatrixIndexes ixOut = new MatrixIndexes(ixIn.getFirstIndex(), ixIn.getSecondIndex()); //i,j\nMatrixBlock blkIn1 = arg0._2()._1();\nMatrixBlock blkIn2 = arg0._2()._2();\n- MatrixBlock blkOut = new MatrixBlock();\n//core block matrix multiplication\n- blkIn1.aggregateBinaryOperations(blkIn1, blkIn2, blkOut, _op);\n+ MatrixBlock blkOut = OperationsOnMatrixValues\n+ .performAggregateBinaryIgnoreIndexes(blkIn1, blkIn2, new MatrixBlock(), _op);\n//output new tuple\nreturn new Tuple2<>(ixOut, blkOut);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/Tsmm2SPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/Tsmm2SPInstruction.java", "diff": "@@ -215,7 +215,7 @@ public class Tsmm2SPInstruction extends UnarySPInstruction {\n(int)(_type.isLeft()?1:ixin.getColumnIndex()));\nMatrixBlock mbin2t = transpose(mbin2, new MatrixBlock()); //prep for transpose rewrite mm\n- MatrixBlock out2 = (MatrixBlock) OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes( //mm\n+ MatrixBlock out2 = OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes( //mm\n_type.isLeft() ? mbin2t : mbin, _type.isLeft() ? mbin : mbin2t, new MatrixBlock(), _op);\nMatrixIndexes ixout2 = _type.isLeft() ? new MatrixIndexes(2,1) : new MatrixIndexes(1,2);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/ZipmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/ZipmmSPInstruction.java", "diff": "@@ -36,6 +36,7 @@ import org.apache.sysml.runtime.instructions.cp.CPOperand;\nimport org.apache.sysml.runtime.instructions.spark.utils.RDDAggregateUtils;\nimport org.apache.sysml.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysml.runtime.matrix.data.MatrixIndexes;\n+import org.apache.sysml.runtime.matrix.data.OperationsOnMatrixValues;\nimport org.apache.sysml.runtime.matrix.operators.AggregateBinaryOperator;\nimport org.apache.sysml.runtime.matrix.operators.AggregateOperator;\nimport org.apache.sysml.runtime.matrix.operators.Operator;\n@@ -124,7 +125,8 @@ public class ZipmmSPInstruction extends BinarySPInstruction {\nMatrixBlock tmp = (MatrixBlock)in2.reorgOperations(_rop, new MatrixBlock(), 0, 0, 0);\n//core matrix multiplication (for t(y)%*%X or t(X)%*%y)\n- return tmp.aggregateBinaryOperations(tmp, in1, new MatrixBlock(), _abop);\n+ return OperationsOnMatrixValues\n+ .performAggregateBinaryIgnoreIndexes(tmp, in1, new MatrixBlock(), _abop);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "diff": "@@ -228,14 +228,13 @@ public class OperationsOnMatrixValues\nvalue1.aggregateBinaryOperations(indexes1, value1, indexes2, value2, valueOut, op);\n}\n- public static MatrixValue performAggregateBinaryIgnoreIndexes(MatrixBlock value1, MatrixBlock value2,\n+ public static MatrixBlock performAggregateBinaryIgnoreIndexes(MatrixBlock value1, MatrixBlock value2,\nMatrixBlock valueOut, AggregateBinaryOperator op) {\n//perform on the value\nif( value2 instanceof CompressedMatrixBlock )\n- value2.aggregateBinaryOperations(value1, value2, valueOut, op);\n+ return value2.aggregateBinaryOperations(value1, value2, valueOut, op);\nelse\n- value1.aggregateBinaryOperations(value1, value2, valueOut, op);\n- return valueOut;\n+ return value1.aggregateBinaryOperations(value1, value2, valueOut, op);\n}\n@SuppressWarnings(\"rawtypes\")\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2244] Fix handling of compressed blocks in few spark mm ops This patch fixes the missing handling of compressed right-hand-side blocks in spark cpmm, rmm, zipmm, and tsmm2 instructions. Similar to mapmm, tsmm, mapmmchain, we now use a common primitive that internally handles this case by calling binary operations on the compressed rhs.
49,701
14.04.2018 16:23:10
25,200
bb53c6b4634f05cfa7f0c68ece45fd2f089d4634
[MINOR] Fix parent-child link bug in Hop rewrite The rewrite `fuseDatagenAndBinaryOperation3a` in `RewriteAlgebraicSimplificationStatic` fails to change the parents when rewiring DataGen Hops. This patch adds the correct parents. The problem arises in `LinearLogRegDMLTest` if the `ProgramRewriter`'s `CHECK` flag is set to true (thereby invoking the HopDagValidator). Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/DataGenOp.java", "new_path": "src/main/java/org/apache/sysml/hops/DataGenOp.java", "diff": "@@ -374,8 +374,10 @@ public class DataGenOp extends Hop implements MultiThreadedHop\nreturn getInput().get(getParamIndex(key));\n}\n- public void setInput(String key, Hop hop) {\n+ public void setInput(String key, Hop hop, boolean linkParent) {\ngetInput().set(getParamIndex(key), hop);\n+ if( linkParent )\n+ hop.getParent().add(this);\n}\npublic boolean hasConstantValue()\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/rewrite/RewriteAlgebraicSimplificationStatic.java", "new_path": "src/main/java/org/apache/sysml/hops/rewrite/RewriteAlgebraicSimplificationStatic.java", "diff": "@@ -438,8 +438,8 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\n&& HopRewriteUtils.isLiteralOfValue(min, 0)\n&& HopRewriteUtils.isLiteralOfValue(max, 0) )\n{\n- gen.setInput(DataExpression.RAND_MIN, right);\n- gen.setInput(DataExpression.RAND_MAX, right);\n+ gen.setInput(DataExpression.RAND_MIN, right, true);\n+ gen.setInput(DataExpression.RAND_MAX, right, true);\n//rewire all parents (avoid anomalies with replicated datagen)\nList<Hop> parents = new ArrayList<>(bop.getParent());\nfor( Hop p : parents )\n@@ -454,8 +454,8 @@ public class RewriteAlgebraicSimplificationStatic extends HopRewriteRule\n&& HopRewriteUtils.isLiteralOfValue(max, 1) )\n{\nif( HopRewriteUtils.isLiteralOfValue(min, 1) )\n- gen.setInput(DataExpression.RAND_MIN, right);\n- gen.setInput(DataExpression.RAND_MAX, right);\n+ gen.setInput(DataExpression.RAND_MIN, right, true);\n+ gen.setInput(DataExpression.RAND_MAX, right, true);\n//rewire all parents (avoid anomalies with replicated datagen)\nList<Hop> parents = new ArrayList<>(bop.getParent());\nfor( Hop p : parents )\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix parent-child link bug in Hop rewrite The rewrite `fuseDatagenAndBinaryOperation3a` in `RewriteAlgebraicSimplificationStatic` fails to change the parents when rewiring DataGen Hops. This patch adds the correct parents. The problem arises in `LinearLogRegDMLTest` if the `ProgramRewriter`'s `CHECK` flag is set to true (thereby invoking the HopDagValidator). Closes #758.
49,738
14.04.2018 15:25:00
25,200
79db07968d3f5425e6ff27c024e0260f13077b52
Fine tuning ultra-sparse matrix mult selection This patch further tunes the selection of ultra-sparse matrix mult block operations by (1) using ultra-sparse operations (with sparse output) for outer-product like operations that are known to result in sparse outputs, and (2) avoid unnecessary sparse-dense conversion for operations with colunm vector outputs.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MapmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MapmmSPInstruction.java", "diff": "@@ -431,43 +431,27 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nthrows Exception\n{\nArrayList<Tuple2<MatrixIndexes, MatrixBlock>> ret = new ArrayList<>();\n-\nMatrixIndexes ixIn = arg0._1();\nMatrixBlock blkIn = arg0._2();\n- if( _type == CacheType.LEFT )\n- {\n+ if( _type == CacheType.LEFT ) {\n//for all matching left-hand-side blocks\nint len = _pbc.getNumRowBlocks();\n- for( int i=1; i<=len; i++ )\n- {\n+ for( int i=1; i<=len; i++ ) {\nMatrixBlock left = _pbc.getBlock(i, (int)ixIn.getRowIndex());\n- MatrixIndexes ixOut = new MatrixIndexes();\n- MatrixBlock blkOut = new MatrixBlock();\n-\n- //execute matrix-vector mult\n- OperationsOnMatrixValues.performAggregateBinary(\n- new MatrixIndexes(i,ixIn.getRowIndex()), left, ixIn, blkIn, ixOut, blkOut, _op);\n-\n- ret.add(new Tuple2<>(ixOut, blkOut));\n+ MatrixBlock blkOut = OperationsOnMatrixValues\n+ .performAggregateBinaryIgnoreIndexes(left, blkIn, new MatrixBlock(), _op);\n+ ret.add(new Tuple2<>(new MatrixIndexes(i, ixIn.getColumnIndex()), blkOut));\n}\n}\n- else //if( _type == CacheType.RIGHT )\n- {\n+ else { //RIGHT\n//for all matching right-hand-side blocks\nint len = _pbc.getNumColumnBlocks();\n- for( int j=1; j<=len; j++ )\n- {\n- //get the right hand side matrix\n+ for( int j=1; j<=len; j++ ) {\nMatrixBlock right = _pbc.getBlock((int)ixIn.getColumnIndex(), j);\n- MatrixIndexes ixOut = new MatrixIndexes();\n- MatrixBlock blkOut = new MatrixBlock();\n-\n- //execute matrix-vector mult\n- OperationsOnMatrixValues.performAggregateBinary(\n- ixIn, blkIn, new MatrixIndexes(ixIn.getColumnIndex(),j), right, ixOut, blkOut, _op);\n-\n- ret.add(new Tuple2<>(ixOut, blkOut));\n+ MatrixBlock blkOut = OperationsOnMatrixValues\n+ .performAggregateBinaryIgnoreIndexes(blkIn, right, new MatrixBlock(), _op);\n+ ret.add(new Tuple2<>(new MatrixIndexes(ixIn.getRowIndex(), j), blkOut));\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixMult.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixMult.java", "diff": "@@ -1490,7 +1490,8 @@ public class LibMatrixMult\n*/\nprivate static void matrixMultUltraSparse(MatrixBlock m1, MatrixBlock m2, MatrixBlock ret, int rl, int ru) {\nfinal boolean leftUS = m1.isUltraSparse()\n- || (m1.isUltraSparse(false) && !m2.isUltraSparse());\n+ || (m1.isUltraSparse(false) && !m2.isUltraSparse())\n+ || (m1.sparse && !m2.sparse);\nfinal int m = m1.rlen;\nfinal int cd = m1.clen;\nfinal int n = m2.clen;\n@@ -3693,14 +3694,21 @@ public class LibMatrixMult\n}\npublic static boolean isUltraSparseMatrixMult(MatrixBlock m1, MatrixBlock m2) {\n+ if( m2.clen == 1 ) //mv always dense\n+ return false;\n//note: ultra-sparse matrix mult implies also sparse outputs, hence we need\n//to be conservative an cannot use this for all ultra-sparse matrices.\n+ double outSp = OptimizerUtils.getMatMultSparsity(\n+ m1.getSparsity(), m2.getSparsity(), m1.rlen, m1.clen, m2.clen, true);\nreturn (m1.isUltraSparse() || m2.isUltraSparse()) //base case\n|| (m1.isUltraSparsePermutationMatrix()\n&& OptimizerUtils.getSparsity(m2.rlen, m2.clen, m2.nonZeros)<1.0)\n|| ((m1.isUltraSparse(false) || m2.isUltraSparse(false))\n- && OptimizerUtils.getMatMultSparsity(m1.getSparsity(), m2.getSparsity(),\n- m1.rlen, m1.clen, m2.clen, true) < MatrixBlock.ULTRA_SPARSITY_TURN_POINT2);\n+ && outSp < MatrixBlock.ULTRA_SPARSITY_TURN_POINT2)\n+ || (m1.getSparsity() < MatrixBlock.ULTRA_SPARSITY_TURN_POINT2\n+ && m1.getNonZeros() < MatrixBlock.ULTRA_SPARSE_BLOCK_NNZ\n+ && m1.getLength()+m2.getLength() < (long)m1.rlen*m2.clen\n+ && outSp < MatrixBlock.SPARSITY_TURN_POINT);\n}\nprivate static MatrixBlock prepMatrixMultRightInput( MatrixBlock m1, MatrixBlock m2 ) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "diff": "@@ -101,6 +101,7 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab\n//sparsity threshold for ultra-sparse matrix operations (40nnz in a 1kx1k block)\npublic static final double ULTRA_SPARSITY_TURN_POINT = 0.00004;\npublic static final double ULTRA_SPARSITY_TURN_POINT2 = 0.0004;\n+ public static final int ULTRA_SPARSE_BLOCK_NNZ = 40;\n//default sparse block type: modified compressed sparse rows, for efficient incremental construction\npublic static final SparseBlock.Type DEFAULT_SPARSEBLOCK = SparseBlock.Type.MCSR;\n//default sparse block type for update in place: compressed sparse rows, to prevent serialization\n@@ -874,7 +875,8 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab\npublic boolean isUltraSparse(boolean checkNnz) {\ndouble sp = ((double)nonZeros/rlen)/clen;\n//check for sparse representation in order to account for vectors in dense\n- return sparse && sp<ULTRA_SPARSITY_TURN_POINT && (!checkNnz || nonZeros<40);\n+ return sparse && sp<ULTRA_SPARSITY_TURN_POINT\n+ && (!checkNnz || nonZeros<ULTRA_SPARSE_BLOCK_NNZ);\n}\npublic boolean isUltraSparsePermutationMatrix() {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "diff": "@@ -217,15 +217,15 @@ public class OperationsOnMatrixValues\nvalueIn.aggregateUnaryOperations(op, valueOut, brlen, bclen, indexesIn);\n}\n- public static void performAggregateBinary(MatrixIndexes indexes1, MatrixBlock value1, MatrixIndexes indexes2, MatrixBlock value2,\n+ public static MatrixBlock performAggregateBinary(MatrixIndexes indexes1, MatrixBlock value1, MatrixIndexes indexes2, MatrixBlock value2,\nMatrixIndexes indexesOut, MatrixBlock valueOut, AggregateBinaryOperator op) {\n//compute output index\nindexesOut.setIndexes(indexes1.getRowIndex(), indexes2.getColumnIndex());\n//perform on the value\nif( value2 instanceof CompressedMatrixBlock )\n- value2.aggregateBinaryOperations(value1, value2, valueOut, op);\n+ return value2.aggregateBinaryOperations(value1, value2, valueOut, op);\nelse //default\n- value1.aggregateBinaryOperations(indexes1, value1, indexes2, value2, valueOut, op);\n+ return value1.aggregateBinaryOperations(indexes1, value1, indexes2, value2, valueOut, op);\n}\npublic static MatrixBlock performAggregateBinaryIgnoreIndexes(MatrixBlock value1, MatrixBlock value2,\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2241] Fine tuning ultra-sparse matrix mult selection This patch further tunes the selection of ultra-sparse matrix mult block operations by (1) using ultra-sparse operations (with sparse output) for outer-product like operations that are known to result in sparse outputs, and (2) avoid unnecessary sparse-dense conversion for operations with colunm vector outputs.
49,738
14.04.2018 20:38:18
25,200
2e6e02f0bc116786665a10dbe2deb0bb395876b4
[MINOR] Fix robustness CSE leaf node merge (converted pread-tread) This patch makes a minor extension of the common subexpression (CSE) rewrite. In JMLC scenarios, persistent reads are converted to transient reads which need to be properly treated as leaf nodes despite potential parameters.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/rewrite/RewriteCommonSubexpressionElimination.java", "new_path": "src/main/java/org/apache/sysml/hops/rewrite/RewriteCommonSubexpressionElimination.java", "diff": "@@ -25,6 +25,7 @@ import java.util.HashMap;\nimport org.apache.sysml.hops.DataOp;\nimport org.apache.sysml.hops.Hop;\nimport org.apache.sysml.hops.LiteralOp;\n+import org.apache.sysml.hops.Hop.DataOpTypes;\n/**\n* Rule: CommonSubexpressionElimination. For all statement blocks,\n@@ -99,7 +100,8 @@ public class RewriteCommonSubexpressionElimination extends HopRewriteRule\nif( hop.isVisited() )\nreturn ret;\n- if( hop.getInput().isEmpty() ) //LEAF NODE\n+ if( hop.getInput().isEmpty() //LEAF NODE\n+ || HopRewriteUtils.isData(hop, DataOpTypes.TRANSIENTREAD) )\n{\nif( hop instanceof LiteralOp )\n{\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Fix robustness CSE leaf node merge (converted pread-tread) This patch makes a minor extension of the common subexpression (CSE) rewrite. In JMLC scenarios, persistent reads are converted to transient reads which need to be properly treated as leaf nodes despite potential parameters.
49,738
16.04.2018 19:31:47
25,200
25feb997978e990eb5dc11eaaa2dc6ef7af03c61
[MINOR] Simplify spark key-value list handling via streams
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/utils/SparkUtils.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/utils/SparkUtils.java", "diff": "@@ -70,40 +70,28 @@ public class SparkUtils\nreturn new Tuple2<>(in.getIndexes(), (MatrixBlock)in.getValue());\n}\n- public static ArrayList<Tuple2<MatrixIndexes,MatrixBlock>> fromIndexedMatrixBlock( ArrayList<IndexedMatrixValue> in ) {\n- ArrayList<Tuple2<MatrixIndexes,MatrixBlock>> ret = new ArrayList<>();\n- for( IndexedMatrixValue imv : in )\n- ret.add(fromIndexedMatrixBlock(imv));\n- return ret;\n+ public static List<Tuple2<MatrixIndexes,MatrixBlock>> fromIndexedMatrixBlock( List<IndexedMatrixValue> in ) {\n+ return in.stream().map(imv -> fromIndexedMatrixBlock(imv)).collect(Collectors.toList());\n}\npublic static Pair<MatrixIndexes,MatrixBlock> fromIndexedMatrixBlockToPair( IndexedMatrixValue in ){\nreturn new Pair<>(in.getIndexes(), (MatrixBlock)in.getValue());\n}\n- public static ArrayList<Pair<MatrixIndexes,MatrixBlock>> fromIndexedMatrixBlockToPair( ArrayList<IndexedMatrixValue> in ) {\n- ArrayList<Pair<MatrixIndexes,MatrixBlock>> ret = new ArrayList<>();\n- for( IndexedMatrixValue imv : in )\n- ret.add(fromIndexedMatrixBlockToPair(imv));\n- return ret;\n+ public static List<Pair<MatrixIndexes,MatrixBlock>> fromIndexedMatrixBlockToPair( List<IndexedMatrixValue> in ) {\n+ return in.stream().map(imv -> fromIndexedMatrixBlockToPair(imv)).collect(Collectors.toList());\n}\npublic static Tuple2<Long,FrameBlock> fromIndexedFrameBlock( Pair<Long, FrameBlock> in ){\nreturn new Tuple2<>(in.getKey(), in.getValue());\n}\n- public static ArrayList<Tuple2<Long,FrameBlock>> fromIndexedFrameBlock( ArrayList<Pair<Long, FrameBlock>> in ) {\n- ArrayList<Tuple2<Long, FrameBlock>> ret = new ArrayList<>();\n- for( Pair<Long, FrameBlock> ifv : in )\n- ret.add(fromIndexedFrameBlock(ifv));\n- return ret;\n+ public static List<Tuple2<Long,FrameBlock>> fromIndexedFrameBlock(List<Pair<Long, FrameBlock>> in) {\n+ return in.stream().map(ifv -> fromIndexedFrameBlock(ifv)).collect(Collectors.toList());\n}\n- public static ArrayList<Pair<Long,Long>> toIndexedLong( List<Tuple2<Long, Long>> in ) {\n- ArrayList<Pair<Long, Long>> ret = new ArrayList<>();\n- for( Tuple2<Long, Long> e : in )\n- ret.add(new Pair<>(e._1(), e._2()));\n- return ret;\n+ public static List<Pair<Long,Long>> toIndexedLong( List<Tuple2<Long, Long>> in ) {\n+ return in.stream().map(e -> new Pair<>(e._1(), e._2())).collect(Collectors.toList());\n}\npublic static Pair<Long,FrameBlock> toIndexedFrameBlock( Tuple2<Long,FrameBlock> in ) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "diff": "@@ -22,6 +22,7 @@ package org.apache.sysml.runtime.matrix.data;\nimport java.util.ArrayList;\nimport java.util.Arrays;\n+import java.util.List;\nimport org.apache.sysml.parser.Expression.ValueType;\nimport org.apache.sysml.runtime.DMLRuntimeException;\n@@ -238,7 +239,7 @@ public class OperationsOnMatrixValues\n}\n@SuppressWarnings(\"rawtypes\")\n- public static ArrayList performSlice(IndexRange ixrange, int brlen, int bclen, int iix, int jix, CacheBlock in) {\n+ public static List performSlice(IndexRange ixrange, int brlen, int bclen, int iix, int jix, CacheBlock in) {\nif( in instanceof MatrixBlock )\nreturn performSlice(ixrange, brlen, bclen, iix, jix, (MatrixBlock)in);\nelse if( in instanceof FrameBlock )\n@@ -246,13 +247,11 @@ public class OperationsOnMatrixValues\nthrow new DMLRuntimeException(\"Unsupported cache block type: \"+in.getClass().getName());\n}\n-\n@SuppressWarnings(\"rawtypes\")\n- public static ArrayList performSlice(IndexRange ixrange, int brlen, int bclen, int iix, int jix, MatrixBlock in) {\n+ public static List performSlice(IndexRange ixrange, int brlen, int bclen, int iix, int jix, MatrixBlock in) {\nIndexedMatrixValue imv = new IndexedMatrixValue(new MatrixIndexes(iix, jix), (MatrixBlock)in);\nArrayList<IndexedMatrixValue> outlist = new ArrayList<>();\nperformSlice(imv, ixrange, brlen, bclen, outlist);\n-\nreturn SparkUtils.fromIndexedMatrixBlockToPair(outlist);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Simplify spark key-value list handling via streams
49,738
16.04.2018 19:57:09
25,200
6aaea2fddfcf0937c7f02bcc181c7684718b98bf
Performance dense-sparse vector transpose (in MCSR) This patch makes a moderate performance improvement for dense-sparse vector transpose which avoids unnecessary binary search operations per vector. This is useful for scenarios with ultra-sparse vectors and spark operations where large vectors are partitioned into many 1K vectors.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseRowVector.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/SparseRowVector.java", "diff": "@@ -209,8 +209,9 @@ public final class SparseRowVector extends SparseRow implements Serializable\nreturn (index >= 0) ? values[index] : 0;\n}\n- public int searchIndexesFirstLTE(int col)\n- {\n+ public int searchIndexesFirstLTE(int col) {\n+ if( size == 0 ) return -1;\n+\n//search for existing col index\nint index = Arrays.binarySearch(indexes, 0, size, col);\nif( index >= 0 )\n@@ -221,8 +222,9 @@ public final class SparseRowVector extends SparseRow implements Serializable\nreturn (index-1 < size) ? index-1 : -1;\n}\n- public int searchIndexesFirstGTE(int col)\n- {\n+ public int searchIndexesFirstGTE(int col) {\n+ if( size == 0 ) return -1;\n+\n//search for existing col index\nint index = Arrays.binarySearch(indexes, 0, size, col);\nif( index >= 0 )\n@@ -233,8 +235,9 @@ public final class SparseRowVector extends SparseRow implements Serializable\nreturn (index < size) ? index : -1;\n}\n- public int searchIndexesFirstGT(int col)\n- {\n+ public int searchIndexesFirstGT(int col) {\n+ if( size == 0 ) return -1;\n+\n//search for existing col index\nint index = Arrays.binarySearch(indexes, 0, size, col);\nif( index >= 0 )\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2246] Performance dense-sparse vector transpose (in MCSR) This patch makes a moderate performance improvement for dense-sparse vector transpose which avoids unnecessary binary search operations per vector. This is useful for scenarios with ultra-sparse vectors and spark operations where large vectors are partitioned into many 1K vectors.
49,738
16.04.2018 23:41:31
25,200
f5d97c55162bc9c7db57e685c04be9aafe9657f6
Performance spark mapmm (lazy-iter) / reshape (sparse) This patch makes a minor performance improvement to spark mapmm operations that require flatmap, by returning a lazy iterator which has the potential to improve memory efficiency and thus reduce unnecessary GC overhead. Furthermore, this also includes some cleanups including spark reshape operations.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/mr/AggregateBinaryInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/mr/AggregateBinaryInstruction.java", "diff": "@@ -154,7 +154,7 @@ public class AggregateBinaryInstruction extends BinaryMRInstructionBase implemen\nout=cachedValues.holdPlace(output, valueClass);\n//process instruction\n- OperationsOnMatrixValues.performAggregateBinary(\n+ OperationsOnMatrixValues.matMult(\nin1.getIndexes(), (MatrixBlock) in1.getValue(),\nin2.getIndexes(), (MatrixBlock) in2.getValue(),\nout.getIndexes(), (MatrixBlock) out.getValue(),\n@@ -200,7 +200,7 @@ public class AggregateBinaryInstruction extends BinaryMRInstructionBase implemen\nIndexedMatrixValue out = cachedValues.holdPlace(output, valueClass);\n//process instruction\n- OperationsOnMatrixValues.performAggregateBinary(in1.getIndexes(), (MatrixBlock)in1.getValue(),\n+ OperationsOnMatrixValues.matMult(in1.getIndexes(), (MatrixBlock)in1.getValue(),\nin2BlockIndex, (MatrixBlock) in2BlockValue, out.getIndexes(), (MatrixBlock)out.getValue(),\n((AggregateBinaryOperator)optr));\nremoveOutput &= ( !_outputEmptyBlocks && out.getValue().isEmpty() );\n@@ -227,7 +227,7 @@ public class AggregateBinaryInstruction extends BinaryMRInstructionBase implemen\nIndexedMatrixValue out = cachedValues.holdPlace(output, valueClass);\n//process instruction\n- OperationsOnMatrixValues.performAggregateBinary(\n+ OperationsOnMatrixValues.matMult(\nin1BlockIndex, (MatrixBlock)in1BlockValue,\nin2.getIndexes(), (MatrixBlock)in2.getValue(),\nout.getIndexes(), (MatrixBlock)out.getValue(),\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/mr/MatrixReshapeMRInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/mr/MatrixReshapeMRInstruction.java", "diff": "package org.apache.sysml.runtime.instructions.mr;\nimport java.util.ArrayList;\n+import java.util.List;\nimport org.apache.sysml.runtime.DMLRuntimeException;\nimport org.apache.sysml.runtime.instructions.InstructionUtils;\n@@ -36,8 +37,6 @@ public class MatrixReshapeMRInstruction extends UnaryInstruction {\nprivate MatrixCharacteristics _mcIn = null;\nprivate MatrixCharacteristics _mcOut = null;\n- private ArrayList<IndexedMatrixValue> _cache = null;\n-\nprivate MatrixReshapeMRInstruction(Operator op, byte in, long rows, long cols, boolean byrow, byte out,\nString istr) {\nsuper(MRType.MMTSJ, op, in, out, istr);\n@@ -46,8 +45,7 @@ public class MatrixReshapeMRInstruction extends UnaryInstruction {\n_byrow = byrow;\n}\n- public void setMatrixCharacteristics( MatrixCharacteristics mcIn, MatrixCharacteristics mcOut )\n- {\n+ public void setMatrixCharacteristics( MatrixCharacteristics mcIn, MatrixCharacteristics mcOut ) {\n_mcIn = mcIn;\n}\n@@ -73,25 +71,17 @@ public class MatrixReshapeMRInstruction extends UnaryInstruction {\n{\nArrayList<IndexedMatrixValue> blkList = cachedValues.get(input);\nif( blkList != null )\n- for(IndexedMatrixValue imv : blkList)\n- {\n- if( imv == null )\n- continue;\n-\n- //get cached blocks\n- ArrayList<IndexedMatrixValue> out = _cache;\n+ for(IndexedMatrixValue imv : blkList) {\n+ if( imv == null ) continue;\n//process instruction\n_mcOut.setBlockSize(brlen, bclen);\n- out = LibMatrixReorg.reshape(imv, _mcIn, out, _mcOut, _byrow, true);\n+ List<IndexedMatrixValue> out =\n+ LibMatrixReorg.reshape(imv, _mcIn, _mcOut, _byrow, true);\n//put the output values in the output cache\nfor( IndexedMatrixValue outBlk : out )\ncachedValues.add(output, outBlk);\n-\n- //put blocks into own cache\n- if( LibMatrixReorg.ALLOW_BLOCK_REUSE )\n- _cache = out;\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CpmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/CpmmSPInstruction.java", "diff": "@@ -207,7 +207,7 @@ public class CpmmSPInstruction extends BinarySPInstruction {\n//core block matrix multiplication\nMatrixBlock blkOut = OperationsOnMatrixValues\n- .performAggregateBinaryIgnoreIndexes(blkIn1, blkIn2, new MatrixBlock(), _op);\n+ .matMult(blkIn1, blkIn2, new MatrixBlock(), _op);\n//return target block\nixOut.setIndexes(arg0._2()._1().getIndexes().getRowIndex(),\n@@ -236,7 +236,7 @@ public class CpmmSPInstruction extends BinarySPInstruction {\n.reorgOperations(_rop, new MatrixBlock(), 0, 0, 0);\n//core block matrix multiplication\nreturn OperationsOnMatrixValues\n- .performAggregateBinaryIgnoreIndexes(in1, in2, new MatrixBlock(), _op);\n+ .matMult(in1, in2, new MatrixBlock(), _op);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MapmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MapmmSPInstruction.java", "diff": "package org.apache.sysml.runtime.instructions.spark;\n-import java.util.ArrayList;\nimport java.util.Iterator;\n+import java.util.stream.IntStream;\nimport org.apache.spark.api.java.JavaPairRDD;\nimport org.apache.spark.api.java.JavaRDD;\n@@ -275,8 +275,8 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock left = _pbc.getBlock(1, (int)ixIn.getRowIndex());\n//execute matrix-vector mult\n- OperationsOnMatrixValues.performAggregateBinary(\n- new MatrixIndexes(1,ixIn.getRowIndex()), left, ixIn, blkIn, ixOut, blkOut, _op);\n+ OperationsOnMatrixValues.matMult(new MatrixIndexes(1,ixIn.getRowIndex()),\n+ left, ixIn, blkIn, ixOut, blkOut, _op);\n}\nelse //if( _type == CacheType.RIGHT )\n{\n@@ -284,8 +284,8 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock right = _pbc.getBlock((int)ixIn.getColumnIndex(), 1);\n//execute matrix-vector mult\n- OperationsOnMatrixValues.performAggregateBinary(\n- ixIn, blkIn, new MatrixIndexes(ixIn.getColumnIndex(),1), right, ixOut, blkOut, _op);\n+ OperationsOnMatrixValues.matMult(ixIn, blkIn,\n+ new MatrixIndexes(ixIn.getColumnIndex(),1), right, ixOut, blkOut, _op);\n}\n//output new tuple\n@@ -327,7 +327,7 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock left = _pbc.getBlock(1, (int)ixIn.getRowIndex());\n//execute matrix-vector mult\n- return OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(\n+ return OperationsOnMatrixValues.matMult(\nleft, blkIn, new MatrixBlock(), _op);\n}\nelse //if( _type == CacheType.RIGHT )\n@@ -336,7 +336,7 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock right = _pbc.getBlock((int)ixIn.getColumnIndex(), 1);\n//execute matrix-vector mult\n- return OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(\n+ return OperationsOnMatrixValues.matMult(\nblkIn, right, new MatrixBlock(), _op);\n}\n}\n@@ -392,7 +392,7 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock left = _pbc.getBlock(1, (int)ixIn.getRowIndex());\n//execute index preserving matrix multiplication\n- OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(left, blkIn, blkOut, _op);\n+ OperationsOnMatrixValues.matMult(left, blkIn, blkOut, _op);\n}\nelse //if( _type == CacheType.RIGHT )\n{\n@@ -400,7 +400,7 @@ public class MapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock right = _pbc.getBlock((int)ixIn.getColumnIndex(), 1);\n//execute index preserving matrix multiplication\n- OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes(blkIn, right, blkOut, _op);\n+ OperationsOnMatrixValues.matMult(blkIn, right, blkOut, _op);\n}\nreturn new Tuple2<>(ixIn, blkOut);\n@@ -430,32 +430,23 @@ public class MapmmSPInstruction extends BinarySPInstruction {\npublic Iterator<Tuple2<MatrixIndexes, MatrixBlock>> call( Tuple2<MatrixIndexes, MatrixBlock> arg0 )\nthrows Exception\n{\n- ArrayList<Tuple2<MatrixIndexes, MatrixBlock>> ret = new ArrayList<>();\nMatrixIndexes ixIn = arg0._1();\nMatrixBlock blkIn = arg0._2();\nif( _type == CacheType.LEFT ) {\n- //for all matching left-hand-side blocks\n- int len = _pbc.getNumRowBlocks();\n- for( int i=1; i<=len; i++ ) {\n- MatrixBlock left = _pbc.getBlock(i, (int)ixIn.getRowIndex());\n- MatrixBlock blkOut = OperationsOnMatrixValues\n- .performAggregateBinaryIgnoreIndexes(left, blkIn, new MatrixBlock(), _op);\n- ret.add(new Tuple2<>(new MatrixIndexes(i, ixIn.getColumnIndex()), blkOut));\n- }\n+ //for all matching left-hand-side blocks, returned as lazy iterator\n+ return IntStream.range(1, _pbc.getNumRowBlocks()+1).mapToObj(i ->\n+ new Tuple2<>(new MatrixIndexes(i, ixIn.getColumnIndex()),\n+ OperationsOnMatrixValues.matMult(_pbc.getBlock(i, (int)ixIn.getRowIndex()), blkIn,\n+ new MatrixBlock(), _op))).iterator();\n}\nelse { //RIGHT\n- //for all matching right-hand-side blocks\n- int len = _pbc.getNumColumnBlocks();\n- for( int j=1; j<=len; j++ ) {\n- MatrixBlock right = _pbc.getBlock((int)ixIn.getColumnIndex(), j);\n- MatrixBlock blkOut = OperationsOnMatrixValues\n- .performAggregateBinaryIgnoreIndexes(blkIn, right, new MatrixBlock(), _op);\n- ret.add(new Tuple2<>(new MatrixIndexes(ixIn.getRowIndex(), j), blkOut));\n- }\n+ //for all matching right-hand-side blocks, returned as lazy iterator\n+ return IntStream.range(1, _pbc.getNumColumnBlocks()+1).mapToObj(j ->\n+ new Tuple2<>(new MatrixIndexes(ixIn.getRowIndex(), j),\n+ OperationsOnMatrixValues.matMult(blkIn, _pbc.getBlock((int)ixIn.getColumnIndex(), j),\n+ new MatrixBlock(), _op))).iterator();\n}\n-\n- return ret.iterator();\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MatrixReshapeSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/MatrixReshapeSPInstruction.java", "diff": "package org.apache.sysml.runtime.instructions.spark;\n-import java.util.ArrayList;\nimport java.util.Iterator;\n+import java.util.List;\nimport org.apache.spark.api.java.JavaPairRDD;\nimport org.apache.spark.api.java.function.PairFlatMapFunction;\n@@ -138,8 +138,8 @@ public class MatrixReshapeSPInstruction extends UnarySPInstruction\nIndexedMatrixValue in = SparkUtils.toIndexedMatrixBlock(arg0);\n//execute actual reshape operation\n- ArrayList<IndexedMatrixValue> out = LibMatrixReorg\n- .reshape(in, _mcIn, new ArrayList<>(), _mcOut, _byrow, _outputEmptyBlocks);\n+ List<IndexedMatrixValue> out = LibMatrixReorg\n+ .reshape(in, _mcIn, _mcOut, _byrow, _outputEmptyBlocks);\n//output conversion (for compatibility w/ rdd schema)\nreturn SparkUtils.fromIndexedMatrixBlock(out).iterator();\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/PMapmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/PMapmmSPInstruction.java", "diff": "@@ -193,8 +193,8 @@ public class PMapmmSPInstruction extends BinarySPInstruction {\nMatrixBlock left = pm.getBlock(i, (int)ixIn.getRowIndex());\n//execute matrix-vector mult\n- OperationsOnMatrixValues.performAggregateBinary(\n- new MatrixIndexes(i,ixIn.getRowIndex()), left, ixIn, blkIn, ixOut, blkOut, _op);\n+ OperationsOnMatrixValues.matMult(new MatrixIndexes(i,ixIn.getRowIndex()),\n+ left, ixIn, blkIn, ixOut, blkOut, _op);\n//output new tuple\nixOut.setIndexes(_offset+i, ixOut.getColumnIndex());\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/RmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/RmmSPInstruction.java", "diff": "@@ -191,8 +191,7 @@ public class RmmSPInstruction extends BinarySPInstruction {\nMatrixBlock blkIn2 = arg0._2()._2();\n//core block matrix multiplication\n- MatrixBlock blkOut = OperationsOnMatrixValues\n- .performAggregateBinaryIgnoreIndexes(blkIn1, blkIn2, new MatrixBlock(), _op);\n+ MatrixBlock blkOut = OperationsOnMatrixValues.matMult(blkIn1, blkIn2, new MatrixBlock(), _op);\n//output new tuple\nreturn new Tuple2<>(ixOut, blkOut);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/Tsmm2SPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/Tsmm2SPInstruction.java", "diff": "@@ -154,7 +154,7 @@ public class Tsmm2SPInstruction extends UnarySPInstruction {\n(int)(_type.isLeft()?1:ixin.getColumnIndex()));\nMatrixBlock mbin2t = transpose(mbin2, new MatrixBlock()); //prep for transpose rewrite mm\n- MatrixBlock out2 = (MatrixBlock) OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes( //mm\n+ MatrixBlock out2 = (MatrixBlock) OperationsOnMatrixValues.matMult( //mm\n_type.isLeft() ? mbin2t : mbin, _type.isLeft() ? mbin : mbin2t, new MatrixBlock(), _op);\nMatrixIndexes ixout2 = _type.isLeft() ? new MatrixIndexes(2,1) : new MatrixIndexes(1,2);\nret.add(new Tuple2<>(ixout2, out2));\n@@ -215,7 +215,7 @@ public class Tsmm2SPInstruction extends UnarySPInstruction {\n(int)(_type.isLeft()?1:ixin.getColumnIndex()));\nMatrixBlock mbin2t = transpose(mbin2, new MatrixBlock()); //prep for transpose rewrite mm\n- MatrixBlock out2 = OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes( //mm\n+ MatrixBlock out2 = OperationsOnMatrixValues.matMult( //mm\n_type.isLeft() ? mbin2t : mbin, _type.isLeft() ? mbin : mbin2t, new MatrixBlock(), _op);\nMatrixIndexes ixout2 = _type.isLeft() ? new MatrixIndexes(2,1) : new MatrixIndexes(1,2);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/ZipmmSPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/ZipmmSPInstruction.java", "diff": "@@ -125,8 +125,7 @@ public class ZipmmSPInstruction extends BinarySPInstruction {\nMatrixBlock tmp = (MatrixBlock)in2.reorgOperations(_rop, new MatrixBlock(), 0, 0, 0);\n//core matrix multiplication (for t(y)%*%X or t(X)%*%y)\n- return OperationsOnMatrixValues\n- .performAggregateBinaryIgnoreIndexes(tmp, in1, new MatrixBlock(), _abop);\n+ return OperationsOnMatrixValues.matMult(tmp, in1, new MatrixBlock(), _abop);\n}\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java", "diff": "@@ -28,10 +28,11 @@ import java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\n-import java.util.Map.Entry;\n+import java.util.Map;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Future;\n+import java.util.stream.Collectors;\nimport org.apache.sysml.runtime.DMLRuntimeException;\nimport org.apache.sysml.runtime.controlprogram.caching.MatrixObject.UpdateType;\n@@ -69,9 +70,6 @@ public class LibMatrixReorg\n//safe due to copy-on-write and safe update-in-place handling)\npublic static final boolean SHALLOW_COPY_REORG = true;\n- //allow reuse of temporary blocks for certain operations\n- public static final boolean ALLOW_BLOCK_REUSE = false;\n-\n//use csr instead of mcsr sparse block for rexpand columns / diag v2m\npublic static final boolean SPARSE_OUTPUTS_IN_CSR = true;\n@@ -465,15 +463,15 @@ public class LibMatrixReorg\n* @param outputEmptyBlocks output blocks with nnz=0\n* @return list of indexed matrix values\n*/\n- public static ArrayList<IndexedMatrixValue> reshape( IndexedMatrixValue in, MatrixCharacteristics mcIn,\n- ArrayList<IndexedMatrixValue> out, MatrixCharacteristics mcOut, boolean rowwise, boolean outputEmptyBlocks ) {\n+ public static List<IndexedMatrixValue> reshape(IndexedMatrixValue in, MatrixCharacteristics mcIn,\n+ MatrixCharacteristics mcOut, boolean rowwise, boolean outputEmptyBlocks ) {\n//prepare inputs\nMatrixIndexes ixIn = in.getIndexes();\nMatrixBlock mbIn = (MatrixBlock) in.getValue();\n//prepare result blocks (no reuse in order to guarantee mem constraints)\nCollection<MatrixIndexes> rix = computeAllResultBlockIndexes(ixIn, mcIn, mcOut, mbIn, rowwise, outputEmptyBlocks);\n- HashMap<MatrixIndexes, MatrixBlock> rblk = createAllResultBlocks(rix, mbIn.nonZeros, mcIn, mcOut, rowwise, out);\n+ Map<MatrixIndexes, MatrixBlock> rblk = createAllResultBlocks(rix, mbIn.nonZeros, mcOut);\n//basic algorithm\nlong row_offset = (ixIn.getRowIndex()-1)*mcIn.getRowsPerBlock();\n@@ -483,15 +481,11 @@ public class LibMatrixReorg\nelse //dense\nreshapeDense(mbIn, row_offset, col_offset, rblk, mcIn, mcOut, rowwise);\n- //prepare output\n- out = new ArrayList<>();\n- for( Entry<MatrixIndexes, MatrixBlock> e : rblk.entrySet() )\n- if( outputEmptyBlocks || !e.getValue().isEmptyBlock(false) ) {\n- e.getValue().examSparsity(); //ensure correct format\n- out.add(new IndexedMatrixValue(e.getKey(),e.getValue()));\n- }\n-\n- return out;\n+ //prepare output (sparsity switch, wrapper)\n+ return rblk.entrySet().stream()\n+ .filter( e -> outputEmptyBlocks || !e.getValue().isEmptyBlock(false))\n+ .map(e -> {e.getValue().examSparsity(); return new IndexedMatrixValue(e.getKey(),e.getValue());})\n+ .collect(Collectors.toList());\n}\n/**\n@@ -1553,45 +1547,25 @@ public class LibMatrixReorg\n}\n}\n- @SuppressWarnings(\"unused\")\n- private static HashMap<MatrixIndexes, MatrixBlock> createAllResultBlocks( Collection<MatrixIndexes> rix,\n- long nnz, MatrixCharacteristics mcIn, MatrixCharacteristics mcOut,\n- boolean rowwise, ArrayList<IndexedMatrixValue> reuse )\n- {\n- HashMap<MatrixIndexes, MatrixBlock> ret = new HashMap<MatrixIndexes,MatrixBlock>();\n- long nBlocks = rix.size();\n- int count = 0;\n+ private static Map<MatrixIndexes, MatrixBlock> createAllResultBlocks(Collection<MatrixIndexes> rix, long nnz, MatrixCharacteristics mcOut) {\n+ return rix.stream().collect(Collectors.toMap(ix -> ix, ix -> createResultBlock(ix, nnz, rix.size(), mcOut)));\n+ }\n- for( MatrixIndexes ix : rix )\n- {\n+ private static MatrixBlock createResultBlock(MatrixIndexes ix, long nnz, int nBlocks, MatrixCharacteristics mcOut) {\n//compute indexes\nlong bi = ix.getRowIndex();\nlong bj = ix.getColumnIndex();\nint lbrlen = UtilFunctions.computeBlockSize(mcOut.getRows(), bi, mcOut.getRowsPerBlock());\nint lbclen = UtilFunctions.computeBlockSize(mcOut.getCols(), bj, mcOut.getColsPerBlock());\n-\n+ if( lbrlen<1 || lbclen<1 )\n+ throw new DMLRuntimeException(\"Computed block dimensions (\"+bi+\",\"+bj+\" -> \"+lbrlen+\",\"+lbclen+\") are invalid!\");\n//create result block\nint estnnz = (int) (nnz/nBlocks); //force initial capacity per row to 1, for many blocks\nboolean sparse = MatrixBlock.evalSparseFormatInMemory(lbrlen, lbclen, estnnz);\n- MatrixBlock block = null;\n- if( ALLOW_BLOCK_REUSE && reuse!=null && !reuse.isEmpty()) {\n- block = (MatrixBlock) reuse.get(count++).getValue();\n- block.reset(lbrlen, lbclen, sparse, estnnz);\n- }\n- else\n- block = new MatrixBlock(lbrlen, lbclen, sparse, estnnz);\n-\n- if( lbrlen<1 || lbclen<1 )\n- throw new RuntimeException(\"Computed block dimensions (\"+bi+\",\"+bj+\" -> \"+lbrlen+\",\"+lbclen+\") are invalid!\");\n-\n- ret.put(ix, block);\n- }\n-\n- return ret;\n+ return new MatrixBlock(lbrlen, lbclen, sparse, estnnz);\n}\n- private static void reshapeDense( MatrixBlock in, long row_offset, long col_offset,\n- HashMap<MatrixIndexes,MatrixBlock> rix,\n+ private static void reshapeDense( MatrixBlock in, long row_offset, long col_offset, Map<MatrixIndexes,MatrixBlock> rix,\nMatrixCharacteristics mcIn, MatrixCharacteristics mcOut, boolean rowwise ) {\nif( in.isEmptyBlock(false) )\nreturn;\n@@ -1622,14 +1596,12 @@ public class LibMatrixReorg\n//cleanup for sparse blocks\nif( !rowwise && mcIn.getRows() > 1 ) {\n- for( MatrixBlock block : rix.values() )\n- if( block.sparse )\n- block.sortSparseRows();\n+ rix.values().stream().filter(b -> b.sparse)\n+ .forEach(b -> b.sortSparseRows());\n}\n}\n- private static void reshapeSparse( MatrixBlock in, long row_offset, long col_offset,\n- HashMap<MatrixIndexes,MatrixBlock> rix,\n+ private static void reshapeSparse( MatrixBlock in, long row_offset, long col_offset, Map<MatrixIndexes,MatrixBlock> rix,\nMatrixCharacteristics mcIn, MatrixCharacteristics mcOut, boolean rowwise ) {\nif( in.isEmptyBlock(false) )\nreturn;\n@@ -1639,35 +1611,36 @@ public class LibMatrixReorg\n//append all values to right blocks\nMatrixIndexes ixtmp = new MatrixIndexes();\n- for( int i=0; i<rlen; i++ )\n- {\n- if( !a.isEmpty(i) ) {\n+ for( int i=0; i<rlen; i++ ) {\n+ if( a.isEmpty(i) ) continue;\nlong ai = row_offset+i;\nint apos = a.pos(i);\nint alen = a.size(i);\nint[] aix = a.indexes(i);\ndouble[] avals = a.values(i);\n-\nfor( int j=apos; j<apos+alen; j++ ) {\nlong aj = col_offset+aix[j];\nixtmp = computeResultBlockIndex(ixtmp, ai, aj, mcIn, mcOut, rowwise);\n- MatrixBlock out = rix.get(ixtmp);\n- if( out == null )\n- throw new DMLRuntimeException(\"Missing result block: \"+ixtmp);\n+ MatrixBlock out = getAllocatedBlock(rix, ixtmp);\nixtmp = computeInBlockIndex(ixtmp, ai, aj, mcIn, mcOut, rowwise);\nout.appendValue((int)ixtmp.getRowIndex(),(int)ixtmp.getColumnIndex(), avals[j]);\n}\n}\n- }\n//cleanup for sparse blocks\nif( !rowwise && mcIn.getRows() > 1 ) {\n- for( MatrixBlock block : rix.values() )\n- if( block.sparse )\n- block.sortSparseRows();\n+ rix.values().stream().filter(b -> b.sparse)\n+ .forEach(b -> b.sortSparseRows());\n}\n}\n+ private static MatrixBlock getAllocatedBlock(Map<MatrixIndexes,MatrixBlock> rix, MatrixIndexes ix) {\n+ MatrixBlock out = rix.get(ix);\n+ if( out == null )\n+ throw new DMLRuntimeException(\"Missing result block: \"+ix);\n+ return out;\n+ }\n+\n/**\n* Assumes internal (0-begin) indices ai, aj as input; computes external block indexes (1-begin)\n*\n@@ -1682,25 +1655,27 @@ public class LibMatrixReorg\nprivate static MatrixIndexes computeResultBlockIndex( MatrixIndexes ixout, long ai, long aj,\nMatrixCharacteristics mcIn, MatrixCharacteristics mcOut, boolean rowwise )\n{\n- long tempc = rowwise ? ai*mcIn.getCols()+aj : ai+mcIn.getRows()*aj;\n+ long tempc = computeGlobalCellIndex(mcIn, ai, aj, rowwise);\nlong ci = rowwise ? tempc/mcOut.getCols() : tempc%mcOut.getRows();\nlong cj = rowwise ? tempc%mcOut.getCols() : tempc/mcOut.getRows();\nlong bci = ci/mcOut.getRowsPerBlock() + 1;\nlong bcj = cj/mcOut.getColsPerBlock() + 1;\n- return (ixout != null) ? ixout.setIndexes(bci, bcj) :\n- new MatrixIndexes(bci, bcj);\n+ return ixout.setIndexes(bci, bcj);\n}\nprivate static MatrixIndexes computeInBlockIndex( MatrixIndexes ixout, long ai, long aj,\nMatrixCharacteristics mcIn, MatrixCharacteristics mcOut, boolean rowwise )\n{\n- long tempc = rowwise ? ai*mcIn.getCols()+aj : ai+mcIn.getRows()*aj;\n+ long tempc = computeGlobalCellIndex(mcIn, ai, aj, rowwise);\nlong ci = rowwise ? (tempc/mcOut.getCols())%mcOut.getRowsPerBlock() :\n(tempc%mcOut.getRows())%mcOut.getRowsPerBlock();\nlong cj = rowwise ? (tempc%mcOut.getCols())%mcOut.getColsPerBlock() :\n(tempc/mcOut.getRows())%mcOut.getColsPerBlock();\n- return (ixout != null) ? ixout.setIndexes(ci, cj) :\n- new MatrixIndexes(ci, cj);\n+ return ixout.setIndexes(ci, cj);\n+ }\n+\n+ private static long computeGlobalCellIndex(MatrixCharacteristics mcIn, long ai, long aj, boolean rowwise) {\n+ return rowwise ? ai*mcIn.getCols()+aj : ai+mcIn.getRows()*aj;\n}\nprivate static MatrixBlock removeEmptyRows(MatrixBlock in, MatrixBlock ret, MatrixBlock select, boolean emptyReturn) {\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "diff": "@@ -218,7 +218,7 @@ public class OperationsOnMatrixValues\nvalueIn.aggregateUnaryOperations(op, valueOut, brlen, bclen, indexesIn);\n}\n- public static MatrixBlock performAggregateBinary(MatrixIndexes indexes1, MatrixBlock value1, MatrixIndexes indexes2, MatrixBlock value2,\n+ public static MatrixBlock matMult(MatrixIndexes indexes1, MatrixBlock value1, MatrixIndexes indexes2, MatrixBlock value2,\nMatrixIndexes indexesOut, MatrixBlock valueOut, AggregateBinaryOperator op) {\n//compute output index\nindexesOut.setIndexes(indexes1.getRowIndex(), indexes2.getColumnIndex());\n@@ -229,7 +229,7 @@ public class OperationsOnMatrixValues\nreturn value1.aggregateBinaryOperations(indexes1, value1, indexes2, value2, valueOut, op);\n}\n- public static MatrixBlock performAggregateBinaryIgnoreIndexes(MatrixBlock value1, MatrixBlock value2,\n+ public static MatrixBlock matMult(MatrixBlock value1, MatrixBlock value2,\nMatrixBlock valueOut, AggregateBinaryOperator op) {\n//perform on the value\nif( value2 instanceof CompressedMatrixBlock )\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/mapred/MMCJMRReducerWithAggregator.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/mapred/MMCJMRReducerWithAggregator.java", "diff": "@@ -123,15 +123,15 @@ public class MMCJMRReducerWithAggregator extends MMCJMRCombinerReducerBase\n{\n//perform matrix multiplication\nindexesbuffer.setIndexes(tmp.getKey().getRowIndex(), inIndex);\n- OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes((MatrixBlock)tmp.getValue(),\n- (MatrixBlock)inValue, (MatrixBlock)valueBuffer, (AggregateBinaryOperator)aggBinInstruction.getOperator());\n+ OperationsOnMatrixValues.matMult((MatrixBlock)tmp.getValue(), (MatrixBlock)inValue,\n+ (MatrixBlock)valueBuffer, (AggregateBinaryOperator)aggBinInstruction.getOperator());\n}\nelse //right cached\n{\n//perform matrix multiplication\nindexesbuffer.setIndexes(inIndex, tmp.getKey().getColumnIndex());\n- OperationsOnMatrixValues.performAggregateBinaryIgnoreIndexes((MatrixBlock)inValue,\n- (MatrixBlock)tmp.getValue(), (MatrixBlock)valueBuffer, (AggregateBinaryOperator)aggBinInstruction.getOperator());\n+ OperationsOnMatrixValues.matMult((MatrixBlock)inValue, (MatrixBlock)tmp.getValue(),\n+ (MatrixBlock)valueBuffer, (AggregateBinaryOperator)aggBinInstruction.getOperator());\n}\n//aggregate block to output buffer or direct output\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2237] Performance spark mapmm (lazy-iter) / reshape (sparse) This patch makes a minor performance improvement to spark mapmm operations that require flatmap, by returning a lazy iterator which has the potential to improve memory efficiency and thus reduce unnecessary GC overhead. Furthermore, this also includes some cleanups including spark reshape operations.
49,738
17.04.2018 00:50:14
25,200
767477aee30d376ffac4d07e9333826df1789e0a
[HOTFIX] Fix minor javadoc issue (removed method parameter)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixReorg.java", "diff": "@@ -457,7 +457,6 @@ public class LibMatrixReorg\n*\n* @param in indexed matrix value\n* @param mcIn input matrix characteristics\n- * @param out list of indexed matrix values\n* @param mcOut output matrix characteristics\n* @param rowwise if true, reshape by row\n* @param outputEmptyBlocks output blocks with nnz=0\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix minor javadoc issue (removed method parameter)
49,738
17.04.2018 20:17:25
25,200
d1389c3eab2f0ab3accfa247316e4500eaac7116
[MINOR] Performance right indexing (avoid unnecessary nnz maintenance)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "diff": "@@ -3726,7 +3726,8 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab\n}\n//compute nnz of output (not maintained due to native calls)\n- dest.recomputeNonZeros();\n+ dest.setNonZeros((getNonZeros() == getLength()) ?\n+ (ru-rl+1) * (cu-cl+1) : dest.recomputeNonZeros());\n}\n@Override\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Performance right indexing (avoid unnecessary nnz maintenance)
49,738
18.04.2018 21:26:01
25,200
f6e3a91dfe8852839be6b471ba0eabc723f55bf1
Exploit native matrix mult in dense wsigmoid This patch improves the performance of the fused dense wsigmoid on modern processors with wide SIMD registers and fma by exploiting a native matrix mult as part of the larger wsigmod computation.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixMult.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixMult.java", "diff": "@@ -42,6 +42,7 @@ import org.apache.sysml.runtime.functionobjects.ValueFunction;\nimport org.apache.sysml.runtime.matrix.operators.ReorgOperator;\nimport org.apache.sysml.runtime.util.CommonThreadPool;\nimport org.apache.sysml.runtime.util.UtilFunctions;\n+import org.apache.sysml.utils.NativeHelper;\n/**\n* MB: Library for matrix multiplications including MM, MV, VV for all\n@@ -557,7 +558,13 @@ public class LibMatrixMult\nret.allocateBlock();\n//core weighted square sum mm computation\n- if( !mW.sparse && !mU.sparse && !mV.sparse && !mU.isEmptyBlock() && !mV.isEmptyBlock() )\n+ boolean allDense = !mW.sparse && !mU.sparse && !mV.sparse\n+ && !mU.isEmptyBlock() && !mV.isEmptyBlock();\n+ if( NativeHelper.isNativeLibraryLoaded() && allDense && (mW.rlen == 1 || mW.clen == 1)\n+ && !LibMatrixNative.isMatMultMemoryBound(mU.rlen, mU.clen, mV.rlen)\n+ && mW.getDenseBlock().isContiguous() && mU.getDenseBlock().isContiguous() && mV.getDenseBlock().isContiguous() )\n+ matrixMultWSigmoidDenseNative(mW, mU, mV, ret, wt);\n+ else if( allDense )\nmatrixMultWSigmoidDense(mW, mU, mV, ret, wt, 0, mW.rlen);\nelse if( mW.sparse && !mU.sparse && !mV.sparse && !mU.isEmptyBlock() && !mV.isEmptyBlock())\nmatrixMultWSigmoidSparseDense(mW, mU, mV, ret, wt, 0, mW.rlen);\n@@ -2384,6 +2391,30 @@ public class LibMatrixMult\ndotProduct(tmp1.getDenseBlockValues(), tmp2.getDenseBlockValues(), mU.clen*mU.clen)));\n}\n+ private static void matrixMultWSigmoidDenseNative(MatrixBlock mW, MatrixBlock mU, MatrixBlock mV, MatrixBlock ret, WSigmoidType wt) {\n+ double[] w = mW.getDenseBlockValues();\n+ double[] c = ret.getDenseBlockValues();\n+ final int m = mW.rlen, n = mW.clen;\n+ final int cd = mU.clen;\n+ boolean flagminus = (wt==WSigmoidType.MINUS || wt==WSigmoidType.LOG_MINUS);\n+ boolean flaglog = (wt==WSigmoidType.LOG || wt==WSigmoidType.LOG_MINUS);\n+\n+ //call native matrix multiplication (only called for single-threaded and matrix-vector\n+ //because this ensures that we can deal with the transpose mV without additional transpose)\n+ if(!NativeHelper.dmmdd(((m==1)?mV:mU).getDenseBlockValues(),\n+ ((m==1)?mU:mV).getDenseBlockValues(), c, (m==1)?n:m, cd, 1, 1) )\n+ throw new DMLRuntimeException(\"Error executing native matrix mult.\");\n+\n+ //compute remaining wsigmoid for all relevant outputs\n+ for(int i=0, ix=0; i<m; i++, ix+=n) {\n+ for(int j=0; j<n; j++) {\n+ double wij = w[ix +j];\n+ //if( wij != 0 )\n+ c[ix+j] = wsigmoid(wij, c[ix+j], flagminus, flaglog);\n+ }\n+ }\n+ }\n+\nprivate static void matrixMultWSigmoidDense(MatrixBlock mW, MatrixBlock mU, MatrixBlock mV, MatrixBlock ret, WSigmoidType wt, int rl, int ru) {\nDenseBlock w = mW.getDenseBlock();\nDenseBlock c = ret.getDenseBlock();\n@@ -3463,6 +3494,16 @@ public class LibMatrixMult\nreturn wij * ((flaglog) ? Math.log(cval) : cval);\n}\n+ private static double wsigmoid(final double wij, final double uvij, final boolean flagminus, final boolean flaglog) {\n+ //compute core sigmoid function\n+ double cval = flagminus ?\n+ 1 / (1 + FastMath.exp(uvij)) :\n+ 1 / (1 + FastMath.exp(-uvij));\n+\n+ //compute weighted output\n+ return wij * ((flaglog) ? Math.log(cval) : cval);\n+ }\n+\nprivate static void wdivmm( final double wij, double[] u, double[] v, double[] c, final int uix, final int vix, final boolean left, final boolean mult, final boolean minus, final int len )\n{\n//compute dot product over ui vj\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixNative.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixNative.java", "diff": "@@ -48,7 +48,7 @@ public class LibMatrixNative\n// We could encapsulate heuristics in this function\n// For now, we only consider matrix-vector operation to be memory bound\n- private static boolean isMatMultMemoryBound(int m1Rlen, int m1Clen, int m2Clen) {\n+ public static boolean isMatMultMemoryBound(int m1Rlen, int m1Clen, int m2Clen) {\nreturn (m1Rlen == 1 || m1Clen == 1 || m2Clen == 1)\n&& (8L*m1Rlen*m1Clen > 16 * LibMatrixMult.L3_CACHESIZE\n|| 8L*m1Clen*m2Clen > 16 * LibMatrixMult.L3_CACHESIZE);\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2256] Exploit native matrix mult in dense wsigmoid This patch improves the performance of the fused dense wsigmoid on modern processors with wide SIMD registers and fma by exploiting a native matrix mult as part of the larger wsigmod computation.
49,738
20.04.2018 17:19:03
25,200
a1513d3a1f1e11c89e6dc3644df8fa29769e382e
[HOTFIX][SYSTEMML-2259] Fix correctness new dense-sparse MV mult ops This patch fixes the newly introduced dense-sparse MV mult special case, for inputs where the dense input has a rows of varing number of non-zeros (instead of a mix of empty and full dense rows).
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixBincell.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixBincell.java", "diff": "@@ -470,8 +470,10 @@ public class LibMatrixBincell\ndouble bval = b[i];\nif( bval != 0 ) {\nfor( int j=0; j<clen; j++ ) {\n+ double aval = a[aix+j];\n+ if( aval == 0 ) continue;\nindexes[pos] = j;\n- vals[pos] = a[aix+j] * bval;\n+ vals[pos] = aval * bval;\npos++;\n}\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX][SYSTEMML-2259] Fix correctness new dense-sparse MV mult ops This patch fixes the newly introduced dense-sparse MV mult special case, for inputs where the dense input has a rows of varing number of non-zeros (instead of a mix of empty and full dense rows).
49,738
20.04.2018 19:44:37
25,200
2f278bc2ac85d391b9353124ce85b7db884cba5b
Generalized multi-threaded unary ops dense blocks >16GB This patch generalized the newly introduced multi-threaded unary operations for large dense blocks >16GB by processing a physical block at a time via parallelSetAll.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "diff": "@@ -2584,15 +2584,18 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab\nelse\nLibMatrixAgg.cumaggregateUnaryMatrix(this, ret, op);\n}\n- else if(!sparse && !isEmptyBlock(false) && getDenseBlock().isContiguous()\n+ else if(!sparse && !isEmptyBlock(false)\n&& OptimizerUtils.isMaxLocalParallelism(op.getNumThreads())) {\n//note: we apply multi-threading in a best-effort manner here\n//only for expensive operators such as exp, log, sigmoid, because\n//otherwise allocation, read and write anyway dominates\nret.allocateDenseBlock(false);\n- double[] a = getDenseBlockValues();\n- double[] c = ret.getDenseBlockValues();\n- Arrays.parallelSetAll(c, i -> op.fn.execute(a[i]));\n+ DenseBlock a = getDenseBlock();\n+ DenseBlock c = ret.getDenseBlock();\n+ for(int bi=0; bi<a.numBlocks(); bi++) {\n+ double[] avals = a.valuesAt(bi), cvals = c.valuesAt(bi);\n+ Arrays.parallelSetAll(cvals, i -> op.fn.execute(avals[i]));\n+ }\nret.recomputeNonZeros();\n}\nelse {\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2267] Generalized multi-threaded unary ops dense blocks >16GB This patch generalized the newly introduced multi-threaded unary operations for large dense blocks >16GB by processing a physical block at a time via parallelSetAll.
49,738
21.04.2018 02:14:47
25,200
a22502583437efcf7c68619eefdde7c0c4bff74f
[MINOR] Cleanup dense matrix-vector wsigmoid via native matrixMult
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixMult.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixMult.java", "diff": "@@ -2406,6 +2406,9 @@ public class LibMatrixMult\nboolean flagminus = (wt==WSigmoidType.MINUS || wt==WSigmoidType.LOG_MINUS);\nboolean flaglog = (wt==WSigmoidType.LOG || wt==WSigmoidType.LOG_MINUS);\n+ //note: experiments with a fully native implementation of this method (even with #pragma omp simd)\n+ //showed performance regressions compared to this version because we benefit from FastMath.exp\n+\n//call native matrix multiplication (only called for single-threaded and matrix-vector\n//because this ensures that we can deal with the transpose mV without additional transpose)\nif(!NativeHelper.dmmdd(((m==1)?mV:mU).getDenseBlockValues(),\n@@ -2413,12 +2416,13 @@ public class LibMatrixMult\nthrow new DMLRuntimeException(\"Error executing native matrix mult.\");\n//compute remaining wsigmoid for all relevant outputs\n- for(int i=0, ix=0; i<m; i++, ix+=n) {\n- for(int j=0; j<n; j++) {\n- double wij = w[ix +j];\n- //if( wij != 0 )\n- c[ix+j] = wsigmoid(wij, c[ix+j], flagminus, flaglog);\n- }\n+ for( int i=0; i<m*n; i++ ) {\n+ //compute core sigmoid function\n+ double cval = flagminus ?\n+ 1 / (1 + FastMath.exp(c[i])) :\n+ 1 / (1 + FastMath.exp(-c[i]));\n+ //compute weighted output\n+ c[i] = w[i] * ((flaglog) ? Math.log(cval) : cval);\n}\n}\n@@ -3501,16 +3505,6 @@ public class LibMatrixMult\nreturn wij * ((flaglog) ? Math.log(cval) : cval);\n}\n- private static double wsigmoid(final double wij, final double uvij, final boolean flagminus, final boolean flaglog) {\n- //compute core sigmoid function\n- double cval = flagminus ?\n- 1 / (1 + FastMath.exp(uvij)) :\n- 1 / (1 + FastMath.exp(-uvij));\n-\n- //compute weighted output\n- return wij * ((flaglog) ? Math.log(cval) : cval);\n- }\n-\nprivate static void wdivmm( final double wij, double[] u, double[] v, double[] c, final int uix, final int vix, final boolean left, final boolean mult, final boolean minus, final int len )\n{\n//compute dot product over ui vj\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Cleanup dense matrix-vector wsigmoid via native matrixMult
49,738
21.04.2018 19:50:24
25,200
053e7ff03369577dce88fcc82f93345faffb638d
Refactoring dml library for scalable decompositions This patch consolidates the individual dml files of the library for scalable decompositions into a single dml file which simplifies debugging and the inclusion in custom application scripts. Furthermore, the function Choleskey has been renamed to Cholesky.
[ { "change_type": "DELETE", "old_path": "scripts/staging/scalable_linalg/cholesky.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-source(\"scalable_linalg/triangular_inv.dml\") as inv\n-\n-Choleskey = function(Matrix[double] A, int nb)\n- return(Matrix[double] L) {\n- n = ncol(A)\n-\n- if (n <= nb) {\n- L = cholesky(A)\n- } else {\n- k = as.integer(floor(n/2))\n- A11 = A[1:k,1:k]\n- A21 = A[k+1:n,1:k]\n- A22 = A[k+1:n,k+1:n]\n-\n- L11 = Choleskey(A11, nb)\n- L11inv = inv::U_triangular_inv(t(L11))\n- L21 = A21 %*% L11inv\n- A22 = A22 - L21 %*% t(L21)\n- L22 = Choleskey(A22, nb)\n- L12 = matrix(0, rows=nrow(L11), cols=ncol(L22))\n-\n- L = rbind(cbind(L11, L12), cbind(L21, L22))\n- }\n-}\n" }, { "change_type": "DELETE", "old_path": "scripts/staging/scalable_linalg/inverse.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-source(\"scalable_linalg/triangular_inv.dml\") as tinv\n-source(\"scalable_linalg/qr.dml\") as decomp\n-\n-Inverse = function(Matrix[double] A, int nb)\n- return(Matrix[double] X) {\n- # TODO: Some recent papers discuss Block-Recursive algorithm for\n- # matrix inverse which can be explored instead of QR decomposition\n-\n- [Q, R] = decomp::QR(A, nb)\n-\n- Rinv = tinv::U_triangular_inv(R)\n-\n- X = R %*% t(Q)\n-}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "scripts/staging/scalable_linalg/linalg_decomp.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+Cholesky = function(Matrix[double] A, int nb) return(Matrix[double] L) {\n+ n = ncol(A)\n+ if (n <= nb) {\n+ L = cholesky(A)\n+ }\n+ else {\n+ k = as.integer(floor(n/2))\n+ A11 = A[1:k,1:k]\n+ A21 = A[k+1:n,1:k]\n+ A22 = A[k+1:n,k+1:n]\n+\n+ L11 = Cholesky(A11, nb)\n+ L11inv = U_triangular_inv(t(L11))\n+ L21 = A21 %*% L11inv\n+ A22 = A22 - L21 %*% t(L21)\n+ L22 = Cholesky(A22, nb)\n+ L12 = matrix(0, nrow(L11), ncol(L22))\n+\n+ L = rbind(cbind(L11, L12), cbind(L21, L22))\n+ }\n+}\n+\n+Inverse = function(Matrix[double] A, int nb) return(Matrix[double] X) {\n+ # TODO: Some recent papers discuss Block-Recursive algorithm for\n+ # matrix inverse which can be explored instead of QR decomposition\n+\n+ [Q, R] = QR(A, nb)\n+ Rinv = U_triangular_inv(R)\n+ X = R %*% t(Q)\n+}\n+\n+LU = function(Matrix[double] A, int nb) return(Matrix[double] P, Matrix[double] L, Matrix[double] U) {\n+ n = ncol(A)\n+ if (n <= nb) {\n+ [P, L, U] = lu(A)\n+ }\n+ else {\n+ k = as.integer(floor(n/2))\n+ A11 = A[1:k,1:k]\n+ A12 = A[1:k,k+1:n]\n+ A21 = A[k+1:n,1:k]\n+ A22 = A[k+1:n,k+1:n]\n+\n+ [P11, L11, U11] = LU(A11, nb)\n+ L11inv = L_triangular_inv(L11)\n+ U11inv = U_triangular_inv(U11)\n+ U12 = L11inv %*% (P11 %*% A12)\n+ A22 = A22 - A21 %*% U11inv %*% U12\n+ [P22, L22, U22] = LU(A22, nb)\n+ L21 = P22 %*% A21 %*% U11inv\n+\n+ Z12 = matrix(0, nrow(A11), ncol(A22))\n+ Z21 = matrix(0, nrow(A22), ncol(A11))\n+\n+ L = rbind(cbind(L11, Z12), cbind(L21, L22))\n+ U = rbind(cbind(U11, U12), cbind(Z21, U22))\n+ P = rbind(cbind(P11, Z12), cbind(Z21, P22))\n+ }\n+}\n+\n+QR = function(Matrix[double] A, int nb) return(Matrix[double] Q, Matrix[double] R) {\n+ n = ncol(A)\n+ if (n <= nb) {\n+ [H, R] = qr(A)\n+ Q = QfromH(H)\n+ R = R[1:n, 1:n]\n+ }\n+ else {\n+ k = floor(n/2)\n+ A1 = A[,1:k]\n+ A2 = A[,k+1:n]\n+\n+ [Q1, R11] = QR(A1, nb)\n+ R12 = t(Q1) %*% A2\n+ A2 = A2 - Q1 %*% R12\n+ [Q2, R22] = QR(A2, nb)\n+ R21 = matrix(0, nrow(R22), ncol(R11))\n+\n+ Q = cbind(Q1, Q2)\n+ R = rbind(cbind(R11, R12), cbind(R21, R22))\n+ }\n+}\n+\n+# calculate Q from Housholder matrix\n+QfromH = function(Matrix[double] H) return(Matrix[double] Q) {\n+ m = nrow(H);\n+ n = ncol(H);\n+ ones = matrix(1, m, 1);\n+ eye = diag(ones);\n+ Q = eye[,1:n];\n+\n+ for (j in n:1) {\n+ v = H[j:m,j]\n+ b = as.scalar(2/(t(v) %*% v))\n+ Q[j:m, j:n] = Q[j:m, j:n] - (b * v) %*% (t(v) %*% Q[j:m, j:n])\n+ }\n+}\n+\n+Solve = function(Matrix[double] A, Matrix[double] b, int nb) return(Matrix[double] x) {\n+ # TODO: using thin QR may accumulate higher numerical errors.\n+ # Some modifications as suggested by Golub may be explored\n+\n+ [Q, R] = QR(A, nb)\n+ Rinv = U_triangular_inv(R)\n+ x = Rinv %*% t(Q) %*% b\n+}\n+\n+# Inverse of lower triangular matrix\n+L_triangular_inv = function(Matrix[double] L) return(Matrix[double] A) {\n+ n = ncol(L)\n+ if (n == 1) {\n+ A = 1/L[1,1]\n+ }\n+ else if (n == 2) {\n+ A = matrix(0, 2, 2)\n+ A[1,1] = L[2,2]\n+ A[2,2] = L[1,1]\n+ A[2,1] = -L[2,1]\n+ A = A/(as.scalar(L[1,1] * L[2,2]))\n+ }\n+ else {\n+ k = as.integer(floor(n/2))\n+\n+ L11 = L[1:k,1:k]\n+ L21 = L[k+1:n,1:k]\n+ L22 = L[k+1:n,k+1:n]\n+\n+ A11 = L_triangular_inv(L11)\n+ A22 = L_triangular_inv(L22)\n+ A12 = matrix(0, nrow(A11), ncol(A22))\n+ A21 = -A22 %*% L21 %*% A11\n+\n+ A = rbind(cbind(A11, A12), cbind(A21, A22))\n+ }\n+}\n+\n+# Inverse of upper triangular matrix\n+U_triangular_inv = function(Matrix[double] U) return(Matrix[double] A) {\n+ n = ncol(U)\n+ if (n == 1) {\n+ A = 1/U[1,1]\n+ }\n+ else if (n == 2) {\n+ A = matrix(0, 2, 2)\n+ A[1,1] = U[2,2]\n+ A[2,2] = U[1,1]\n+\n+ A[1,2] = -U[1,2]\n+ A = A/(as.scalar(U[1,1] * U[2,2]))\n+ }\n+ else {\n+ k = as.integer(floor(n/2))\n+\n+ U11 = U[1:k,1:k]\n+ U12 = U[1:k,k+1:n]\n+ U22 = U[k+1:n,k+1:n]\n+\n+ A11 = U_triangular_inv(U11)\n+ A22 = U_triangular_inv(U22)\n+ A12 = -A11 %*% U12 %*% A22\n+ A21 = matrix(0, nrow(A22), ncol(A11))\n+\n+ A = rbind(cbind(A11, A12), cbind(A21, A22))\n+ }\n+}\n" }, { "change_type": "DELETE", "old_path": "scripts/staging/scalable_linalg/lu.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-source(\"scalable_linalg/triangular_inv.dml\") as inv\n-\n-LU = function(Matrix[double] A, int nb)\n- return(Matrix[double] P, Matrix[double] L, Matrix[double] U) {\n- n = ncol(A)\n- if (n <= nb) {\n- [P, L, U] = lu(A)\n- } else {\n- k = as.integer(floor(n/2))\n- A11 = A[1:k,1:k]\n- A12 = A[1:k,k+1:n]\n- A21 = A[k+1:n,1:k]\n- A22 = A[k+1:n,k+1:n]\n-\n- [P11, L11, U11] = LU(A11, nb)\n- L11inv = inv::L_triangular_inv(L11)\n- U11inv = inv::U_triangular_inv(U11)\n- U12 = L11inv %*% (P11 %*% A12)\n- A22 = A22 - A21 %*% U11inv %*% U12\n- [P22, L22, U22] = LU(A22, nb)\n- L21 = P22 %*% A21 %*% U11inv\n-\n- Z12 = matrix(0, rows=nrow(A11), cols=ncol(A22))\n- Z21 = matrix(0, rows=nrow(A22), cols=ncol(A11))\n-\n- L = rbind(cbind(L11, Z12), cbind(L21, L22))\n- U = rbind(cbind(U11, U12), cbind(Z21, U22))\n- P = rbind(cbind(P11, Z12), cbind(Z21, P22))\n- }\n-}\n" }, { "change_type": "DELETE", "old_path": "scripts/staging/scalable_linalg/qr.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-# calculate Q from Housholder matrix\n-QfromH = function(Matrix[double] H)\n- return(Matrix[double] Q) {\n- m = nrow(H);\n- n = ncol(H);\n- ones = matrix(1, m, 1);\n- eye = diag(ones);\n- Q = eye[,1:n];\n-\n- for (j in n:1) {\n- v = H[j:m,j]\n- b = as.scalar(2/(t(v) %*% v))\n- Q[j:m, j:n] = Q[j:m, j:n] - (b * v) %*% (t(v) %*% Q[j:m, j:n])\n- }\n-}\n-\n-QR = function(Matrix[double] A, int nb)\n- return(Matrix[double] Q, Matrix[double] R) {\n- n = ncol(A)\n-\n- if (n <= nb) {\n- [H, R] = qr(A)\n- Q = QfromH(H)\n- R = R[1:n, 1:n]\n- }\n- else {\n- k = floor(n/2)\n- A1 = A[,1:k]\n- A2 = A[,k+1:n]\n-\n- [Q1, R11] = QR(A1, nb)\n- R12 = t(Q1) %*% A2\n- A2 = A2 - Q1 %*% R12\n- [Q2, R22] = QR(A2, nb)\n- R21 = matrix(0, rows = nrow(R22), cols = ncol(R11))\n-\n- Q = cbind(Q1, Q2)\n- R = rbind(cbind(R11, R12), cbind(R21, R22))\n- }\n-}\n" }, { "change_type": "DELETE", "old_path": "scripts/staging/scalable_linalg/solve.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-source(\"scalable_linalg/triangular_inv.dml\") as inv\n-source(\"scalable_linalg/qr.dml\") as decomp\n-\n-Solve = function(Matrix[double] A, Matrix[double] b, int nb)\n- return(Matrix[double] x) {\n- # TODO: using thin QR may accumulate higher numerical erros.\n- # Some modifications as suggested by Golub may be explored\n-\n- [Q, R] = decomp::QR(A, nb)\n-\n- Rinv = inv::U_triangular_inv(R)\n-\n- x = Rinv %*% t(Q) %*% b\n-}\n" }, { "change_type": "DELETE", "old_path": "scripts/staging/scalable_linalg/triangular_inv.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-# Inverse of lower triangular matrix\n-L_triangular_inv = function(Matrix[double] L)\n- return(Matrix[double] A) {\n- n = ncol(L)\n-\n- if (n == 1) {\n- A = 1/L[1,1]\n- } else if (n == 2) {\n- A = matrix(0, rows=2, cols=2)\n- A[1,1] = L[2,2]\n- A[2,2] = L[1,1]\n- A[2,1] = -L[2,1]\n- A = A/(as.scalar(L[1,1] * L[2,2]))\n- } else {\n- k = as.integer(floor(n/2))\n-\n- L11 = L[1:k,1:k]\n- L21 = L[k+1:n,1:k]\n- L22 = L[k+1:n,k+1:n]\n-\n- A11 = L_triangular_inv(L11)\n- A22 = L_triangular_inv(L22)\n- A12 = matrix(0, rows=nrow(A11), cols=ncol(A22))\n- A21 = -A22 %*% L21 %*% A11\n-\n- A = rbind(cbind(A11, A12), cbind(A21, A22))\n- }\n- }\n-\n-# Inverse of upper triangular matrix\n-U_triangular_inv = function(Matrix[double] U)\n- return(Matrix[double] A) {\n- n = ncol(U)\n-\n- if (n == 1) {\n- A = 1/U[1,1]\n- } else if (n == 2) {\n- A = matrix(0, rows=2, cols=2)\n- A[1,1] = U[2,2]\n- A[2,2] = U[1,1]\n-\n- A[1,2] = -U[1,2]\n- A = A/(as.scalar(U[1,1] * U[2,2]))\n- } else {\n- k = as.integer(floor(n/2))\n-\n- U11 = U[1:k,1:k]\n- U12 = U[1:k,k+1:n]\n- U22 = U[k+1:n,k+1:n]\n-\n- A11 = U_triangular_inv(U11)\n- A22 = U_triangular_inv(U22)\n- A12 = -A11 %*% U12 %*% A22\n- A21 = matrix(0, rows=nrow(A22), cols=ncol(A11))\n-\n- A = rbind(cbind(A11, A12), cbind(A21, A22))\n- }\n- }\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2270] Refactoring dml library for scalable decompositions This patch consolidates the individual dml files of the library for scalable decompositions into a single dml file which simplifies debugging and the inclusion in custom application scripts. Furthermore, the function Choleskey has been renamed to Cholesky.
49,738
21.04.2018 22:13:42
25,200
0209edd7c8e84fac9f4d2c9c80b0ea7e664e798e
[MINOR] Cleanup lib commons math (input/output consistency)
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/BinaryMatrixMatrixCPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/BinaryMatrixMatrixCPInstruction.java", "diff": "package org.apache.sysml.runtime.instructions.cp;\n-import org.apache.sysml.runtime.controlprogram.caching.MatrixObject;\nimport org.apache.sysml.runtime.controlprogram.context.ExecutionContext;\nimport org.apache.sysml.runtime.matrix.data.LibCommonsMath;\nimport org.apache.sysml.runtime.matrix.data.MatrixBlock;\n@@ -35,11 +34,12 @@ public class BinaryMatrixMatrixCPInstruction extends BinaryCPInstruction {\n@Override\npublic void processInstruction(ExecutionContext ec) {\n- String opcode = getOpcode();\n- if ( LibCommonsMath.isSupportedMatrixMatrixOperation(opcode) ) {\n+ if ( LibCommonsMath.isSupportedMatrixMatrixOperation(getOpcode()) ) {\nMatrixBlock solution = LibCommonsMath.matrixMatrixOperations(\n- ec.getMatrixObject(input1.getName()), (MatrixObject)ec.getVariable(input2.getName()), opcode);\n+ ec.getMatrixInput(input1.getName()), ec.getMatrixInput(input2.getName()), getOpcode());\nec.setMatrixOutput(output.getName(), solution, getExtendedOpcode());\n+ ec.releaseMatrixInput(input1.getName());\n+ ec.releaseMatrixInput(input2.getName());\nreturn;\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/MultiReturnBuiltinCPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/MultiReturnBuiltinCPInstruction.java", "diff": "@@ -24,7 +24,6 @@ import java.util.ArrayList;\nimport org.apache.sysml.parser.Expression.DataType;\nimport org.apache.sysml.parser.Expression.ValueType;\nimport org.apache.sysml.runtime.DMLRuntimeException;\n-import org.apache.sysml.runtime.controlprogram.caching.MatrixObject;\nimport org.apache.sysml.runtime.controlprogram.context.ExecutionContext;\nimport org.apache.sysml.runtime.instructions.InstructionUtils;\nimport org.apache.sysml.runtime.matrix.data.LibCommonsMath;\n@@ -98,16 +97,12 @@ public class MultiReturnBuiltinCPInstruction extends ComputationCPInstruction {\n@Override\npublic void processInstruction(ExecutionContext ec) {\n- String opcode = getOpcode();\n- MatrixObject mo = ec.getMatrixObject(input1.getName());\n- MatrixBlock[] out = null;\n-\n- if(LibCommonsMath.isSupportedMultiReturnOperation(opcode))\n- out = LibCommonsMath.multiReturnOperations(mo, opcode);\n- else\n- throw new DMLRuntimeException(\"Invalid opcode in MultiReturnBuiltin instruction: \" + opcode);\n-\n+ if(!LibCommonsMath.isSupportedMultiReturnOperation(getOpcode()))\n+ throw new DMLRuntimeException(\"Invalid opcode in MultiReturnBuiltin instruction: \" + getOpcode());\n+ MatrixBlock in = ec.getMatrixInput(input1.getName());\n+ MatrixBlock[] out = LibCommonsMath.multiReturnOperations(in, getOpcode());\n+ ec.releaseMatrixInput(input1.getName(), getExtendedOpcode());\nfor(int i=0; i < _outputs.size(); i++) {\nec.setMatrixOutput(_outputs.get(i).getName(), out[i], getExtendedOpcode());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/UnaryMatrixCPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/cp/UnaryMatrixCPInstruction.java", "diff": "@@ -32,21 +32,22 @@ public class UnaryMatrixCPInstruction extends UnaryCPInstruction {\n@Override\npublic void processInstruction(ExecutionContext ec) {\n- String output_name = output.getName();\n- String opcode = getOpcode();\n- if(LibCommonsMath.isSupportedUnaryOperation(opcode)) {\n- MatrixBlock retBlock = LibCommonsMath.unaryOperations(ec.getMatrixObject(input1.getName()),getOpcode());\n- ec.setMatrixOutput(output_name, retBlock, getExtendedOpcode());\n+ MatrixBlock inBlock = ec.getMatrixInput(input1.getName(), getExtendedOpcode());\n+ MatrixBlock retBlock = null;\n+\n+ if(LibCommonsMath.isSupportedUnaryOperation(getOpcode())) {\n+ retBlock = LibCommonsMath.unaryOperations(inBlock, getOpcode());\n+ ec.releaseMatrixInput(input1.getName(), getExtendedOpcode());\n}\nelse {\nUnaryOperator u_op = (UnaryOperator) _optr;\n- MatrixBlock inBlock = ec.getMatrixInput(input1.getName(), getExtendedOpcode());\n- MatrixBlock retBlock = (MatrixBlock) (inBlock.unaryOperations(u_op, new MatrixBlock()));\n+ retBlock = (MatrixBlock) (inBlock.unaryOperations(u_op, new MatrixBlock()));\nec.releaseMatrixInput(input1.getName(), getExtendedOpcode());\n// Ensure right dense/sparse output representation (guarded by released input memory)\nif( checkGuardedRepresentationChange(inBlock, retBlock) )\nretBlock.examSparsity();\n- ec.setMatrixOutput(output_name, retBlock, getExtendedOpcode());\n}\n+\n+ ec.setMatrixOutput(output.getName(), retBlock, getExtendedOpcode());\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibCommonsMath.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibCommonsMath.java", "diff": "@@ -28,7 +28,6 @@ import org.apache.commons.math3.linear.QRDecomposition;\nimport org.apache.commons.math3.linear.RealMatrix;\nimport org.apache.commons.math3.linear.SingularValueDecomposition;\nimport org.apache.sysml.runtime.DMLRuntimeException;\n-import org.apache.sysml.runtime.controlprogram.caching.MatrixObject;\nimport org.apache.sysml.runtime.util.DataConverter;\n/**\n@@ -56,7 +55,7 @@ public class LibCommonsMath\nreturn ( opcode.equals(\"solve\") );\n}\n- public static MatrixBlock unaryOperations(MatrixObject inj, String opcode) {\n+ public static MatrixBlock unaryOperations(MatrixBlock inj, String opcode) {\nArray2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(inj);\nif(opcode.equals(\"inverse\"))\nreturn computeMatrixInverse(matrixInput);\n@@ -65,7 +64,7 @@ public class LibCommonsMath\nreturn null;\n}\n- public static MatrixBlock[] multiReturnOperations(MatrixObject in, String opcode) {\n+ public static MatrixBlock[] multiReturnOperations(MatrixBlock in, String opcode) {\nif(opcode.equals(\"qr\"))\nreturn computeQR(in);\nelse if (opcode.equals(\"lu\"))\n@@ -77,7 +76,7 @@ public class LibCommonsMath\nreturn null;\n}\n- public static MatrixBlock matrixMatrixOperations(MatrixObject in1, MatrixObject in2, String opcode) {\n+ public static MatrixBlock matrixMatrixOperations(MatrixBlock in1, MatrixBlock in2, String opcode) {\nif(opcode.equals(\"solve\")) {\nif (in1.getNumRows() != in1.getNumColumns())\nthrow new DMLRuntimeException(\"The A matrix, in solve(A,b) should have squared dimensions.\");\n@@ -93,7 +92,7 @@ public class LibCommonsMath\n* @param in2 matrix object 2\n* @return matrix block\n*/\n- private static MatrixBlock computeSolve(MatrixObject in1, MatrixObject in2) {\n+ private static MatrixBlock computeSolve(MatrixBlock in1, MatrixBlock in2) {\nArray2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in1);\nArray2DRowRealMatrix vectorInput = DataConverter.convertToArray2DRowRealMatrix(in2);\n@@ -116,7 +115,7 @@ public class LibCommonsMath\n* @param in matrix object\n* @return array of matrix blocks\n*/\n- private static MatrixBlock[] computeQR(MatrixObject in) {\n+ private static MatrixBlock[] computeQR(MatrixBlock in) {\nArray2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in);\n// Perform QR decomposition\n@@ -137,7 +136,7 @@ public class LibCommonsMath\n* @param in matrix object\n* @return array of matrix blocks\n*/\n- private static MatrixBlock[] computeLU(MatrixObject in) {\n+ private static MatrixBlock[] computeLU(MatrixBlock in) {\nif ( in.getNumRows() != in.getNumColumns() ) {\nthrow new DMLRuntimeException(\"LU Decomposition can only be done on a square matrix. Input matrix is rectangular (rows=\" + in.getNumRows() + \", cols=\"+ in.getNumColumns() +\")\");\n}\n@@ -165,7 +164,7 @@ public class LibCommonsMath\n* @param in matrix object\n* @return array of matrix blocks\n*/\n- private static MatrixBlock[] computeEigen(MatrixObject in) {\n+ private static MatrixBlock[] computeEigen(MatrixBlock in) {\nif ( in.getNumRows() != in.getNumColumns() ) {\nthrow new DMLRuntimeException(\"Eigen Decomposition can only be done on a square matrix. Input matrix is rectangular (rows=\" + in.getNumRows() + \", cols=\"+ in.getNumColumns() +\")\");\n}\n@@ -216,7 +215,7 @@ public class LibCommonsMath\n* @param in Input matrix\n* @return An array containing U, Sigma & V\n*/\n- private static MatrixBlock[] computeSvd(MatrixObject in) {\n+ private static MatrixBlock[] computeSvd(MatrixBlock in) {\nArray2DRowRealMatrix matrixInput = DataConverter.convertToArray2DRowRealMatrix(in);\nSingularValueDecomposition svd = new SingularValueDecomposition(matrixInput);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/util/DataConverter.java", "new_path": "src/main/java/org/apache/sysml/runtime/util/DataConverter.java", "diff": "@@ -31,7 +31,6 @@ import java.util.Map.Entry;\nimport org.apache.commons.math3.linear.Array2DRowRealMatrix;\nimport org.apache.sysml.parser.Expression.ValueType;\nimport org.apache.sysml.runtime.DMLRuntimeException;\n-import org.apache.sysml.runtime.controlprogram.caching.MatrixObject;\nimport org.apache.sysml.runtime.instructions.cp.BooleanObject;\nimport org.apache.sysml.runtime.io.MatrixReader;\nimport org.apache.sysml.runtime.io.MatrixReaderFactory;\n@@ -780,10 +779,8 @@ public class DataConverter\n* @param mo matrix object\n* @return matrix as a commons-math3 Array2DRowRealMatrix\n*/\n- public static Array2DRowRealMatrix convertToArray2DRowRealMatrix(MatrixObject mo) {\n- MatrixBlock mb = mo.acquireRead();\n+ public static Array2DRowRealMatrix convertToArray2DRowRealMatrix(MatrixBlock mb) {\ndouble[][] data = DataConverter.convertToDoubleMatrix(mb);\n- mo.release();\nreturn new Array2DRowRealMatrix(data, false);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[MINOR] Cleanup lib commons math (input/output consistency)
49,738
21.04.2018 22:17:55
25,200
d368644a2341ead8d5dcb47b6290fe7c7f833c7a
Include scalable decompositions in integration tests
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/InstructionUtils.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/InstructionUtils.java", "diff": "@@ -87,6 +87,7 @@ import org.apache.sysml.runtime.instructions.gpu.GPUInstruction.GPUINSTRUCTION_T\nimport org.apache.sysml.runtime.instructions.mr.MRInstruction.MRType;\nimport org.apache.sysml.runtime.instructions.spark.SPInstruction.SPType;\nimport org.apache.sysml.runtime.matrix.data.LibCommonsMath;\n+import org.apache.sysml.runtime.matrix.operators.AggregateBinaryOperator;\nimport org.apache.sysml.runtime.matrix.operators.AggregateOperator;\nimport org.apache.sysml.runtime.matrix.operators.AggregateTernaryOperator;\nimport org.apache.sysml.runtime.matrix.operators.AggregateUnaryOperator;\n@@ -865,4 +866,9 @@ public class InstructionUtils\n|| WeightedUnaryMM.OPCODE.equalsIgnoreCase(opcode) //mapwumm\n|| WeightedUnaryMMR.OPCODE.equalsIgnoreCase(opcode); //redwumm\n}\n+\n+ public static AggregateBinaryOperator getMatMultOperator(int k) {\n+ AggregateOperator agg = new AggregateOperator(0, Plus.getPlusFnObject());\n+ return new AggregateBinaryOperator(Multiply.getMultiplyFnObject(), agg, k);\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/AutomatedTestBase.java", "new_path": "src/test/java/org/apache/sysml/test/integration/AutomatedTestBase.java", "diff": "@@ -53,6 +53,7 @@ import org.apache.sysml.runtime.matrix.MatrixCharacteristics;\nimport org.apache.sysml.runtime.matrix.data.CSVFileFormatProperties;\nimport org.apache.sysml.runtime.matrix.data.FrameBlock;\nimport org.apache.sysml.runtime.matrix.data.InputInfo;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;\nimport org.apache.sysml.runtime.matrix.data.OutputInfo;\nimport org.apache.sysml.runtime.util.DataConverter;\n@@ -504,6 +505,11 @@ public abstract class AutomatedTestBase\nreturn matrix;\n}\n+ protected double[][] writeInputMatrixWithMTD(String name, MatrixBlock matrix, boolean bIncludeR) {\n+ double[][] data = DataConverter.convertToDoubleMatrix(matrix);\n+ return writeInputMatrixWithMTD(name, data, bIncludeR);\n+ }\n+\nprotected double[][] writeInputMatrixWithMTD(String name, double[][] matrix, boolean bIncludeR) {\nMatrixCharacteristics mc = new MatrixCharacteristics(matrix.length, matrix[0].length, OptimizerUtils.DEFAULT_BLOCKSIZE, OptimizerUtils.DEFAULT_BLOCKSIZE, -1);\nreturn writeInputMatrixWithMTD(name, matrix, bIncludeR, mc);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysml/test/integration/applications/dml/ScalableDecompositionTest.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.sysml.test.integration.applications.dml;\n+\n+import java.util.HashMap;\n+\n+import org.junit.Test;\n+import org.apache.sysml.api.DMLScript;\n+import org.apache.sysml.api.DMLScript.RUNTIME_PLATFORM;\n+import org.apache.sysml.hops.OptimizerUtils;\n+import org.apache.sysml.lops.LopProperties.ExecType;\n+import org.apache.sysml.lops.MMTSJ.MMTSJType;\n+import org.apache.sysml.runtime.instructions.InstructionUtils;\n+import org.apache.sysml.runtime.matrix.data.LibCommonsMath;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\n+import org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysml.test.integration.AutomatedTestBase;\n+import org.apache.sysml.test.integration.TestConfiguration;\n+import org.apache.sysml.test.utils.TestUtils;\n+\n+public class ScalableDecompositionTest extends AutomatedTestBase\n+{\n+ private final static String TEST_NAME1 = \"ScalableDecomposition\";\n+ private final static String TEST_DIR = \"applications/decomp/\";\n+ private final static String TEST_CLASS_DIR =\n+ TEST_DIR + ScalableDecompositionTest.class.getSimpleName() + \"/\";\n+\n+ private final static int rows = 1362;\n+ private final static int cols = 1362;\n+ private final static int blen = 200;\n+ private final static double eps = 1e-7;\n+\n+ private enum DecompType {\n+ CHOLESKY, LU, QR, SOLVE, INVERSE\n+ }\n+\n+ @Override\n+ public void setUp() {\n+ TestUtils.clearAssertionInformation();\n+ addTestConfiguration(TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { \"C\",\"D\",\"E\" }));\n+ }\n+\n+ @Test\n+ public void testCholeskyCP() {\n+ runKMeansTest(TEST_NAME1, DecompType.CHOLESKY, false, ExecType.CP);\n+ }\n+\n+ @Test\n+ public void testCholeskyRewritesCP() {\n+ runKMeansTest(TEST_NAME1, DecompType.CHOLESKY, true, ExecType.CP);\n+ }\n+\n+// @Test\n+// public void testCholeskySP() {\n+// runKMeansTest(TEST_NAME1, DecompType.CHOLESKY, false, ExecType.SPARK);\n+// }\n+//\n+// @Test\n+// public void testCholeskyRewritesSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.CHOLESKY, true, ExecType.SPARK);\n+// }\n+\n+// @Test\n+// public void testLUDecompCP() {\n+// runKMeansTest(TEST_NAME1, DecompType.LU, false, ExecType.CP);\n+// }\n+//\n+// @Test\n+// public void testLUDecompRewritesCP() {\n+// runKMeansTest(TEST_NAME1, DecompType.LU, true, ExecType.CP);\n+// }\n+\n+// @Test\n+// public void testLUDecompSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.LU, false, ExecType.SPARK);\n+// }\n+//\n+// @Test\n+// public void testLUDecompRewritesSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.LU, true, ExecType.SPARK);\n+// }\n+\n+// @Test\n+// public void testQRDecompCP() {\n+// runKMeansTest(TEST_NAME1, DecompType.QR, false, ExecType.CP);\n+// }\n+//\n+// @Test\n+// public void testQRDecompRewritesCP() {\n+// runKMeansTest(TEST_NAME1, DecompType.QR, true, ExecType.CP);\n+// }\n+\n+// @Test\n+// public void testQRDecompSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.QR, false, ExecType.SPARK);\n+// }\n+//\n+// @Test\n+// public void testQRDecompRewritesSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.QR, true, ExecType.SPARK);\n+// }\n+\n+// @Test\n+// public void testSolveCP() {\n+// runKMeansTest(TEST_NAME1, DecompType.SOLVE, false, ExecType.CP);\n+// }\n+//\n+// @Test\n+// public void testSolveRewritesCP() {\n+// runKMeansTest(TEST_NAME1, DecompType.SOLVE, true, ExecType.CP);\n+// }\n+\n+// @Test\n+// public void testSolveSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.SOLVE, false, ExecType.SPARK);\n+// }\n+//\n+// @Test\n+// public void testSolveRewritesSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.SOLVE, true, ExecType.SPARK);\n+// }\n+\n+// @Test\n+// public void testInverseCP() {\n+// runKMeansTest(TEST_NAME1, DecompType.SOLVE, false, ExecType.CP);\n+// }\n+//\n+// @Test\n+// public void testInverseRewritesCP() {\n+// runKMeansTest(TEST_NAME1, DecompType.SOLVE, true, ExecType.CP);\n+// }\n+\n+// @Test\n+// public void testInverseSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.SOLVE, false, ExecType.SPARK);\n+// }\n+//\n+// @Test\n+// public void testInverseRewritesSP() {\n+// runKMeansTest(TEST_NAME1, DecompType.SOLVE, true, ExecType.SPARK);\n+// }\n+\n+\n+ private void runKMeansTest(String testname, DecompType type, boolean rewrites, ExecType instType)\n+ {\n+ boolean oldFlag1 = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION;\n+ boolean oldFlag2 = OptimizerUtils.ALLOW_INTER_PROCEDURAL_ANALYSIS;\n+ RUNTIME_PLATFORM platformOld = rtplatform;\n+ switch( instType ){\n+ case SPARK: rtplatform = RUNTIME_PLATFORM.SPARK; break;\n+ default: rtplatform = RUNTIME_PLATFORM.HYBRID_SPARK; break;\n+ }\n+ boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG;\n+ if( rtplatform == RUNTIME_PLATFORM.SPARK || rtplatform == RUNTIME_PLATFORM.HYBRID_SPARK )\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = true;\n+\n+ try\n+ {\n+ TestConfiguration config = getTestConfiguration(testname);\n+ loadTestConfiguration(config);\n+\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewrites;\n+ OptimizerUtils.ALLOW_INTER_PROCEDURAL_ANALYSIS = rewrites;\n+\n+ fullDMLScriptName = SCRIPT_DIR + TEST_DIR + testname + \".dml\";\n+ programArgs = new String[]{\"-explain\",\"-args\",\n+ String.valueOf(type.ordinal()), String.valueOf(blen),\n+ input(\"A\"), input(\"B\"), output(\"C\"), output(\"D\"), output(\"E\") };\n+\n+ switch( type ) {\n+ case CHOLESKY: {\n+ MatrixBlock A = MatrixBlock.randOperations(rows, cols, 1.0, -5, 10, \"uniform\", 7);\n+ MatrixBlock AtA = A.transposeSelfMatrixMultOperations(new MatrixBlock(), MMTSJType.LEFT);\n+ writeInputMatrixWithMTD(\"A\", AtA, false);\n+ runTest(true, false, null, -1);\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"C\");\n+ MatrixBlock C2 = LibCommonsMath.unaryOperations(AtA, \"cholesky\");\n+ TestUtils.compareMatrices(dmlfile, C2, eps);\n+ break;\n+ }\n+ case SOLVE: {\n+ MatrixBlock A = MatrixBlock.randOperations(rows, cols, 1.0, -5, 10, \"uniform\", 7);\n+ MatrixBlock b = MatrixBlock.randOperations(cols, 1, 1.0, -1, 1, \"uniform\", 3);\n+ MatrixBlock y = A.aggregateBinaryOperations(A, b, new MatrixBlock(), InstructionUtils.getMatMultOperator(1));\n+ writeInputMatrixWithMTD(\"A\", A, false);\n+ writeInputMatrixWithMTD(\"B\", y, false);\n+ runTest(true, false, null, -1);\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"C\");\n+ MatrixBlock C2 = LibCommonsMath.matrixMatrixOperations(A, b, \"solve\");\n+ TestUtils.compareMatrices(dmlfile, C2, eps);\n+ break;\n+ }\n+ case LU: {\n+ MatrixBlock A = MatrixBlock.randOperations(rows, cols, 1.0, -5, 10, \"uniform\", 7);\n+ writeInputMatrixWithMTD(\"A\", A, false);\n+ runTest(true, false, null, -1);\n+ MatrixBlock[] C = LibCommonsMath.multiReturnOperations(A, \"lu\");\n+ String[] outputs = new String[]{\"C\",\"D\",\"E\"};\n+ for(int i=0; i<outputs.length; i++) {\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(outputs[i]);\n+ TestUtils.compareMatrices(dmlfile, C[i], eps);\n+ }\n+ break;\n+ }\n+ case QR: {\n+ MatrixBlock A = MatrixBlock.randOperations(rows, cols, 1.0, -5, 10, \"uniform\", 7);\n+ writeInputMatrixWithMTD(\"A\", A, false);\n+ runTest(true, false, null, -1);\n+ MatrixBlock[] C = LibCommonsMath.multiReturnOperations(A, \"qr\");\n+ String[] outputs = new String[]{\"C\",\"D\",\"E\"};\n+ for(int i=0; i<outputs.length; i++) {\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(outputs[i]);\n+ TestUtils.compareMatrices(dmlfile, C[i], eps);\n+ }\n+ break;\n+ }\n+ case INVERSE: {\n+ MatrixBlock A = MatrixBlock.randOperations(rows, cols, 1.0, -5, 10, \"uniform\", 7);\n+ writeInputMatrixWithMTD(\"A\", A, false);\n+ runTest(true, false, null, -1);\n+ HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS(\"C\");\n+ MatrixBlock C2 = LibCommonsMath.unaryOperations(A, \"inverse\");\n+ TestUtils.compareMatrices(dmlfile, C2, eps);\n+ break;\n+ }\n+ }\n+ }\n+ finally {\n+ rtplatform = platformOld;\n+ DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld;\n+ OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = oldFlag1;\n+ OptimizerUtils.ALLOW_INTER_PROCEDURAL_ANALYSIS = oldFlag2;\n+ }\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/utils/TestUtils.java", "new_path": "src/test/java/org/apache/sysml/test/utils/TestUtils.java", "diff": "@@ -62,6 +62,7 @@ import org.apache.sysml.runtime.matrix.data.MatrixCell;\nimport org.apache.sysml.runtime.matrix.data.MatrixIndexes;\nimport org.apache.sysml.runtime.matrix.data.OutputInfo;\nimport org.apache.sysml.runtime.matrix.data.MatrixValue.CellIndex;\n+import org.apache.sysml.runtime.util.DataConverter;\nimport org.apache.sysml.runtime.util.UtilFunctions;\nimport org.apache.sysml.test.integration.AutomatedTestBase;\n@@ -693,22 +694,18 @@ public class TestUtils\nassertEquals(expected, actual);\n}\n- /**\n- *\n- * @param m1\n- * @param m2\n- * @param tolerance\n- * @param name1\n- * @param name2\n- * @param ignoreNaN\n- * @return\n- */\npublic static boolean compareMatrices(HashMap<CellIndex, Double> m1, HashMap<CellIndex, Double> m2,\ndouble tolerance, String name1, String name2)\n{\nreturn compareMatrices(m1, m2, tolerance, name1, name2, false);\n}\n+ public static void compareMatrices(HashMap<CellIndex, Double> m1, MatrixBlock m2, double tolerance) {\n+ double[][] ret1 = convertHashMapToDoubleArray(m1);\n+ double[][] ret2 = DataConverter.convertToDoubleMatrix(m2);\n+ compareMatrices(ret1, ret2, m2.getNumRows(), m2.getNumColumns(), tolerance);\n+ }\n+\n/**\n* Compares two matrices given as HashMaps. The matrix containing more nnz\n* is iterated and each cell value compared against the corresponding cell\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/scripts/applications/decomp/ScalableDecomposition.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/scalable_linalg/linalg_decomp.dml\") as decomp\n+\n+A = read($3);\n+\n+if( $1 == 0 ) {\n+ C = decomp::Cholesky(A, $2);\n+}\n+else if( $1 == 1 ) {\n+ [C, D, E] = decomp::LU(A, $2);\n+}\n+else if( $1 == 2 ) {\n+ [C, D] = decomp::QR(A, $2);\n+}\n+else if( $1 == 3 ) {\n+ B = read($4);\n+ C = decomp::Solve(A, B, $2);\n+}\n+else if( $1 == 4 ) {\n+ C = decomp::Inverse(A, $2);\n+}\n+\n+write(C, $5);\n+if( exists(D) )\n+ write(D, $6)\n+if( exists(E) )\n+ write(E, $7)\n" }, { "change_type": "MODIFY", "old_path": "src/test_suites/java/org/apache/sysml/test/integration/applications/ZPackageSuite.java", "new_path": "src/test_suites/java/org/apache/sysml/test/integration/applications/ZPackageSuite.java", "diff": "@@ -27,7 +27,6 @@ import org.junit.runners.Suite;\n* they should not be run in parallel. */\n@RunWith(Suite.class)\[email protected]({\n-\n// .applications.dml package\norg.apache.sysml.test.integration.applications.dml.ApplyTransformDMLTest.class,\norg.apache.sysml.test.integration.applications.dml.ArimaDMLTest.class,\n@@ -45,6 +44,7 @@ import org.junit.runners.Suite;\norg.apache.sysml.test.integration.applications.dml.NaiveBayesDMLTest.class,\norg.apache.sysml.test.integration.applications.dml.NaiveBayesParforDMLTest.class,\norg.apache.sysml.test.integration.applications.dml.PageRankDMLTest.class,\n+ org.apache.sysml.test.integration.applications.dml.ScalableDecompositionTest.class,\norg.apache.sysml.test.integration.applications.dml.WelchTDMLTest.class,\n// .applications.pydml package\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2271] Include scalable decompositions in integration tests
49,738
23.04.2018 11:49:20
25,200
afbedf3bf441e9106f87b907b4e2c6d86e4608cb
[HOTFIX] Fix incorrect meta data in frame converter test
[ { "change_type": "MODIFY", "old_path": "src/test/java/org/apache/sysml/test/integration/functions/frame/FrameConverterTest.java", "new_path": "src/test/java/org/apache/sysml/test/integration/functions/frame/FrameConverterTest.java", "diff": "@@ -324,7 +324,7 @@ public class FrameConverterTest extends AutomatedTestBase\n{\ntry\n{\n- MatrixCharacteristics mcMatrix = new MatrixCharacteristics(rows, schema.length, 1000, 1000, 0);\n+ MatrixCharacteristics mcMatrix = new MatrixCharacteristics(rows, schema.length, 1000, 1000, -1);\nMatrixCharacteristics mcFrame = new MatrixCharacteristics(rows, schema.length, -1, -1, -1);\nMatrixBlock matrixBlock1 = null;\n" } ]
Java
Apache License 2.0
apache/systemds
[HOTFIX] Fix incorrect meta data in frame converter test
49,738
26.04.2018 20:39:24
25,200
18cc576dcad813a059322d9f0bb83208ed0bb646
Performance spark unary aggregates (empty block filter) This patch improves the performance of sparse-safe spark unary aggregate operations such as sum(X) by filtering empty blocks before the actual unary aggregate operations.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/AggregateUnarySPInstruction.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/AggregateUnarySPInstruction.java", "diff": "@@ -34,6 +34,7 @@ import org.apache.sysml.runtime.instructions.InstructionUtils;\nimport org.apache.sysml.runtime.instructions.cp.CPOperand;\nimport org.apache.sysml.runtime.instructions.spark.functions.AggregateDropCorrectionFunction;\nimport org.apache.sysml.runtime.instructions.spark.functions.FilterDiagBlocksFunction;\n+import org.apache.sysml.runtime.instructions.spark.functions.FilterNonEmptyBlocksFunction;\nimport org.apache.sysml.runtime.instructions.spark.utils.RDDAggregateUtils;\nimport org.apache.sysml.runtime.matrix.MatrixCharacteristics;\nimport org.apache.sysml.runtime.matrix.data.MatrixBlock;\n@@ -91,6 +92,9 @@ public class AggregateUnarySPInstruction extends UnarySPInstruction {\n//perform aggregation if necessary and put output into symbol table\nif( _aggtype == SparkAggType.SINGLE_BLOCK )\n{\n+ if( auop.sparseSafe )\n+ out = out.filter(new FilterNonEmptyBlocksFunction());\n+\nJavaRDD<MatrixBlock> out2 = out.map(\nnew RDDUAggFunction2(auop, mc.getRowsPerBlock(), mc.getColsPerBlock()));\nMatrixBlock out3 = RDDAggregateUtils.aggStable(out2, aggop);\n@@ -164,7 +168,7 @@ public class AggregateUnarySPInstruction extends UnarySPInstruction {\n/**\n* Similar to RDDUAggFunction but single output block.\n*/\n- private static class RDDUAggFunction2 implements Function<Tuple2<MatrixIndexes, MatrixBlock>, MatrixBlock>\n+ public static class RDDUAggFunction2 implements Function<Tuple2<MatrixIndexes, MatrixBlock>, MatrixBlock>\n{\nprivate static final long serialVersionUID = 2672082409287856038L;\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2279] Performance spark unary aggregates (empty block filter) This patch improves the performance of sparse-safe spark unary aggregate operations such as sum(X) by filtering empty blocks before the actual unary aggregate operations.
49,738
26.04.2018 20:59:28
25,200
3b359c39029e26cd188fd64f370d00eb102adcf8
Performance spark sumByKey incr block aggregation This patch improves the performance of the very common spark sumByKey primitives as used for many matrix multiplications and other operations with global aggregation. We now avoid the unnecessary creation of dense correction blocks, which greatly reduces GC overhead for ultra-sparse scenarios.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/utils/RDDAggregateUtils.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/utils/RDDAggregateUtils.java", "diff": "@@ -26,13 +26,16 @@ import org.apache.spark.api.java.function.Function2;\nimport org.apache.sysml.lops.PartialAggregate.CorrectionLocationType;\nimport org.apache.sysml.runtime.DMLRuntimeException;\nimport org.apache.sysml.runtime.functionobjects.KahanPlus;\n+import org.apache.sysml.runtime.instructions.InstructionUtils;\nimport org.apache.sysml.runtime.instructions.cp.KahanObject;\n+import org.apache.sysml.runtime.instructions.spark.AggregateUnarySPInstruction.RDDUAggFunction2;\nimport org.apache.sysml.runtime.instructions.spark.data.CorrMatrixBlock;\nimport org.apache.sysml.runtime.instructions.spark.data.RowMatrixBlock;\nimport org.apache.sysml.runtime.matrix.data.MatrixBlock;\nimport org.apache.sysml.runtime.matrix.data.MatrixIndexes;\nimport org.apache.sysml.runtime.matrix.data.OperationsOnMatrixValues;\nimport org.apache.sysml.runtime.matrix.operators.AggregateOperator;\n+import org.apache.sysml.runtime.matrix.operators.AggregateUnaryOperator;\n/**\n* Collection of utility methods for aggregating binary block rdds. As a general\n@@ -83,8 +86,8 @@ public class RDDAggregateUtils\n//stable sum of blocks per key, by passing correction blocks along with aggregates\nJavaPairRDD<MatrixIndexes, CorrMatrixBlock> tmp =\nin.combineByKey( new CreateCorrBlockCombinerFunction(deepCopyCombiner),\n- new MergeSumBlockValueFunction(),\n- new MergeSumBlockCombinerFunction(), numPartitions );\n+ new MergeSumBlockValueFunction(deepCopyCombiner),\n+ new MergeSumBlockCombinerFunction(deepCopyCombiner), numPartitions );\n//strip-off correction blocks from\nJavaPairRDD<MatrixIndexes, MatrixBlock> out =\n@@ -94,13 +97,18 @@ public class RDDAggregateUtils\nreturn out;\n}\n- public static JavaPairRDD<MatrixIndexes, Double> sumCellsByKeyStable( JavaPairRDD<MatrixIndexes, Double> in )\n+\n+ public static JavaPairRDD<MatrixIndexes, Double> sumCellsByKeyStable( JavaPairRDD<MatrixIndexes, Double> in ) {\n+ return sumCellsByKeyStable(in, in.getNumPartitions());\n+ }\n+\n+ public static JavaPairRDD<MatrixIndexes, Double> sumCellsByKeyStable( JavaPairRDD<MatrixIndexes, Double> in, int numParts )\n{\n//stable sum of blocks per key, by passing correction blocks along with aggregates\nJavaPairRDD<MatrixIndexes, KahanObject> tmp =\nin.combineByKey( new CreateCellCombinerFunction(),\nnew MergeSumCellValueFunction(),\n- new MergeSumCellCombinerFunction() );\n+ new MergeSumCellCombinerFunction(), numParts);\n//strip-off correction blocks from\nJavaPairRDD<MatrixIndexes, Double> out =\n@@ -166,6 +174,12 @@ public class RDDAggregateUtils\nreturn out;\n}\n+ public static double max(JavaPairRDD<MatrixIndexes, MatrixBlock> in) {\n+ AggregateUnaryOperator auop = InstructionUtils.parseBasicAggregateUnaryOperator(\"uamax\");\n+ MatrixBlock tmp = aggStable(in.map(new RDDUAggFunction2(auop, -1, -1)), auop.aggOp);\n+ return tmp.quickGetValue(0, 0);\n+ }\n+\n/**\n* Merges disjoint data of all blocks per key.\n*\n@@ -258,6 +272,12 @@ public class RDDAggregateUtils\nprivate AggregateOperator _op = new AggregateOperator(0, KahanPlus.getKahanPlusFnObject(), true, CorrectionLocationType.NONE);\n+ private final boolean _deep;\n+\n+ public MergeSumBlockValueFunction(boolean deep) {\n+ _deep = deep;\n+ }\n+\n@Override\npublic CorrMatrixBlock call(CorrMatrixBlock arg0, MatrixBlock arg1)\nthrows Exception\n@@ -270,12 +290,12 @@ public class RDDAggregateUtils\nMatrixBlock corr = arg0.getCorrection();\n//correction block allocation on demand\n- if( corr == null )\n+ if( corr == null && !arg1.isEmptyBlock(false) )\ncorr = new MatrixBlock(value.getNumRows(), value.getNumColumns(), false);\n//aggregate other input and maintain corrections\n//(existing value and corr are used in place)\n- OperationsOnMatrixValues.incrementalAggregation(value, corr, arg1, _op, false);\n+ OperationsOnMatrixValues.incrementalAggregation(value, corr, arg1, _op, false, _deep);\nreturn arg0.set(value, corr);\n}\n}\n@@ -285,6 +305,11 @@ public class RDDAggregateUtils\nprivate static final long serialVersionUID = 7664941774566119853L;\nprivate AggregateOperator _op = new AggregateOperator(0, KahanPlus.getKahanPlusFnObject(), true, CorrectionLocationType.NONE);\n+ private final boolean _deep;\n+\n+ public MergeSumBlockCombinerFunction(boolean deep) {\n+ _deep = deep;\n+ }\n@Override\npublic CorrMatrixBlock call(CorrMatrixBlock arg0, CorrMatrixBlock arg1)\n@@ -298,12 +323,13 @@ public class RDDAggregateUtils\n//correction block allocation on demand (but use second if exists)\nif( corr == null ) {\ncorr = (arg1.getCorrection()!=null) ? arg1.getCorrection() :\n+ value2.isEmptyBlock(false) || (!_deep && value1.isEmptyBlock(false)) ? null :\nnew MatrixBlock(value1.getNumRows(), value1.getNumColumns(), false);\n}\n//aggregate other input and maintain corrections\n//(existing value and corr are used in place)\n- OperationsOnMatrixValues.incrementalAggregation(value1, corr, value2, _op, false);\n+ OperationsOnMatrixValues.incrementalAggregation(value1, corr, value2, _op, false, _deep);\nreturn arg0.set(value1, corr);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/io/ReaderBinaryBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/io/ReaderBinaryBlock.java", "diff": "@@ -113,7 +113,7 @@ public class ReaderBinaryBlock extends MatrixReader\n//where ultra-sparse deserialization only reuses CSR blocks\nMatrixBlock value = new MatrixBlock(brlen, bclen, sparse);\nif( sparse ) {\n- value.allocateAndResetSparseRowsBlock(true, SparseBlock.Type.CSR);\n+ value.allocateAndResetSparseBlock(true, SparseBlock.Type.CSR);\nvalue.getSparseBlock().allocate(0, brlen*bclen);\n}\nreturn value;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/CM_N_COVCell.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/CM_N_COVCell.java", "diff": "@@ -98,7 +98,7 @@ public class CM_N_COVCell extends MatrixValue implements WritableComparable\n@Override\npublic void incrementalAggregate(AggregateOperator aggOp,\n- MatrixValue correction, MatrixValue newWithCorrection) {\n+ MatrixValue correction, MatrixValue newWithCorrection, boolean deep) {\nthrow new RuntimeException(\"operation not supported for CM_N_COVCell\");\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixAgg.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/LibMatrixAgg.java", "diff": "@@ -122,12 +122,23 @@ public class LibMatrixAgg\n* @param in input matrix\n* @param aggVal current aggregate values (in/out)\n* @param aggCorr current aggregate correction (in/out)\n+ * @param deep deep copy flag\n*/\n- public static void aggregateBinaryMatrix(MatrixBlock in, MatrixBlock aggVal, MatrixBlock aggCorr) {\n+ public static void aggregateBinaryMatrix(MatrixBlock in, MatrixBlock aggVal, MatrixBlock aggCorr, boolean deep) {\n//Timing time = new Timing(true);\n//boolean saggVal = aggVal.sparse, saggCorr = aggCorr.sparse;\n//long naggVal = aggVal.nonZeros, naggCorr = aggCorr.nonZeros;\n+ //common empty block handling\n+ if( in.isEmptyBlock(false) ) {\n+ return;\n+ }\n+ if( !deep && aggVal.isEmptyBlock(false) ) {\n+ //shallow copy without correction allocation\n+ aggVal.copyShallow(in);\n+ return;\n+ }\n+\n//ensure MCSR instead of CSR for update in-place\nif( aggVal.sparse && aggVal.isAllocated() && aggVal.getSparseBlock() instanceof SparseBlockCSR )\naggVal.sparseBlock = SparseBlockFactory.copySparseBlock(SparseBlock.Type.MCSR, aggVal.getSparseBlock(), true);\n@@ -977,9 +988,6 @@ public class LibMatrixAgg\n}\nprivate static void aggregateBinaryMatrixAllDense(MatrixBlock in, MatrixBlock aggVal, MatrixBlock aggCorr) {\n- if( in.denseBlock==null || in.isEmptyBlock(false) )\n- return;\n-\n//allocate output arrays (if required)\naggVal.allocateDenseBlock(); //should always stay in dense\naggCorr.allocateDenseBlock(); //should always stay in dense\n@@ -1011,9 +1019,6 @@ public class LibMatrixAgg\n}\nprivate static void aggregateBinaryMatrixSparseDense(MatrixBlock in, MatrixBlock aggVal, MatrixBlock aggCorr) {\n- if( in.isEmptyBlock(false) )\n- return;\n-\n//allocate output arrays (if required)\naggVal.allocateDenseBlock(); //should always stay in dense\naggCorr.allocateDenseBlock(); //should always stay in dense\n@@ -1055,9 +1060,6 @@ public class LibMatrixAgg\n}\nprivate static void aggregateBinaryMatrixSparseGeneric(MatrixBlock in, MatrixBlock aggVal, MatrixBlock aggCorr) {\n- if( in.isEmptyBlock(false) )\n- return;\n-\nSparseBlock a = in.getSparseBlock();\nKahanObject buffer1 = new KahanObject(0, 0);\n@@ -1095,9 +1097,6 @@ public class LibMatrixAgg\n}\nprivate static void aggregateBinaryMatrixDenseGeneric(MatrixBlock in, MatrixBlock aggVal, MatrixBlock aggCorr) {\n- if( in.denseBlock==null || in.isEmptyBlock(false) )\n- return;\n-\nfinal int m = in.rlen;\nfinal int n = in.clen;\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixCell.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixCell.java", "diff": "@@ -266,7 +266,7 @@ public class MatrixCell extends MatrixValue implements WritableComparable, Seria\n@Override\npublic void incrementalAggregate(AggregateOperator aggOp,\n- MatrixValue correction, MatrixValue newWithCorrection) {\n+ MatrixValue correction, MatrixValue newWithCorrection, boolean deep) {\nthrow new DMLRuntimeException(\"MatrixCell.incrementalAggregate should never be called\");\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixValue.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixValue.java", "diff": "@@ -127,8 +127,11 @@ public abstract class MatrixValue implements WritableComparable\npublic abstract MatrixValue unaryOperations(UnaryOperator op, MatrixValue result);\n- public abstract void incrementalAggregate(AggregateOperator aggOp, MatrixValue correction,\n- MatrixValue newWithCorrection);\n+ public void incrementalAggregate(AggregateOperator aggOp, MatrixValue correction, MatrixValue newWithCorrection) {\n+ incrementalAggregate(aggOp, correction, newWithCorrection, true);\n+ }\n+\n+ public abstract void incrementalAggregate(AggregateOperator aggOp, MatrixValue correction, MatrixValue newWithCorrection, boolean deep);\npublic abstract void incrementalAggregate(AggregateOperator aggOp, MatrixValue newWithCorrection);\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/OperationsOnMatrixValues.java", "diff": "@@ -196,12 +196,18 @@ public class OperationsOnMatrixValues\n}\npublic static void incrementalAggregation(MatrixValue valueAgg, MatrixValue correction, MatrixValue valueAdd,\n- AggregateOperator op, boolean imbededCorrection)\n+ AggregateOperator op, boolean imbededCorrection) {\n+ incrementalAggregation(valueAgg, correction, valueAdd, op, imbededCorrection, true);\n+ }\n+\n+\n+ public static void incrementalAggregation(MatrixValue valueAgg, MatrixValue correction, MatrixValue valueAdd,\n+ AggregateOperator op, boolean imbededCorrection, boolean deep)\n{\nif(op.correctionExists)\n{\nif(!imbededCorrection || op.correctionLocation==CorrectionLocationType.NONE)\n- valueAgg.incrementalAggregate(op, correction, valueAdd);\n+ valueAgg.incrementalAggregate(op, correction, valueAdd, deep);\nelse\nvalueAgg.incrementalAggregate(op, valueAdd);\n}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2281] Performance spark sumByKey incr block aggregation This patch improves the performance of the very common spark sumByKey primitives as used for many matrix multiplications and other operations with global aggregation. We now avoid the unnecessary creation of dense correction blocks, which greatly reduces GC overhead for ultra-sparse scenarios.
49,727
28.04.2018 16:02:37
25,200
945f3ccf9f167ee43c5946b2ea871af5b56a72be
Runtime support for remote parfor broadcast inputs Closes
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/ParForProgramBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/ParForProgramBlock.java", "diff": "@@ -308,6 +308,7 @@ public class ParForProgramBlock extends ForProgramBlock\npublic static final boolean FORCE_CP_ON_REMOTE_MR = true; // compile body to CP if exec type forced to MR\npublic static final boolean LIVEVAR_AWARE_EXPORT = true; // export only read variables according to live variable analysis\npublic static final boolean RESET_RECOMPILATION_FLAGs = true;\n+ public static final boolean ALLOW_BROADCAST_INPUTS = false; // enables to broadcast inputs for remote_spark\npublic static final String PARFOR_FNAME_PREFIX = \"/parfor/\";\npublic static final String PARFOR_MR_TASKS_TMP_FNAME = PARFOR_FNAME_PREFIX + \"%ID%_MR_taskfile\";\n@@ -1042,8 +1043,8 @@ public class ParForProgramBlock extends ForProgramBlock\nexportMatricesToHDFS(ec);\n// Step 3) submit Spark parfor job (no lazy evaluation, since collect on result)\n- //MatrixObject colocatedDPMatrixObj = (_colocatedDPMatrix!=null)? (MatrixObject)ec.getVariable(_colocatedDPMatrix) : null;\n- RemoteParForJobReturn ret = RemoteParForSpark.runJob(_ID, program, clsMap, tasks, ec, _enableCPCaching, _numThreads);\n+ RemoteParForJobReturn ret = RemoteParForSpark.runJob(_ID, program,\n+ clsMap, tasks, ec, _resultVars, _enableCPCaching, _numThreads);\nif( _monitor )\nStatisticMonitor.putPFStat(_ID, Stat.PARFOR_WAIT_EXEC_T, time.stop());\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/ExecutionContext.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/ExecutionContext.java", "diff": "@@ -196,6 +196,11 @@ public class ExecutionContext {\nreturn (MatrixObject) dat;\n}\n+ public boolean isFrameObject(String varname) {\n+ Data dat = getVariable(varname);\n+ return (dat!= null && dat instanceof FrameObject);\n+ }\n+\npublic FrameObject getFrameObject(CPOperand input) {\nreturn getFrameObject(input.getName());\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/context/SparkExecutionContext.java", "diff": "@@ -506,9 +506,47 @@ public class SparkExecutionContext extends ExecutionContext\nreturn rdd;\n}\n+ public Broadcast<CacheBlock> broadcastVariable(CacheableData<CacheBlock> cd) {\n+ long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;\n+ Broadcast<CacheBlock> brBlock = null;\n+\n+ // reuse existing non partitioned broadcast handle\n+ if (cd.getBroadcastHandle() != null && cd.getBroadcastHandle().isNonPartitionedBroadcastValid()) {\n+ brBlock = cd.getBroadcastHandle().getNonPartitionedBroadcast();\n+ }\n+\n+ if (brBlock == null) {\n+ //create new broadcast handle (never created, evicted)\n+ // account for overwritten invalid broadcast (e.g., evicted)\n+ if (cd.getBroadcastHandle() != null)\n+ CacheableData.addBroadcastSize(-cd.getBroadcastHandle().getNonPartitionedBroadcastSize());\n+\n+ // read the matrix block\n+ CacheBlock cb = cd.acquireRead();\n+ cd.release();\n+\n+ // broadcast a non-empty frame whose size is smaller than 2G\n+ if (cb.getExactSerializedSize() > 0 && cb.getExactSerializedSize() <= Integer.MAX_VALUE) {\n+ brBlock = getSparkContext().broadcast(cb);\n+ // create the broadcast handle if the matrix or frame has never been broadcasted\n+ if (cd.getBroadcastHandle() == null) {\n+ cd.setBroadcastHandle(new BroadcastObject<>());\n+ }\n+ cd.getBroadcastHandle().setNonPartitionedBroadcast(brBlock,\n+ OptimizerUtils.estimateSize(cd.getMatrixCharacteristics()));\n+ CacheableData.addBroadcastSize(cd.getBroadcastHandle().getNonPartitionedBroadcastSize());\n+\n+ if (DMLScript.STATISTICS) {\n+ Statistics.accSparkBroadCastTime(System.nanoTime() - t0);\n+ Statistics.incSparkBroadcastCount(1);\n+ }\n+ }\n+ }\n+ return brBlock;\n+ }\n+\n@SuppressWarnings(\"unchecked\")\n- public PartitionedBroadcast<MatrixBlock> getBroadcastForVariable( String varname )\n- {\n+ public PartitionedBroadcast<MatrixBlock> getBroadcastForVariable(String varname) {\n//NOTE: The memory consumption of this method is the in-memory size of the\n//matrix object plus the partitioned size in 1k-1k blocks. Since the call\n//to broadcast happens after the matrix object has been released, the memory\n@@ -524,18 +562,15 @@ public class SparkExecutionContext extends ExecutionContext\nPartitionedBroadcast<MatrixBlock> bret = null;\n//reuse existing broadcast handle\n- if( mo.getBroadcastHandle()!=null\n- && mo.getBroadcastHandle().isValid() )\n- {\n- bret = mo.getBroadcastHandle().getBroadcast();\n+ if (mo.getBroadcastHandle() != null && mo.getBroadcastHandle().isPartitionedBroadcastValid()) {\n+ bret = mo.getBroadcastHandle().getPartitionedBroadcast();\n}\n//create new broadcast handle (never created, evicted)\n- if( bret == null )\n- {\n+ if (bret == null) {\n//account for overwritten invalid broadcast (e.g., evicted)\nif (mo.getBroadcastHandle() != null)\n- CacheableData.addBroadcastSize(-mo.getBroadcastHandle().getSize());\n+ CacheableData.addBroadcastSize(-mo.getBroadcastHandle().getPartitionedBroadcastSize());\n//obtain meta data for matrix\nint brlen = (int) mo.getNumRowsPerBlock();\n@@ -554,18 +589,20 @@ public class SparkExecutionContext extends ExecutionContext\n//create coarse-grained partitioned broadcasts\nif (numParts > 1) {\nArrays.parallelSetAll(ret, i -> createPartitionedBroadcast(pmb, numPerPart, i));\n- }\n- else { //single partition\n+ } else { //single partition\nret[0] = getSparkContext().broadcast(pmb);\nif (!isLocalMaster())\npmb.clearBlocks();\n}\nbret = new PartitionedBroadcast<>(ret, mo.getMatrixCharacteristics());\n- BroadcastObject<MatrixBlock> bchandle = new BroadcastObject<>(bret,\n+ // create the broadcast handle if the matrix or frame has never been broadcasted\n+ if (mo.getBroadcastHandle() == null) {\n+ mo.setBroadcastHandle(new BroadcastObject<MatrixBlock>());\n+ }\n+ mo.getBroadcastHandle().setPartitionedBroadcast(bret,\nOptimizerUtils.estimatePartitionedSizeExactSparsity(mo.getMatrixCharacteristics()));\n- mo.setBroadcastHandle(bchandle);\n- CacheableData.addBroadcastSize(bchandle.getSize());\n+ CacheableData.addBroadcastSize(mo.getBroadcastHandle().getPartitionedBroadcastSize());\n}\nif (DMLScript.STATISTICS) {\n@@ -577,8 +614,7 @@ public class SparkExecutionContext extends ExecutionContext\n}\n@SuppressWarnings(\"unchecked\")\n- public PartitionedBroadcast<FrameBlock> getBroadcastForFrameVariable( String varname)\n- {\n+ public PartitionedBroadcast<FrameBlock> getBroadcastForFrameVariable(String varname) {\nlong t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;\nFrameObject fo = getFrameObject(varname);\n@@ -586,18 +622,15 @@ public class SparkExecutionContext extends ExecutionContext\nPartitionedBroadcast<FrameBlock> bret = null;\n//reuse existing broadcast handle\n- if( fo.getBroadcastHandle()!=null\n- && fo.getBroadcastHandle().isValid() )\n- {\n- bret = fo.getBroadcastHandle().getBroadcast();\n+ if (fo.getBroadcastHandle() != null && fo.getBroadcastHandle().isPartitionedBroadcastValid()) {\n+ bret = fo.getBroadcastHandle().getPartitionedBroadcast();\n}\n//create new broadcast handle (never created, evicted)\n- if( bret == null )\n- {\n+ if (bret == null) {\n//account for overwritten invalid broadcast (e.g., evicted)\nif (fo.getBroadcastHandle() != null)\n- CacheableData.addBroadcastSize(-fo.getBroadcastHandle().getSize());\n+ CacheableData.addBroadcastSize(-fo.getBroadcastHandle().getPartitionedBroadcastSize());\n//obtain meta data for frame\nint bclen = (int) fo.getNumColumns();\n@@ -616,18 +649,19 @@ public class SparkExecutionContext extends ExecutionContext\n//create coarse-grained partitioned broadcasts\nif (numParts > 1) {\nArrays.parallelSetAll(ret, i -> createPartitionedBroadcast(pmb, numPerPart, i));\n- }\n- else { //single partition\n+ } else { //single partition\nret[0] = getSparkContext().broadcast(pmb);\nif (!isLocalMaster())\npmb.clearBlocks();\n}\nbret = new PartitionedBroadcast<>(ret, fo.getMatrixCharacteristics());\n- BroadcastObject<FrameBlock> bchandle = new BroadcastObject<>(bret,\n+ if (fo.getBroadcastHandle() == null) {\n+ fo.setBroadcastHandle(new BroadcastObject<FrameBlock>());\n+ }\n+ fo.getBroadcastHandle().setPartitionedBroadcast(bret,\nOptimizerUtils.estimatePartitionedSizeExactSparsity(fo.getMatrixCharacteristics()));\n- fo.setBroadcastHandle(bchandle);\n- CacheableData.addBroadcastSize(bchandle.getSize());\n+ CacheableData.addBroadcastSize(fo.getBroadcastHandle().getPartitionedBroadcastSize());\n}\nif (DMLScript.STATISTICS) {\n@@ -1124,11 +1158,20 @@ public class SparkExecutionContext extends ExecutionContext\n_parRDDs.deregisterRDD(rddID);\n}\nelse if( lob instanceof BroadcastObject ) {\n- PartitionedBroadcast pbm = ((BroadcastObject)lob).getBroadcast();\n- if( pbm != null ) //robustness for evictions\n- for( Broadcast<PartitionedBlock> bc : pbm.getBroadcasts() )\n+ BroadcastObject bob = (BroadcastObject) lob;\n+ // clean the partitioned broadcast\n+ if (bob.isPartitionedBroadcastValid()) {\n+ PartitionedBroadcast pbm = bob.getPartitionedBroadcast();\n+ if( pbm != null ) //robustness evictions\n+ pbm.destroy();\n+ }\n+ // clean the non-partitioned broadcast\n+ if (((BroadcastObject) lob).isNonPartitionedBroadcastValid()) {\n+ Broadcast<CacheableData> bc = bob.getNonPartitionedBroadcast();\n+ if( bc != null ) //robustness evictions\ncleanupBroadcastVariable(bc);\n- CacheableData.addBroadcastSize(-((BroadcastObject)lob).getSize());\n+ }\n+ CacheableData.addBroadcastSize(-bob.getNonPartitionedBroadcastSize());\n}\n//recursively process lineage children\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/parfor/CachedReuseVariables.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/parfor/CachedReuseVariables.java", "diff": "@@ -23,8 +23,15 @@ import java.lang.ref.SoftReference;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\n+import java.util.Map;\n+import java.util.Map.Entry;\n+import org.apache.spark.broadcast.Broadcast;\nimport org.apache.sysml.runtime.controlprogram.LocalVariableMap;\n+import org.apache.sysml.runtime.controlprogram.ParForProgramBlock;\n+import org.apache.sysml.runtime.controlprogram.caching.CacheBlock;\n+import org.apache.sysml.runtime.controlprogram.caching.CacheableData;\n+import org.apache.sysml.runtime.instructions.cp.Data;\npublic class CachedReuseVariables\n{\n@@ -34,10 +41,21 @@ public class CachedReuseVariables\n_data = new HashMap<>();\n}\n- public synchronized void reuseVariables(long pfid, LocalVariableMap vars, Collection<String> blacklist) {\n+ public synchronized boolean containsVars(long pfid) {\n+ return _data.containsKey(pfid);\n+ }\n+\n+ @SuppressWarnings(\"unused\")\n+ public synchronized void reuseVariables(long pfid, LocalVariableMap vars, Collection<String> blacklist, Map<String, Broadcast<CacheBlock>> _brInputs) {\n+\n+ //fetch the broadcast variables\n+ if (ParForProgramBlock.ALLOW_BROADCAST_INPUTS && !containsVars(pfid)) {\n+ loadBroadcastVariables(vars, _brInputs);\n+ }\n+\n//check for existing reuse map\nLocalVariableMap tmp = null;\n- if( _data.containsKey(pfid) )\n+ if( containsVars(pfid) )\ntmp = _data.get(pfid).get();\n//build reuse map if not created yet or evicted\n@@ -57,4 +75,15 @@ public class CachedReuseVariables\npublic synchronized void clearVariables(long pfid) {\n_data.remove(pfid);\n}\n+\n+ @SuppressWarnings(\"unchecked\")\n+ private static void loadBroadcastVariables(LocalVariableMap variables, Map<String, Broadcast<CacheBlock>> brInputs) {\n+ for( Entry<String, Broadcast<CacheBlock>> e : brInputs.entrySet() ) {\n+ Data d = variables.get(e.getKey());\n+ CacheableData<CacheBlock> cdcb = (CacheableData<CacheBlock>) d;\n+ cdcb.acquireModify(e.getValue().getValue());\n+ cdcb.setEmptyStatus(); // avoid eviction\n+ cdcb.refreshMetaData();\n+ }\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/parfor/RemoteParForSpark.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/parfor/RemoteParForSpark.java", "diff": "package org.apache.sysml.runtime.controlprogram.parfor;\n+import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\n+import java.util.Map;\n+import java.util.Set;\n+import java.util.stream.Collectors;\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\nimport org.apache.spark.api.java.JavaSparkContext;\n+import org.apache.spark.broadcast.Broadcast;\nimport org.apache.spark.util.LongAccumulator;\n+import org.apache.sysml.parser.ParForStatementBlock;\n+import org.apache.sysml.parser.ParForStatementBlock.ResultVar;\n+import org.apache.sysml.runtime.controlprogram.ParForProgramBlock;\n+import org.apache.sysml.runtime.controlprogram.caching.CacheBlock;\n+import org.apache.sysml.runtime.controlprogram.caching.CacheableData;\n+import org.apache.sysml.runtime.controlprogram.caching.MatrixObject;\n+import org.apache.sysml.runtime.instructions.cp.Data;\n+import org.apache.sysml.runtime.instructions.cp.ScalarObject;\nimport scala.Tuple2;\nimport org.apache.sysml.api.DMLScript;\n@@ -47,7 +60,6 @@ import org.apache.sysml.utils.Statistics;\n* pre-aggregation by overwriting partial task results with pre-paggregated results from subsequent\n* iterations)\n*\n- * TODO broadcast variables if possible\n* TODO reducebykey on variable names\n*/\npublic class RemoteParForSpark\n@@ -58,7 +70,7 @@ public class RemoteParForSpark\nprivate static final IDSequence _jobID = new IDSequence();\npublic static RemoteParForJobReturn runJob(long pfid, String prog, HashMap<String, byte[]> clsMap,\n- List<Task> tasks, ExecutionContext ec, boolean cpCaching, int numMappers)\n+ List<Task> tasks, ExecutionContext ec, ArrayList<ResultVar> resultVars, boolean cpCaching, int numMappers)\n{\nString jobname = \"ParFor-ESP\";\nlong t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;\n@@ -75,10 +87,16 @@ public class RemoteParForSpark\nif( InfrastructureAnalyzer.isLocalMode() )\nRemoteParForSparkWorker.cleanupCachedVariables(jobid);\n+ // broadcast the inputs except the result variables\n+ Map<String, Broadcast<CacheBlock>> brInputs = null;\n+ if (ParForProgramBlock.ALLOW_BROADCAST_INPUTS) {\n+ brInputs = broadcastInputs(sec, resultVars);\n+ }\n+\n//run remote_spark parfor job\n//(w/o lazy evaluation to fit existing parfor framework, e.g., result merge)\nList<Tuple2<Long,String>> out = sc.parallelize(tasks, tasks.size()) //create rdd of parfor tasks\n- .flatMapToPair(new RemoteParForSparkWorker(jobid, prog, clsMap, cpCaching, aTasks, aIters))\n+ .flatMapToPair(new RemoteParForSparkWorker(jobid, prog, clsMap, cpCaching, aTasks, aIters, brInputs))\n.collect(); //execute and get output handles\n//de-serialize results\n@@ -97,4 +115,25 @@ public class RemoteParForSpark\nreturn ret;\n}\n+\n+ @SuppressWarnings(\"unchecked\")\n+ private static Map<String, Broadcast<CacheBlock>> broadcastInputs(SparkExecutionContext sec, ArrayList<ParForStatementBlock.ResultVar> resultVars) {\n+ LocalVariableMap inputs = sec.getVariables();\n+ // exclude the result variables\n+ // TODO use optimizer-picked list of amenable objects (e.g., size constraints)\n+ Set<String> retVars = resultVars.stream()\n+ .map(v -> v._name).collect(Collectors.toSet());\n+ Set<String> brVars = inputs.keySet().stream()\n+ .filter(v -> !retVars.contains(v)).collect(Collectors.toSet());\n+\n+ // construct broadcast objects\n+ Map<String, Broadcast<CacheBlock>> result = new HashMap<>();\n+ for (String key : brVars) {\n+ Data var = sec.getVariable(key);\n+ if ((var instanceof ScalarObject) || (var instanceof MatrixObject && ((MatrixObject) var).isPartitioned()))\n+ continue;\n+ result.put(key, sec.broadcastVariable((CacheableData<CacheBlock>) var));\n+ }\n+ return result;\n+ }\n}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/controlprogram/parfor/RemoteParForSparkWorker.java", "new_path": "src/main/java/org/apache/sysml/runtime/controlprogram/parfor/RemoteParForSparkWorker.java", "diff": "@@ -23,13 +23,16 @@ import java.io.IOException;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.Iterator;\n+import java.util.Map;\nimport java.util.Map.Entry;\nimport java.util.stream.Collectors;\nimport org.apache.spark.TaskContext;\nimport org.apache.spark.api.java.function.PairFlatMapFunction;\n+import org.apache.spark.broadcast.Broadcast;\nimport org.apache.spark.util.LongAccumulator;\nimport org.apache.sysml.runtime.codegen.CodegenUtils;\n+import org.apache.sysml.runtime.controlprogram.caching.CacheBlock;\nimport org.apache.sysml.runtime.controlprogram.caching.CacheableData;\nimport org.apache.sysml.runtime.controlprogram.parfor.stat.InfrastructureAnalyzer;\nimport org.apache.sysml.runtime.controlprogram.parfor.util.IDHandler;\n@@ -53,7 +56,9 @@ public class RemoteParForSparkWorker extends ParWorker implements PairFlatMapFun\nprivate final LongAccumulator _aTasks;\nprivate final LongAccumulator _aIters;\n- public RemoteParForSparkWorker(long jobid, String program, HashMap<String, byte[]> clsMap, boolean cpCaching, LongAccumulator atasks, LongAccumulator aiters) {\n+ private final Map<String, Broadcast<CacheBlock>> _brInputs;\n+\n+ public RemoteParForSparkWorker(long jobid, String program, HashMap<String, byte[]> clsMap, boolean cpCaching, LongAccumulator atasks, LongAccumulator aiters, Map<String, Broadcast<CacheBlock>> brInputs) {\n_jobid = jobid;\n_prog = program;\n_clsMap = clsMap;\n@@ -62,6 +67,7 @@ public class RemoteParForSparkWorker extends ParWorker implements PairFlatMapFun\n//setup spark accumulators\n_aTasks = atasks;\n_aIters = aiters;\n+ _brInputs = brInputs;\n}\n@Override\n@@ -108,7 +114,7 @@ public class RemoteParForSparkWorker extends ParWorker implements PairFlatMapFun\n_ec.pinVariables(_ec.getVarList()); //avoid cleanup of shared inputs\nCollection<String> blacklist = UtilFunctions.asSet(_resultVars.stream()\n.map(v -> v._name).collect(Collectors.toList()), _ec.getVarListPartitioned());\n- reuseVars.reuseVariables(_jobid, _ec.getVariables(), blacklist);\n+ reuseVars.reuseVariables(_jobid, _ec.getVariables(), blacklist, _brInputs);\n//init and register-cleanup of buffer pool (in parfor spark, multiple tasks might\n//share the process-local, i.e., per executor, buffer pool; hence we synchronize\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/data/BroadcastObject.java", "new_path": "src/main/java/org/apache/sysml/runtime/instructions/spark/data/BroadcastObject.java", "diff": "@@ -24,31 +24,60 @@ import java.lang.ref.SoftReference;\nimport org.apache.spark.broadcast.Broadcast;\nimport org.apache.sysml.runtime.controlprogram.caching.CacheBlock;\n-public class BroadcastObject<T extends CacheBlock> extends LineageObject\n-{\n+public class BroadcastObject<T extends CacheBlock> extends LineageObject {\n//soft reference storage for graceful cleanup in case of memory pressure\n- protected final SoftReference<PartitionedBroadcast<T>> _bcHandle;\n- private final long _size;\n+ private SoftReference<PartitionedBroadcast<T>> _pbcRef; // partitioned broadcast object reference\n+ private SoftReference<Broadcast<T>> _npbcRef; // non partitioned broadcast object reference\n- public BroadcastObject( PartitionedBroadcast<T> bvar, long size ) {\n+ private long _pbcSize; // partitioned broadcast size\n+ private long _npbcSize; // non-partitioned broadcast size\n+\n+ public BroadcastObject() {\nsuper();\n- _bcHandle = new SoftReference<>(bvar);\n- _size = size;\n+ }\n+\n+ public void setNonPartitionedBroadcast(Broadcast<T> bvar, long size) {\n+ _npbcRef = new SoftReference<>(bvar);\n+ _npbcSize = size;\n+ }\n+\n+ public void setPartitionedBroadcast(PartitionedBroadcast<T> bvar, long size) {\n+ _pbcRef = new SoftReference<>(bvar);\n+ _pbcSize = size;\n}\n@SuppressWarnings(\"rawtypes\")\n- public PartitionedBroadcast getBroadcast() {\n- return _bcHandle.get();\n+ public PartitionedBroadcast getPartitionedBroadcast() {\n+ return _pbcRef.get();\n+ }\n+\n+ public Broadcast<T> getNonPartitionedBroadcast() {\n+ return _npbcRef.get();\n+ }\n+\n+ public long getPartitionedBroadcastSize() {\n+ return _pbcSize;\n+ }\n+\n+ public long getNonPartitionedBroadcastSize() {\n+ return _npbcSize;\n+ }\n+\n+ public boolean isPartitionedBroadcastValid() {\n+ return _pbcRef != null && checkPartitionedBroadcastValid();\n+ }\n+\n+ public boolean isNonPartitionedBroadcastValid() {\n+ return _npbcRef != null && checkNonPartitionedBroadcastValid();\n}\n- public long getSize() {\n- return _size;\n+ private boolean checkNonPartitionedBroadcastValid() {\n+ return _npbcRef.get() != null;\n}\n- public boolean isValid()\n- {\n+ private boolean checkPartitionedBroadcastValid() {\n//check for evicted soft reference\n- PartitionedBroadcast<T> pbm = _bcHandle.get();\n+ PartitionedBroadcast<T> pbm = _pbcRef.get();\nif (pbm == null)\nreturn false;\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-1313] Runtime support for remote parfor broadcast inputs Closes #759.
49,738
28.04.2018 23:52:52
25,200
db35d99d83c691b5678cccbbf7846cf0ef2bf240
[SYSTEMML-2286,2287] New sparsity estimation framework, basic estims This patch introduces a new matrix multiply estimation framework along with the two existing basic estimators (average and worst-case) as well as some tests where the estimator need to produce exact results.
[ { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/hops/OptimizerUtils.java", "new_path": "src/main/java/org/apache/sysml/hops/OptimizerUtils.java", "diff": "@@ -984,7 +984,7 @@ public class OptimizerUtils\nreturn Math.min(1, nnz1/m) * Math.min(1, nnz2/n);\n}\nelse\n- return (1 - Math.pow(1-sp1*sp2, k) );\n+ return 1 - Math.pow(1-sp1*sp2, k);\n}\npublic static double getLeftIndexingSparsity( long rlen1, long clen1, long nnz1, long rlen2, long clen2, long nnz2 )\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysml/hops/estim/EstimatorBasicAvg.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.sysml.hops.estim;\n+\n+import org.apache.sysml.hops.OptimizerUtils;\n+import org.apache.sysml.runtime.matrix.MatrixCharacteristics;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\n+\n+/**\n+ * Basic average case estimator for matrix sparsity:\n+ * sp = 1 - Math.pow(1-sp1*sp2, k)\n+ */\n+public class EstimatorBasicAvg extends SparsityEstimator\n+{\n+ @Override\n+ public double estim(MMNode root) {\n+ double sp1 = !root.getLeft().isLeaf() ? estim(root.getLeft()) :\n+ OptimizerUtils.getSparsity(root.getLeft().getMatrixCharacteristics());\n+ double sp2 = !root.getRight().isLeaf() ? estim(root.getRight()) :\n+ OptimizerUtils.getSparsity(root.getRight().getMatrixCharacteristics());\n+ return estimIntern(sp1, sp2, root.getRows(), root.getLeft().getCols(), root.getCols());\n+ }\n+\n+ @Override\n+ public double estim(MatrixBlock m1, MatrixBlock m2) {\n+ return estim(m1.getMatrixCharacteristics(), m2.getMatrixCharacteristics());\n+ }\n+\n+ @Override\n+ public double estim(MatrixCharacteristics mc1, MatrixCharacteristics mc2) {\n+ return estimIntern(\n+ OptimizerUtils.getSparsity(mc1), OptimizerUtils.getSparsity(mc2),\n+ mc1.getRows(), mc1.getCols(), mc2.getCols());\n+ }\n+\n+ private double estimIntern(double sp1, double sp2, long m, long k, long n) {\n+ return OptimizerUtils.getMatMultSparsity(sp1, sp2, m, k, n, false);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysml/hops/estim/EstimatorBasicWorst.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.sysml.hops.estim;\n+\n+import org.apache.sysml.hops.OptimizerUtils;\n+import org.apache.sysml.runtime.matrix.MatrixCharacteristics;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\n+\n+/**\n+ * Basic average case estimator for matrix sparsity:\n+ * sp = Math.min(1, sp1 * k) * Math.min(1, sp2 * k).\n+ *\n+ * Note: for outer-products (i.e., k=1) this worst-case\n+ * estimate is equivalent to the average case estimate and\n+ * the exact output sparsity.\n+ */\n+public class EstimatorBasicWorst extends SparsityEstimator\n+{\n+ @Override\n+ public double estim(MMNode root) {\n+ double sp1 = !root.getLeft().isLeaf() ? estim(root.getLeft()) :\n+ OptimizerUtils.getSparsity(root.getLeft().getMatrixCharacteristics());\n+ double sp2 = !root.getRight().isLeaf() ? estim(root.getRight()) :\n+ OptimizerUtils.getSparsity(root.getRight().getMatrixCharacteristics());\n+ return estimIntern(sp1, sp2, root.getRows(), root.getLeft().getCols(), root.getCols());\n+ }\n+\n+ @Override\n+ public double estim(MatrixBlock m1, MatrixBlock m2) {\n+ return estim(m1.getMatrixCharacteristics(), m2.getMatrixCharacteristics());\n+ }\n+\n+ @Override\n+ public double estim(MatrixCharacteristics mc1, MatrixCharacteristics mc2) {\n+ return estimIntern(\n+ OptimizerUtils.getSparsity(mc1), OptimizerUtils.getSparsity(mc2),\n+ mc1.getRows(), mc1.getCols(), mc2.getCols());\n+ }\n+\n+ private double estimIntern(double sp1, double sp2, long m, long k, long n) {\n+ return OptimizerUtils.getMatMultSparsity(sp1, sp2, m, k, n, true);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysml/hops/estim/MMNode.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.sysml.hops.estim;\n+\n+import org.apache.sysml.runtime.matrix.MatrixCharacteristics;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\n+\n+/**\n+ * Helper class to represent matrix multiply operators in a DAG\n+ * along with references to its abstract data handles.\n+ */\n+public class MMNode\n+{\n+ private final MMNode _m1;\n+ private final MMNode _m2;\n+ private final MatrixBlock _data;\n+ private final MatrixCharacteristics _mc;\n+\n+ public MMNode(MMNode left, MMNode right) {\n+ _m1 = left;\n+ _m2 = right;\n+ _data = null;\n+ _mc = isLeaf() ? _data.getMatrixCharacteristics() :\n+ new MatrixCharacteristics(_data.getNumRows(),\n+ _data.getNumColumns(), -1, -1);\n+ }\n+\n+ public long getRows() {\n+ return _mc.getRows();\n+ }\n+\n+ public long getCols() {\n+ return _mc.getCols();\n+ }\n+\n+ public MatrixCharacteristics getMatrixCharacteristics() {\n+ return _mc;\n+ }\n+\n+ public MMNode getLeft() {\n+ return _m1;\n+ }\n+\n+ public MMNode getRight() {\n+ return _m2;\n+ }\n+\n+ public boolean isLeaf() {\n+ return _data != null;\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/main/java/org/apache/sysml/hops/estim/SparsityEstimator.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.sysml.hops.estim;\n+\n+import org.apache.sysml.runtime.matrix.MatrixCharacteristics;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\n+\n+public abstract class SparsityEstimator\n+{\n+ /**\n+ * Estimates the output sparsity of a DAG of matrix multiplications\n+ * for the given operator graph of a single root node.\n+ *\n+ * @param root\n+ * @return\n+ */\n+ public abstract double estim(MMNode root);\n+\n+ /**\n+ * Estimates the output sparsity of a single matrix multiplication\n+ * for the two given matrices.\n+ *\n+ * @param m1 left-hand-side operand\n+ * @param m2 right-hand-side operand\n+ * @return sparsity\n+ */\n+ public abstract double estim(MatrixBlock m1, MatrixBlock m2);\n+\n+ /**\n+ * Estimates the output sparsity of a single matrix multiplication\n+ * for the two given matrices represented by meta data only.\n+ *\n+ * @param mc1 left-hand-side operand\n+ * @param mc2 right-hand-side operand\n+ * @return sparsity\n+ */\n+ public abstract double estim(MatrixCharacteristics mc1, MatrixCharacteristics mc2);\n+\n+}\n" }, { "change_type": "MODIFY", "old_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "new_path": "src/main/java/org/apache/sysml/runtime/matrix/data/MatrixBlock.java", "diff": "@@ -463,6 +463,10 @@ public class MatrixBlock extends MatrixValue implements CacheBlock, Externalizab\nreturn OptimizerUtils.getSparsity(rlen, clen, nonZeros);\n}\n+ public MatrixCharacteristics getMatrixCharacteristics() {\n+ return new MatrixCharacteristics(rlen, clen, -1, -1, nonZeros);\n+ }\n+\npublic boolean isVector() {\nreturn (rlen == 1 || clen == 1);\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test/java/org/apache/sysml/test/integration/functions/estim/OuterProductTest.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.sysml.test.integration.functions.estim;\n+\n+import org.junit.Test;\n+import org.apache.sysml.hops.estim.EstimatorBasicAvg;\n+import org.apache.sysml.hops.estim.EstimatorBasicWorst;\n+import org.apache.sysml.hops.estim.SparsityEstimator;\n+import org.apache.sysml.runtime.instructions.InstructionUtils;\n+import org.apache.sysml.runtime.matrix.data.MatrixBlock;\n+import org.apache.sysml.test.integration.AutomatedTestBase;\n+import org.apache.sysml.test.utils.TestUtils;\n+\n+/**\n+ * This is a basic sanity check for all estimator, which need\n+ * to compute the exact sparsity for the special case of outer products.\n+ */\n+public class OuterProductTest extends AutomatedTestBase\n+{\n+ private final static int m = 1154;\n+ private final static int k = 1;\n+ private final static int n = 900;\n+ private final static double[] case1 = new double[]{0.1, 0.7};\n+ private final static double[] case2 = new double[]{0.6, 0.7};\n+\n+ @Override\n+ public void setUp() {\n+ //do nothing\n+ }\n+\n+ @Test\n+ public void testBasicAvgCase1() {\n+ runSparsityEstimateTest(new EstimatorBasicAvg(), m, n, k, case1);\n+ }\n+\n+ @Test\n+ public void testBasicAvgCase2() {\n+ runSparsityEstimateTest(new EstimatorBasicAvg(), m, n, k, case2);\n+ }\n+\n+ @Test\n+ public void testBasicWorstCase1() {\n+ runSparsityEstimateTest(new EstimatorBasicWorst(), m, n, k, case1);\n+ }\n+\n+ @Test\n+ public void testBasicWorstCase2() {\n+ runSparsityEstimateTest(new EstimatorBasicWorst(), m, n, k, case2);\n+ }\n+\n+ private void runSparsityEstimateTest(SparsityEstimator estim, int m, int k, int n, double[] sp) {\n+ MatrixBlock m1 = MatrixBlock.randOperations(m, k, sp[0], 1, 1, \"uniform\", 3);\n+ MatrixBlock m2 = MatrixBlock.randOperations(k, n, sp[1], 1, 1, \"uniform\", 3);\n+ MatrixBlock m3 = m1.aggregateBinaryOperations(m1, m2,\n+ new MatrixBlock(), InstructionUtils.getMatMultOperator(1));\n+\n+ //compare estimated and real sparsity\n+ double est = estim.estim(m1, m2);\n+ TestUtils.compareScalars(est, m3.getSparsity(), 1e-16);\n+ }\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "src/test_suites/java/org/apache/sysml/test/integration/functions/estim/ZPackageSuite.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.sysml.test.integration.functions.estim;\n+\n+import org.junit.runner.RunWith;\n+import org.junit.runners.Suite;\n+\n+/** Group together the tests in this package into a single suite so that the Maven build\n+ * won't run two of them at once. */\n+@RunWith(Suite.class)\[email protected]({\n+ OuterProductTest.class,\n+})\n+\n+\n+/** This class is just a holder for the above JUnit annotations. */\n+public class ZPackageSuite {\n+\n+}\n" } ]
Java
Apache License 2.0
apache/systemds
[SYSTEMML-2286,2287] New sparsity estimation framework, basic estims This patch introduces a new matrix multiply estimation framework along with the two existing basic estimators (average and worst-case) as well as some tests where the estimator need to produce exact results.