ops.cpp 12 KB
Newer Older
1
//*****************************************************************************
nmostafa's avatar
nmostafa committed
2
// Copyright 2017-2019 Intel Corporation
3 4 5 6 7 8 9 10 11 12 13 14 15
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
16 17 18 19

// NOTE: This file follows nGraph format style and MLIR naming convention since it does
// not expose public API to the rest of nGraph codebase and heavily depends on MLIR API.

20 21
#include "ops.hpp"
#include "assertion.hpp"
22
#include "llvm/ADT/StringSwitch.h"
23 24 25 26 27 28 29 30 31 32 33
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/raw_ostream.h"
#include "type.hpp"

using llvm::ArrayRef;
using llvm::raw_ostream;
using llvm::raw_string_ostream;
using llvm::SmallVector;
using llvm::StringRef;
using llvm::Twine;
34
using namespace mlir;
35 36

#include "ops_attributes.cpp.inc"
37 38 39 40 41 42 43
// TODO:
// - Move verifiers and other OP helpers (e.g. getSomeAttribute()) to separate files
//
// - Op helpers: Since it is not possible to add arbitrary code (and would complicate the .td file)
// to Ops classes, we will add helper classes with static methods for each Op that needs it
// Additional verification methods
// Tensor type checks are already verified by the caller of these methods
44 45

/// Checks if all operands and results are of compatible shapes
46
template <typename T>
47
static mlir::LogicalResult verifyCompatibleOperandsAndResults(T* op, bool checkResult = true)
48
{
49 50 51 52 53 54 55 56
    mlir::Type t0 = op->getOperation()->getOperand(0)->getType();
    mlir::NGTensorType opType0 = t0.cast<NGTensorType>();

    Operation* opr = op->getOperation();
    auto i = 0;
    for (auto operand : opr->getOperands())
    {
        if (i == 0)
57
        {
58
            continue;
59
        }
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        mlir::Type t = operand->getType();
        mlir::NGTensorType opType = t.cast<NGTensorType>();
        if (!opType.isCompatible(opType0))
            return op->emitOpError("Incompatible operand shape");
        i++;
    }

    if (checkResult)
    {
        for (auto result : opr->getResults())
        {
            mlir::Type t = result->getType();
            mlir::NGTensorType resType = t.cast<NGTensorType>();
            if (!resType.isCompatible(opType0))
                return op->emitOpError("Incompatible operand shape");
        }
    }
77 78
    return mlir::success();
}
79

80 81 82 83 84 85
template <typename T>
static mlir::LogicalResult verifyUnaryArithOp(T* op)
{
    return verifyCompatibleOperandsAndResults(op);
}

86 87 88
template <typename T>
static mlir::LogicalResult verifyBinaryArithOp(T* op)
{
89
    return verifyCompatibleOperandsAndResults(op);
90
}
91

92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
template <typename T>
static mlir::LogicalResult verifyAxisReductionOp(T* op)
{
    return mlir::failure();
}

template <typename T>
static mlir::LogicalResult verifyLogicalReductionOp(T* op)
{
    // TODO: verifyAxisReductionOp(op) + input and return element type.
    return mlir::failure();
}

template <typename T>
static mlir::LogicalResult verifyIndexReductionOp(T* op)
{
    // TODO: verifyAxisReductionOp(op) + return element type + single axis.
109
    return mlir::success();
110 111
}

112 113 114 115 116
template <typename T>
static mlir::LogicalResult verifyOp(T* op)
{
    return op->emitOpError("Unsupported verifier for this operation");
}
117

118
template <>
119
mlir::LogicalResult verifyOp(NGDotOp* op)
120
{
121 122 123 124
    // TODO(dcab): Improve verification: proper shapes, etc.
    return mlir::success();
}

