Beispiel #1
0
  @Override
  protected ExecType optFindExecType() throws HopsException {

    checkAndSetForcedPlatform();

    ExecType REMOTE = OptimizerUtils.isSparkExecutionMode() ? ExecType.SPARK : ExecType.MR;

    if (_etypeForced != null) {
      _etype = _etypeForced;
    } else {
      if (OptimizerUtils.isMemoryBasedOptLevel()) {
        _etype = findExecTypeByMemEstimate();
      } else if (getInput().get(0).areDimsBelowThreshold()) {
        _etype = ExecType.CP;
      } else {
        _etype = REMOTE;
      }

      // check for valid CP dimensions and matrix size
      checkAndSetInvalidCPDimsAndSize();
    }

    // mark for recompile (forever)
    if (OptimizerUtils.ALLOW_DYN_RECOMPILATION && !dimsKnown(true) && _etype == REMOTE)
      setRequiresRecompile();

    return _etype;
  }
Beispiel #2
0
  @Override
  protected ExecType optFindExecType() throws HopsException {
    checkAndSetForcedPlatform();

    ExecType REMOTE = OptimizerUtils.isSparkExecutionMode() ? ExecType.SPARK : ExecType.MR;

    if (_etypeForced != null) {
      _etype = _etypeForced;
    } else {
      if (OptimizerUtils.isMemoryBasedOptLevel()) {
        _etype = findExecTypeByMemEstimate();
      }
      // Choose CP, if the input dimensions are below threshold or if the input is a vector
      // Also, matrix inverse is currently implemented only in CP (through commons math)
      else if (getInput().get(0).areDimsBelowThreshold()
          || getInput().get(0).isVector()
          || isInMemoryOperation()) {
        _etype = ExecType.CP;
      } else {
        _etype = REMOTE;
      }

      // check for valid CP dimensions and matrix size
      checkAndSetInvalidCPDimsAndSize();
    }

    // mark for recompile (forever)
    if (OptimizerUtils.ALLOW_DYN_RECOMPILATION && !dimsKnown(true) && _etype == REMOTE)
      setRequiresRecompile();

    if (_op == OpOp1.PRINT || _op == OpOp1.STOP || _op == OpOp1.INVERSE) _etype = ExecType.CP;

    return _etype;
  }
  @Override
  protected ExecType optFindExecType() throws HopsException {
    checkAndSetForcedPlatform();

    ExecType REMOTE = OptimizerUtils.isSparkExecutionMode() ? ExecType.SPARK : ExecType.MR;

    if (_etypeForced != null) {
      _etype = _etypeForced;
    } else {
      if (OptimizerUtils.isMemoryBasedOptLevel()) {
        _etype = findExecTypeByMemEstimate();
      }
      // Choose CP, if the input dimensions are below threshold or if the input is a vector
      // Also, matrix inverse is currently implemented only in CP (through commons math)
      else if (getInput().get(0).areDimsBelowThreshold()
          || getInput().get(0).isVector()
          || isInMemoryOperation()) {
        _etype = ExecType.CP;
      } else {
        _etype = REMOTE;
      }

      // check for valid CP dimensions and matrix size
      checkAndSetInvalidCPDimsAndSize();
    }

    // spark-specific decision refinement (execute unary w/ spark input and
    // single parent also in spark because it's likely cheap and reduces intermediates)
    if (_etype == ExecType.CP
        && _etypeForced != ExecType.CP
        && getInput().get(0).optFindExecType() == ExecType.SPARK
        && getDataType().isMatrix()
        && !isCumulativeUnaryOperation()
        && !isCastUnaryOperation()
        && _op != OpOp1.MEDIAN
        && _op != OpOp1.IQM
        && !(getInput().get(0) instanceof DataOp) // input is not checkpoint
        && getInput().get(0).getParent().size() == 1) // unary is only parent
    {
      // pull unary operation into spark
      _etype = ExecType.SPARK;
    }

    // mark for recompile (forever)
    if (ConfigurationManager.isDynamicRecompilation() && !dimsKnown(true) && _etype == REMOTE)
      setRequiresRecompile();

    // ensure cp exec type for single-node operations
    if (_op == OpOp1.PRINT
        || _op == OpOp1.STOP
        || _op == OpOp1.INVERSE
        || _op == OpOp1.EIGEN
        || _op == OpOp1.CHOLESKY) {
      _etype = ExecType.CP;
    }

    return _etype;
  }
  @Override
  protected double computeIntermediateMemEstimate(long dim1, long dim2, long nnz) {
    // default: no additional memory required
    double val = 0;

    double sparsity = OptimizerUtils.getSparsity(dim1, dim2, nnz);

    switch (_op) // see MatrixAggLib for runtime operations
    {
      case MAX:
      case MIN:
        // worst-case: column-wise, sparse (temp int count arrays)
        if (_direction == Direction.Col) val = dim2 * OptimizerUtils.INT_SIZE;
        break;
      case SUM:
      case SUM_SQ:
        // worst-case correction LASTROW / LASTCOLUMN
        if (_direction == Direction.Col) // (potentially sparse)
        val = OptimizerUtils.estimateSizeExactSparsity(1, dim2, sparsity);
        else if (_direction == Direction.Row) // (always dense)
        val = OptimizerUtils.estimateSizeExactSparsity(dim1, 1, 1.0);
        break;
      case MEAN:
        // worst-case correction LASTTWOROWS / LASTTWOCOLUMNS
        if (_direction == Direction.Col) // (potentially sparse)
        val = OptimizerUtils.estimateSizeExactSparsity(2, dim2, sparsity);
        else if (_direction == Direction.Row) // (always dense)
        val = OptimizerUtils.estimateSizeExactSparsity(dim1, 2, 1.0);
        break;
      case VAR:
        // worst-case correction LASTFOURROWS / LASTFOURCOLUMNS
        if (_direction == Direction.Col) // (potentially sparse)
        val = OptimizerUtils.estimateSizeExactSparsity(4, dim2, sparsity);
        else if (_direction == Direction.Row) // (always dense)
        val = OptimizerUtils.estimateSizeExactSparsity(dim1, 4, 1.0);
        break;
      case MAXINDEX:
      case MININDEX:
        Hop hop = getInput().get(0);
        if (isUnaryAggregateOuterCPRewriteApplicable())
          val = 3 * OptimizerUtils.estimateSizeExactSparsity(1, hop._dim2, 1.0);
        else
          // worst-case correction LASTCOLUMN
          val = OptimizerUtils.estimateSizeExactSparsity(dim1, 1, 1.0);
        break;
      default:
        // no intermediate memory consumption
        val = 0;
    }

    return val;
  }
  @Override
  protected ExecType optFindExecType() throws HopsException {

    checkAndSetForcedPlatform();

    ExecType REMOTE = OptimizerUtils.isSparkExecutionMode() ? ExecType.SPARK : ExecType.MR;

    // forced / memory-based / threshold-based decision
    if (_etypeForced != null) {
      _etype = _etypeForced;
    } else {
      if (OptimizerUtils.isMemoryBasedOptLevel()) {
        _etype = findExecTypeByMemEstimate();
      }
      // Choose CP, if the input dimensions are below threshold or if the input is a vector
      else if (getInput().get(0).areDimsBelowThreshold() || getInput().get(0).isVector()) {
        _etype = ExecType.CP;
      } else {
        _etype = REMOTE;
      }

      // check for valid CP dimensions and matrix size
      checkAndSetInvalidCPDimsAndSize();
    }

    // spark-specific decision refinement (execute unary aggregate w/ spark input and
    // single parent also in spark because it's likely cheap and reduces data transfer)
    if (_etype == ExecType.CP
        && _etypeForced != ExecType.CP
        && !(getInput().get(0) instanceof DataOp) // input is not checkpoint
        && getInput().get(0).getParent().size() == 1 // uagg is only parent
        && getInput().get(0).optFindExecType() == ExecType.SPARK) {
      // pull unary aggregate into spark
      _etype = ExecType.SPARK;
    }

    // mark for recompile (forever)
    if (ConfigurationManager.isDynamicRecompilation() && !dimsKnown(true) && _etype == REMOTE) {
      setRequiresRecompile();
    }

    return _etype;
  }
  private boolean isUnaryAggregateOuterRewriteApplicable() {
    boolean ret = false;
    Hop input = getInput().get(0);

    if (input instanceof BinaryOp && ((BinaryOp) input).isOuterVectorOperator()) {
      // for special cases, we need to hold the broadcast twice in order to allow for
      // an efficient binary search over a plain java array
      double factor =
          (isCompareOperator(((BinaryOp) input).getOp())
                  && (_direction == Direction.Row
                      || _direction == Direction.Col
                      || _direction == Direction.RowCol)
                  && (_op == AggOp.SUM))
              ? 2.0
              : 1.0;

      factor +=
          (isCompareOperator(((BinaryOp) input).getOp())
                  && (_direction == Direction.Row || _direction == Direction.Col)
                  && (_op == AggOp.MAXINDEX || _op == AggOp.MININDEX))
              ? 1.0
              : 0.0;

      // note: memory constraint only needs to take the rhs into account because the output
      // is guaranteed to be an aggregate of <=16KB
      Hop right = input.getInput().get(1);
      if ((right.dimsKnown()
              && factor * OptimizerUtils.estimateSize(right.getDim1(), right.getDim2())
                  < OptimizerUtils.getRemoteMemBudgetMap(true)) // dims known and estimate fits
          || (!right.dimsKnown()
              && factor * right.getOutputMemEstimate()
                  < OptimizerUtils.getRemoteMemBudgetMap(
                      true))) // dims unknown but worst-case estimate fits
      {
        ret = true;
      }
    }

    return ret;
  }
  /**
   * This will check if there is sufficient memory locally (twice the size of second matrix, for
   * original and sort data), and remotely (size of second matrix (sorted data)).
   *
   * @return true if sufficient memory
   */
  private boolean isUnaryAggregateOuterSPRewriteApplicable() {
    boolean ret = false;
    Hop input = getInput().get(0);

    if (input instanceof BinaryOp && ((BinaryOp) input).isOuterVectorOperator()) {
      // note: both cases (partitioned matrix, and sorted double array), require to
      // fit the broadcast twice into the local memory budget. Also, the memory
      // constraint only needs to take the rhs into account because the output is
      // guaranteed to be an aggregate of <=16KB

      Hop right = input.getInput().get(1);

      double size =
          right.dimsKnown()
              ? OptimizerUtils.estimateSize(right.getDim1(), right.getDim2())
              : // dims known and estimate fits
              right.getOutputMemEstimate(); // dims unknown but worst-case estimate fits

      if (_op == AggOp.MAXINDEX || _op == AggOp.MININDEX) {
        double memBudgetExec = SparkExecutionContext.getBroadcastMemoryBudget();
        double memBudgetLocal = OptimizerUtils.getLocalMemBudget();

        // basic requirement: the broadcast needs to to fit twice in the remote broadcast memory
        // and local memory budget because we have to create a partitioned broadcast
        // memory and hand it over to the spark context as in-memory object
        ret = (2 * size < memBudgetExec && 2 * size < memBudgetLocal);

      } else {
        if (OptimizerUtils.checkSparkBroadcastMemoryBudget(size)) {
          ret = true;
        }
      }
    }

    return ret;
  }
  private Lop constructLopsTernaryAggregateRewrite(ExecType et)
      throws HopsException, LopsException {
    Hop input1 = getInput().get(0);
    Hop input11 = input1.getInput().get(0);
    Hop input12 = input1.getInput().get(1);

    Lop ret = null;
    Lop in1 = null;
    Lop in2 = null;
    Lop in3 = null;

    if (input11 instanceof BinaryOp && ((BinaryOp) input11).getOp() == OpOp2.MULT) {
      in1 = input11.getInput().get(0).constructLops();
      in2 = input11.getInput().get(1).constructLops();
      in3 = input12.constructLops();
    } else if (input12 instanceof BinaryOp && ((BinaryOp) input12).getOp() == OpOp2.MULT) {
      in1 = input11.constructLops();
      in2 = input12.getInput().get(0).constructLops();
      in3 = input12.getInput().get(1).constructLops();
    } else {
      in1 = input11.constructLops();
      in2 = input12.constructLops();
      in3 = new LiteralOp(1).constructLops();
    }

    // create new ternary aggregate operator
    int k = OptimizerUtils.getConstrainedNumThreads(_maxNumThreads);
    // The execution type of a unary aggregate instruction should depend on the execution type of
    // inputs to avoid OOM
    // Since we only support matrix-vector and not vector-matrix, checking the execution type of
    // input1 should suffice.
    ExecType et_input = input1.optFindExecType();
    ret =
        new TernaryAggregate(
            in1,
            in2,
            in3,
            Aggregate.OperationTypes.KahanSum,
            Binary.OperationTypes.MULTIPLY,
            DataType.SCALAR,
            ValueType.DOUBLE,
            et_input,
            k);

    return ret;
  }
  @Override
  public Lop constructLops() throws HopsException, LopsException {
    // return already created lops
    if (getLops() != null) return getLops();

    try {
      ExecType et = optFindExecType();
      Hop input = getInput().get(0);

      if (et == ExecType.CP) {
        Lop agg1 = null;
        if (isTernaryAggregateRewriteApplicable()) {
          agg1 = constructLopsTernaryAggregateRewrite(et);
        } else if (isUnaryAggregateOuterCPRewriteApplicable()) {
          OperationTypes op = HopsAgg2Lops.get(_op);
          DirectionTypes dir = HopsDirection2Lops.get(_direction);

          BinaryOp binput = (BinaryOp) getInput().get(0);
          agg1 =
              new UAggOuterChain(
                  binput.getInput().get(0).constructLops(),
                  binput.getInput().get(1).constructLops(),
                  op,
                  dir,
                  HopsOpOp2LopsB.get(binput.getOp()),
                  DataType.MATRIX,
                  getValueType(),
                  ExecType.CP);
          PartialAggregate.setDimensionsBasedOnDirection(
              agg1, getDim1(), getDim2(), input.getRowsInBlock(), input.getColsInBlock(), dir);

          if (getDataType() == DataType.SCALAR) {
            UnaryCP unary1 =
                new UnaryCP(
                    agg1, HopsOpOp1LopsUS.get(OpOp1.CAST_AS_SCALAR), getDataType(), getValueType());
            unary1.getOutputParameters().setDimensions(0, 0, 0, 0, -1);
            setLineNumbers(unary1);
            setLops(unary1);
          }

        } else { // general case
          int k = OptimizerUtils.getConstrainedNumThreads(_maxNumThreads);
          if (DMLScript.USE_ACCELERATOR
              && (DMLScript.FORCE_ACCELERATOR
                  || getMemEstimate() < OptimizerUtils.GPU_MEMORY_BUDGET)
              && (_op == AggOp.SUM)) {
            et = ExecType.GPU;
            k = 1;
          }
          agg1 =
              new PartialAggregate(
                  input.constructLops(),
                  HopsAgg2Lops.get(_op),
                  HopsDirection2Lops.get(_direction),
                  getDataType(),
                  getValueType(),
                  et,
                  k);
        }

        setOutputDimensions(agg1);
        setLineNumbers(agg1);
        setLops(agg1);

        if (getDataType() == DataType.SCALAR) {
          agg1.getOutputParameters()
              .setDimensions(1, 1, getRowsInBlock(), getColsInBlock(), getNnz());
        }
      } else if (et == ExecType.MR) {
        OperationTypes op = HopsAgg2Lops.get(_op);
        DirectionTypes dir = HopsDirection2Lops.get(_direction);

        // unary aggregate operation
        Lop transform1 = null;
        if (isUnaryAggregateOuterRewriteApplicable()) {
          BinaryOp binput = (BinaryOp) getInput().get(0);
          transform1 =
              new UAggOuterChain(
                  binput.getInput().get(0).constructLops(),
                  binput.getInput().get(1).constructLops(),
                  op,
                  dir,
                  HopsOpOp2LopsB.get(binput.getOp()),
                  DataType.MATRIX,
                  getValueType(),
                  ExecType.MR);
          PartialAggregate.setDimensionsBasedOnDirection(
              transform1,
              getDim1(),
              getDim2(),
              input.getRowsInBlock(),
              input.getColsInBlock(),
              dir);
        } else // default
        {
          transform1 =
              new PartialAggregate(input.constructLops(), op, dir, DataType.MATRIX, getValueType());
          ((PartialAggregate) transform1)
              .setDimensionsBasedOnDirection(
                  getDim1(), getDim2(), input.getRowsInBlock(), input.getColsInBlock());
        }
        setLineNumbers(transform1);

        // aggregation if required
        Lop aggregate = null;
        Group group1 = null;
        Aggregate agg1 = null;
        if (requiresAggregation(input, _direction) || transform1 instanceof UAggOuterChain) {
          group1 =
              new Group(transform1, Group.OperationTypes.Sort, DataType.MATRIX, getValueType());
          group1
              .getOutputParameters()
              .setDimensions(
                  getDim1(), getDim2(), input.getRowsInBlock(), input.getColsInBlock(), getNnz());
          setLineNumbers(group1);

          agg1 = new Aggregate(group1, HopsAgg2Lops.get(_op), DataType.MATRIX, getValueType(), et);
          agg1.getOutputParameters()
              .setDimensions(
                  getDim1(), getDim2(), input.getRowsInBlock(), input.getColsInBlock(), getNnz());
          agg1.setupCorrectionLocation(PartialAggregate.getCorrectionLocation(op, dir));
          setLineNumbers(agg1);

          aggregate = agg1;
        } else {
          ((PartialAggregate) transform1).setDropCorrection();
          aggregate = transform1;
        }

        setLops(aggregate);

        // cast if required
        if (getDataType() == DataType.SCALAR) {

          // Set the dimensions of PartialAggregate LOP based on the
          // direction in which aggregation is performed
          PartialAggregate.setDimensionsBasedOnDirection(
              transform1,
              input.getDim1(),
              input.getDim2(),
              input.getRowsInBlock(),
              input.getColsInBlock(),
              dir);

          if (group1 != null && agg1 != null) { // if aggregation required
            group1
                .getOutputParameters()
                .setDimensions(
                    input.getDim1(),
                    input.getDim2(),
                    input.getRowsInBlock(),
                    input.getColsInBlock(),
                    getNnz());
            agg1.getOutputParameters()
                .setDimensions(1, 1, input.getRowsInBlock(), input.getColsInBlock(), getNnz());
          }

          UnaryCP unary1 =
              new UnaryCP(
                  aggregate,
                  HopsOpOp1LopsUS.get(OpOp1.CAST_AS_SCALAR),
                  getDataType(),
                  getValueType());
          unary1.getOutputParameters().setDimensions(0, 0, 0, 0, -1);
          setLineNumbers(unary1);
          setLops(unary1);
        }
      } else if (et == ExecType.SPARK) {
        OperationTypes op = HopsAgg2Lops.get(_op);
        DirectionTypes dir = HopsDirection2Lops.get(_direction);

        // unary aggregate
        if (isTernaryAggregateRewriteApplicable()) {
          Lop aggregate = constructLopsTernaryAggregateRewrite(et);
          setOutputDimensions(aggregate); // 0x0 (scalar)
          setLineNumbers(aggregate);
          setLops(aggregate);
        } else if (isUnaryAggregateOuterSPRewriteApplicable()) {
          BinaryOp binput = (BinaryOp) getInput().get(0);
          Lop transform1 =
              new UAggOuterChain(
                  binput.getInput().get(0).constructLops(),
                  binput.getInput().get(1).constructLops(),
                  op,
                  dir,
                  HopsOpOp2LopsB.get(binput.getOp()),
                  DataType.MATRIX,
                  getValueType(),
                  ExecType.SPARK);
          PartialAggregate.setDimensionsBasedOnDirection(
              transform1,
              getDim1(),
              getDim2(),
              input.getRowsInBlock(),
              input.getColsInBlock(),
              dir);
          setLineNumbers(transform1);
          setLops(transform1);

          if (getDataType() == DataType.SCALAR) {
            UnaryCP unary1 =
                new UnaryCP(
                    transform1,
                    HopsOpOp1LopsUS.get(OpOp1.CAST_AS_SCALAR),
                    getDataType(),
                    getValueType());
            unary1.getOutputParameters().setDimensions(0, 0, 0, 0, -1);
            setLineNumbers(unary1);
            setLops(unary1);
          }

        } else // default
        {
          boolean needAgg = requiresAggregation(input, _direction);
          SparkAggType aggtype = getSparkUnaryAggregationType(needAgg);

          PartialAggregate aggregate =
              new PartialAggregate(
                  input.constructLops(),
                  HopsAgg2Lops.get(_op),
                  HopsDirection2Lops.get(_direction),
                  DataType.MATRIX,
                  getValueType(),
                  aggtype,
                  et);
          aggregate.setDimensionsBasedOnDirection(
              getDim1(), getDim2(), input.getRowsInBlock(), input.getColsInBlock());
          setLineNumbers(aggregate);
          setLops(aggregate);

          if (getDataType() == DataType.SCALAR) {
            UnaryCP unary1 =
                new UnaryCP(
                    aggregate,
                    HopsOpOp1LopsUS.get(OpOp1.CAST_AS_SCALAR),
                    getDataType(),
                    getValueType());
            unary1.getOutputParameters().setDimensions(0, 0, 0, 0, -1);
            setLineNumbers(unary1);
            setLops(unary1);
          }
        }
      }
    } catch (Exception e) {
      throw new HopsException(
          this.printErrorLocation() + "In AggUnary Hop, error constructing Lops ", e);
    }

    // add reblock/checkpoint lops if necessary
    constructAndSetLopsDataFlowProperties();

    // return created lops
    return getLops();
  }
 @Override
 protected double computeOutputMemEstimate(long dim1, long dim2, long nnz) {
   double sparsity = OptimizerUtils.getSparsity(dim1, dim2, nnz);
   return OptimizerUtils.estimateSizeExactSparsity(dim1, dim2, sparsity);
 }
  /**
   * @return
   * @throws HopsException
   * @throws LopsException
   */
  private Lop constructLopsSparkCumulativeUnary() throws HopsException, LopsException {
    Hop input = getInput().get(0);
    long rlen = input.getDim1();
    long clen = input.getDim2();
    long brlen = input.getRowsInBlock();
    long bclen = input.getColsInBlock();
    boolean force = !dimsKnown() || _etypeForced == ExecType.SPARK;
    OperationTypes aggtype = getCumulativeAggType();

    Lop X = input.constructLops();
    Lop TEMP = X;
    ArrayList<Lop> DATA = new ArrayList<Lop>();
    int level = 0;

    // recursive preaggregation until aggregates fit into CP memory budget
    while (((2 * OptimizerUtils.estimateSize(TEMP.getOutputParameters().getNumRows(), clen)
                    + OptimizerUtils.estimateSize(1, clen))
                > OptimizerUtils.getLocalMemBudget()
            && TEMP.getOutputParameters().getNumRows() > 1)
        || force) {
      DATA.add(TEMP);

      // preaggregation per block (for spark, the CumulativePartialAggregate subsumes both
      // the preaggregation and subsequent block aggregation)
      long rlenAgg = (long) Math.ceil((double) TEMP.getOutputParameters().getNumRows() / brlen);
      Lop preagg =
          new CumulativePartialAggregate(
              TEMP, DataType.MATRIX, ValueType.DOUBLE, aggtype, ExecType.SPARK);
      preagg.getOutputParameters().setDimensions(rlenAgg, clen, brlen, bclen, -1);
      setLineNumbers(preagg);

      TEMP = preagg;
      level++;
      force = false; // in case of unknowns, generate one level
    }

    // in-memory cum sum (of partial aggregates)
    if (TEMP.getOutputParameters().getNumRows() != 1) {
      int k = OptimizerUtils.getConstrainedNumThreads(_maxNumThreads);
      Unary unary1 =
          new Unary(
              TEMP, HopsOpOp1LopsU.get(_op), DataType.MATRIX, ValueType.DOUBLE, ExecType.CP, k);
      unary1
          .getOutputParameters()
          .setDimensions(TEMP.getOutputParameters().getNumRows(), clen, brlen, bclen, -1);
      setLineNumbers(unary1);
      TEMP = unary1;
    }

    // split, group and mr cumsum
    while (level-- > 0) {
      // (for spark, the CumulativeOffsetBinary subsumes both the split aggregate and
      // the subsequent offset binary apply of split aggregates against the original data)
      double initValue = getCumulativeInitValue();
      CumulativeOffsetBinary binary =
          new CumulativeOffsetBinary(
              DATA.get(level),
              TEMP,
              DataType.MATRIX,
              ValueType.DOUBLE,
              initValue,
              aggtype,
              ExecType.SPARK);
      binary.getOutputParameters().setDimensions(rlen, clen, brlen, bclen, -1);
      setLineNumbers(binary);
      TEMP = binary;
    }

    return TEMP;
  }
  /**
   * MR Cumsum is currently based on a multipass algorithm of (1) preaggregation and (2) subsequent
   * offsetting. Note that we currently support one robust physical operator but many alternative
   * realizations are possible for specific scenarios (e.g., when the preaggregated intermediate fit
   * into the map task memory budget) or by creating custom job types.
   *
   * @return
   * @throws HopsException
   * @throws LopsException
   */
  private Lop constructLopsMRCumulativeUnary() throws HopsException, LopsException {
    Hop input = getInput().get(0);
    long rlen = input.getDim1();
    long clen = input.getDim2();
    long brlen = input.getRowsInBlock();
    long bclen = input.getColsInBlock();
    boolean force = !dimsKnown() || _etypeForced == ExecType.MR;
    OperationTypes aggtype = getCumulativeAggType();

    Lop X = input.constructLops();
    Lop TEMP = X;
    ArrayList<Lop> DATA = new ArrayList<Lop>();
    int level = 0;

    // recursive preaggregation until aggregates fit into CP memory budget
    while (((2 * OptimizerUtils.estimateSize(TEMP.getOutputParameters().getNumRows(), clen)
                    + OptimizerUtils.estimateSize(1, clen))
                > OptimizerUtils.getLocalMemBudget()
            && TEMP.getOutputParameters().getNumRows() > 1)
        || force) {
      DATA.add(TEMP);

      // preaggregation per block
      long rlenAgg = (long) Math.ceil((double) TEMP.getOutputParameters().getNumRows() / brlen);
      Lop preagg =
          new CumulativePartialAggregate(
              TEMP, DataType.MATRIX, ValueType.DOUBLE, aggtype, ExecType.MR);
      preagg.getOutputParameters().setDimensions(rlenAgg, clen, brlen, bclen, -1);
      setLineNumbers(preagg);

      Group group = new Group(preagg, Group.OperationTypes.Sort, DataType.MATRIX, ValueType.DOUBLE);
      group.getOutputParameters().setDimensions(rlenAgg, clen, brlen, bclen, -1);
      setLineNumbers(group);

      Aggregate agg =
          new Aggregate(
              group, HopsAgg2Lops.get(AggOp.SUM), getDataType(), getValueType(), ExecType.MR);
      agg.getOutputParameters().setDimensions(rlenAgg, clen, brlen, bclen, -1);
      agg.setupCorrectionLocation(
          CorrectionLocationType
              .NONE); // aggregation uses kahanSum but the inputs do not have correction values
      setLineNumbers(agg);
      TEMP = agg;
      level++;
      force = false; // in case of unknowns, generate one level
    }

    // in-memory cum sum (of partial aggregates)
    if (TEMP.getOutputParameters().getNumRows() != 1) {
      int k = OptimizerUtils.getConstrainedNumThreads(_maxNumThreads);
      Unary unary1 =
          new Unary(
              TEMP, HopsOpOp1LopsU.get(_op), DataType.MATRIX, ValueType.DOUBLE, ExecType.CP, k);
      unary1
          .getOutputParameters()
          .setDimensions(TEMP.getOutputParameters().getNumRows(), clen, brlen, bclen, -1);
      setLineNumbers(unary1);
      TEMP = unary1;
    }

    // split, group and mr cumsum
    while (level-- > 0) {
      double init = getCumulativeInitValue();
      CumulativeSplitAggregate split =
          new CumulativeSplitAggregate(TEMP, DataType.MATRIX, ValueType.DOUBLE, init);
      split.getOutputParameters().setDimensions(rlen, clen, brlen, bclen, -1);
      setLineNumbers(split);

      Group group1 =
          new Group(DATA.get(level), Group.OperationTypes.Sort, DataType.MATRIX, ValueType.DOUBLE);
      group1.getOutputParameters().setDimensions(rlen, clen, brlen, bclen, -1);
      setLineNumbers(group1);

      Group group2 = new Group(split, Group.OperationTypes.Sort, DataType.MATRIX, ValueType.DOUBLE);
      group2.getOutputParameters().setDimensions(rlen, clen, brlen, bclen, -1);
      setLineNumbers(group2);

      CumulativeOffsetBinary binary =
          new CumulativeOffsetBinary(
              group1, group2, DataType.MATRIX, ValueType.DOUBLE, aggtype, ExecType.MR);
      binary.getOutputParameters().setDimensions(rlen, clen, brlen, bclen, -1);
      setLineNumbers(binary);
      TEMP = binary;
    }

    return TEMP;
  }
  @Override
  public Lop constructLops() throws HopsException, LopsException {
    // reuse existing lop
    if (getLops() != null) return getLops();

    try {
      Hop input = getInput().get(0);

      if (getDataType() == DataType.SCALAR // value type casts or matrix to scalar
          || (_op == OpOp1.CAST_AS_MATRIX && getInput().get(0).getDataType() == DataType.SCALAR)
          || (_op == OpOp1.CAST_AS_FRAME && getInput().get(0).getDataType() == DataType.SCALAR)) {
        if (_op == Hop.OpOp1.IQM) // special handling IQM
        {
          Lop iqmLop = constructLopsIQM();
          setLops(iqmLop);
        } else if (_op == Hop.OpOp1.MEDIAN) {
          Lop medianLop = constructLopsMedian();
          setLops(medianLop);
        } else // general case SCALAR/CAST (always in CP)
        {
          UnaryCP.OperationTypes optype = HopsOpOp1LopsUS.get(_op);
          if (optype == null)
            throw new HopsException(
                "Unknown UnaryCP lop type for UnaryOp operation type '" + _op + "'");

          UnaryCP unary1 =
              new UnaryCP(input.constructLops(), optype, getDataType(), getValueType());
          setOutputDimensions(unary1);
          setLineNumbers(unary1);

          setLops(unary1);
        }
      } else // general case MATRIX
      {
        ExecType et = optFindExecType();

        // special handling cumsum/cumprod/cummin/cumsum
        if (isCumulativeUnaryOperation() && et != ExecType.CP) {
          // TODO additional physical operation if offsets fit in memory
          Lop cumsumLop = null;
          if (et == ExecType.MR) cumsumLop = constructLopsMRCumulativeUnary();
          else cumsumLop = constructLopsSparkCumulativeUnary();
          setLops(cumsumLop);
        } else // default unary
        {
          int k =
              isCumulativeUnaryOperation()
                  ? OptimizerUtils.getConstrainedNumThreads(_maxNumThreads)
                  : 1;
          Unary unary1 =
              new Unary(
                  input.constructLops(),
                  HopsOpOp1LopsU.get(_op),
                  getDataType(),
                  getValueType(),
                  et,
                  k);
          setOutputDimensions(unary1);
          setLineNumbers(unary1);
          setLops(unary1);
        }
      }
    } catch (Exception e) {
      throw new HopsException(
          this.printErrorLocation() + "error constructing Lops for UnaryOp Hop -- \n ", e);
    }

    // add reblock/checkpoint lops if necessary
    constructAndSetLopsDataFlowProperties();

    return getLops();
  }