Adam Procter's avatar
Adam Procter committed
125 126 127 128 129 130 131
template <>
mlir::LogicalResult verifyOp(NGConcatOp* op)
{
    // TODO(amprocte): Improve verification: proper shapes, etc.
    return mlir::success();
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
template <>
mlir::LogicalResult verifyOp(NGSelectOp* op)
{
    mlir::Type t0 = op->getOperation()->getOperand(0)->getType();
    mlir::Type t1 = op->getOperation()->getOperand(1)->getType();
    mlir::Type t2 = op->getOperation()->getOperand(2)->getType();
    mlir::Type r0 = op->getOperation()->getResult(0)->getType();

    NGTensorType opType0 = t0.cast<NGTensorType>();
    NGTensorType opType1 = t1.cast<NGTensorType>();
    NGTensorType opType2 = t2.cast<NGTensorType>();
    NGTensorType resType = r0.cast<NGTensorType>();

    // arg1 arg2 of same shape and elt type
    if (!opType1.isCompatible(opType2))
        return op->emitOpError("Incompatible operand shapes or types for select op");
    // arg0 of same shape and elt type is bool
    if (!opType0.isCompatibleShape(opType1) || !opType0.getElementType().isa<NGBoolType>())
        return op->emitOpError("Incompatible shape for arg0 of select op");
    // result is of same shape and elt type as arg1/2
    if (!resType.isCompatible(opType1))
        return op->emitOpError("Incompatible result shape or type for select op");

    return mlir::success();
}

template <typename T>
static mlir::LogicalResult verifyCmpOp(T* op)
{
    mlir::LogicalResult result = verifyCompatibleOperandsAndResults(op, false /*checkResult*/);
162
    if (failed(result))
163
    {
164
        return result;
165
    }
166

167 168 169 170 171 172 173 174 175
    mlir::Type t0 = op->getOperation()->getOperand(0)->getType();
    mlir::NGTensorType opType0 = t0.cast<NGTensorType>();

    mlir::Type r0 = op->getOperation()->getResult(0)->getType();
    NGTensorType resType = r0.cast<NGTensorType>();

    // result of same shape as input and has bool type
    if (!resType.isCompatibleShape(opType0) || !resType.getElementType().isa<NGBoolType>())
        return op->emitOpError("Incompatible result shape or type for comparison op");
176

177 178
    return mlir::success();
}
179

nmostafa's avatar
nmostafa committed
180 181 182
template <>
mlir::LogicalResult verifyOp(NGGatherOp* op)
{
183
    Type ty = op->params()->getType();
nmostafa's avatar
nmostafa committed
184
    NGTensorType inputType = ty.cast<NGTensorType>();
nmostafa's avatar
nmostafa committed
185

nmostafa's avatar
nmostafa committed
186
    ty = op->indices()->getType();
nmostafa's avatar
nmostafa committed
187 188 189
    NGTensorType indicesType = ty.cast<NGTensorType>();

    // ensure axis < params rank
nmostafa's avatar
nmostafa committed
190
    if (op->axis().getSExtValue() >= inputType.getRank())
nmostafa's avatar
nmostafa committed
191 192 193 194 195 196 197 198 199 200 201
        return op->emitOpError("Gather axis is larger than input rank");

    ty = indicesType.getElementType();

    // ensure indices are I32 or I64
    if (!ty.isa<NGIntegerType>())
        return op->emitOpError("Indices tensor is not of Integer type");

    NGIntegerType indicesEltType = ty.cast<NGIntegerType>();
    if (!indicesEltType.isInt32() && !indicesEltType.isInt64())
        return op->emitOpError("Indices tensor is not of I32 or I64 type");
nmostafa's avatar
nmostafa committed
202

nmostafa's avatar
nmostafa committed
203 204
    mlir::Type r0 = op->res()->getType();
    NGTensorType resType = r0.cast<NGTensorType>();
nmostafa's avatar
nmostafa committed
205

nmostafa's avatar
nmostafa committed
206
    // ensure result is compatible with input
207
    if (resType.getRank() != inputType.getRank() + indicesType.getRank() - 1)
nmostafa's avatar
nmostafa committed
208 209 210 211 212
        return op->emitOpError("Incompatible result shape and/or type");

    return mlir::success();
}

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
template <>
mlir::LogicalResult verifyOp(NGConvolutionOp* op)
{
    Type ty = op->images()->getType();
    NGTensorType imagesType = ty.cast<NGTensorType>();
    Type imagesEt = imagesType.getElementType();
    Shape imagesShape = imagesType.getShape();

    ty = op->filters()->getType();
    NGTensorType filtersType = ty.cast<NGTensorType>();
    Type filtersEt = filtersType.getElementType();
    Shape filtersShape = filtersType.getShape();

    ty = op->res()->getType();
    NGTensorType resultType = ty.cast<NGTensorType>();
    Shape resultShape = resultType.getShape();

    ArrayAttr strides = op->strides();
    ArrayAttr padBelow = op->padBelow();
    ArrayAttr padAbove = op->padAbove();

    unsigned imagesRank = imagesShape.size();
    unsigned filtersRank = filtersShape.size();
    unsigned resultRank = resultShape.size();
    unsigned imageSpatialRank = imagesRank - 2;
    unsigned filtersSpatialRank = filtersRank - 2;
    unsigned stridesRank = strides.size();
    unsigned padBelowRank = padBelow.size();
    unsigned padAboveRank = padAbove.size();

    SmallVector<int64_t, 4> stridesVal, padAboveVal, padBelowVal;
    // Identical filters and image element types
245
    if (filtersEt != imagesEt)
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    {
        return op->emitOpError("Incompatible image and filters types");
    }

    // Verify image shape
    if (imagesRank < 3)
    {
        return op->emitOpError("Image shape of rank below 3");
    }

    // Verify strides and pads shapes
    if (imageSpatialRank != stridesRank || imageSpatialRank != padBelowRank ||
        imageSpatialRank != padAboveRank)
    {
        return op->emitOpError("Image spatial rank mismatches strides and/or padding ranks");
    }

    if (imageSpatialRank != filtersSpatialRank)
    {
        return op->emitOpError("Image and filters spatial ranks mismatch");
    }

    // Batch size is non-zero, and identical non-zero channel depth
    if (imagesShape[0] <= 0 || filtersShape[0] <= 0 || imagesShape[1] != filtersShape[1] ||
        imagesShape[1] <= 0)
    {
        return op->emitOpError("Image and filters have invalid shapes");
    }

    for (auto attrs : llvm::zip(strides, padBelow, padAbove))
    {
        auto s = std::get<0>(attrs).cast<IntegerAttr>().getInt();
        auto pb = std::get<1>(attrs).cast<IntegerAttr>().getInt();
        auto pa = std::get<2>(attrs).cast<IntegerAttr>().getInt();
280

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        if (s <= 0)
        {
            return op->emitOpError("Window stride must be non-negative");
        }
        stridesVal.push_back(s);
        padBelowVal.push_back(pb);
        padAboveVal.push_back(pa);
    }

    // Check output shape
    if (resultRank != imagesRank || resultShape[0] != imagesShape[0] ||
        resultShape[1] != filtersShape[0])
    {
        return op->emitOpError("Invalid result shape");
    }
    for (unsigned i = 0; i < resultRank - 2; i++)
    {
        unsigned resDim = llvm::divideCeil(padBelowVal[i] + padAboveVal[i] + imagesShape[2 + i] -
                                               filtersShape[2 + i] + 1,
                                           stridesVal[i]);
301
        if (resultShape[2 + i] != resDim)
302 303 304 305 306 307
        {
            return op->emitOpError("Invalid result spatial shape");
        }
    }
    return mlir::success();
}
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

static std::string getBufferIdAttrName()
{
    return "ng.buffer_id";
}

void setBufferId(mlir::Operation* op, mlir::IntegerAttr attr)
{
    op->setAttr(getBufferIdAttrName(), attr);
}

mlir::IntegerAttr setBufferId(mlir::Operation* op, unsigned val)
{
    auto attr = mlir::IntegerAttr::get(IntegerType::get(32, op->getContext()), val);
    setBufferId(op, attr);
    return attr;
}

mlir::IntegerAttr getBufferId(mlir::Operation* op)
{
    return op->getAttrOfType<mlir::IntegerAttr>(getBufferIdAttrName());
}

331 332
namespace mlir
{
333 334
#include "ops_interfaces.cpp.inc"

335 336
#define GET_OP_CLASSES
#include "ops.cpp.inc"
337
}
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

// Fused Ops decompose
// Stubs for now
// TODO: Implement and move to another file
void mlir::NGSpaceToDepthOp::decompose()
{
}
void mlir::NGSplitOp::decompose()
{
}
void mlir::NGScaleShiftOp::decompose()
{
}
void mlir::NGUnSqueezeOp::decompose()
{
}
void mlir::NGSquaredDiffOp::decompose()
{
}
void mlir::NGSqueezeOp::decompose()
{
}
void mlir::NGShuffleChannelsOp::decompose()
{
}
void mlir::NGRNNCellOp::decompose()
{
}
void mlir::NGFakeQuantOp::decompose()
{
}
void mlir::NGMVN::decompose()
{
}
void mlir::NGHardSigmoid::decompose()
{
}
void mlir::NGGRNOp::decompose()
{
}
void mlir::NGNormalizeL2Op::decompose()
{
}
void mlir::NGConvBiasBackpropFiltersBias::decompose()
{
}
void mlir::NGPrelu::decompose()
{
}
void mlir::NGLayerNormBackpropOp::decompose()
{
}
void mlir::NGGemmOp::decompose()
{
}
void mlir::NGClampOp::decompose()
{
}
void mlir::NGGroupConvTransposeOp::decompose()
{
}
void mlir::NGConvBiasOp::decompose()
{
}
void mlir::NGConvBiasAddOp::decompose()
{
}
void mlir::NGGRUCellOp::decompose()
{
}
void mlir::NGGroupConvOp::decompose()
{
}
void mlir::NGGeluOp::decompose()
{
}
void mlir::NGGeluBackpropFactorOp::decompose()
{
}
void mlir::NGLSTMCellOp::decompose()
{
}
void mlir::NGLSTMSequenceOp::decompose()
{
}
void mlir::NGMatMul::decompose()
{
}
void mlir::NGLayerNormOp::decompose()
{
}
void mlir::NGDepthToSpaceOp::decompose()
{
}
void mlir::NGEluOp::decompose()
{
}