24 #ifndef TVM_TOPI_NN_H_
25 #define TVM_TOPI_NN_H_
56 std::string name =
"T_relu", std::string tag =
kElementWise) {
59 [&](
const tvm::ffi::Array<tvm::tirx::PrimVar>& i) {
60 auto threshold_const = tvm::tirx::MakeConst(tvm::PrimType(t->dtype), threshold);
61 return tvm::max(t(i), threshold_const);
77 std::string name =
"T_leaky_relu",
81 [&](
const tvm::ffi::Array<tvm::tirx::PrimVar>& i) {
83 auto calpha = tvm::tirx::MakeConst(value.ty(), alpha);
84 return tvm::tirx::Select(value > 0, value, value * calpha);
101 const int axis = 1, std::string name =
"T_prelu",
103 TVM_FFI_ICHECK((
size_t)axis < x->
shape.size()) <<
"Wrong axis (" << axis <<
")value. ";
104 TVM_FFI_ICHECK(topi::detail::GetConstInt(slope->shape[0]) ==
105 topi::detail::GetConstInt(x->shape[axis]))
106 <<
"Wrong slope shape received.";
110 [&](
const tvm::ffi::Array<tvm::tirx::PrimVar>& indices) {
111 auto xval = x(indices);
112 return tvm::tirx::Select(xval > 0, xval, xval * slope(indices[axis]));
157 const tvm::te::Tensor& t,
const tvm::ffi::Array<tvm::PrimExpr>& pad_before,
158 tvm::ffi::Array<tvm::PrimExpr> pad_after = tvm::ffi::Array<tvm::PrimExpr>(),
160 std::string pad_mode =
"constant",
const ffi::Array<PrimExpr>* dyn_output_shape =
nullptr) {
161 if (pad_after.size() < pad_before.size()) {
162 for (
size_t i = pad_after.size(); i < pad_before.size(); ++i) {
163 pad_after.push_back(pad_before[i]);
168 TVM_FFI_ICHECK_GE(pad_before.size(), 1);
169 TVM_FFI_ICHECK_EQ(pad_before.size(), pad_after.size());
170 tvm::ffi::Array<tvm::PrimExpr> pad_before_int32;
171 tvm::ffi::Array<tvm::PrimExpr> pad_after_int32;
173 for (
const auto& ele : pad_before) {
176 for (
const auto& ele : pad_after) {
180 tvm::ffi::Array<tvm::PrimExpr> output_shape;
181 if (dyn_output_shape ==
nullptr) {
182 for (
size_t i = 0; i < t->shape.size(); ++i) {
183 if (i >= pad_before.size()) {
184 output_shape.push_back(t->shape[i]);
186 output_shape.push_back(
187 analyzer->Simplify(t->shape[i] + pad_before_int32[i] + pad_after_int32[i]));
191 for (
size_t i = 0; i < dyn_output_shape->size(); i++) {
192 output_shape.push_back((*dyn_output_shape)[i]);
196 if (!pad_value.defined()) {
200 auto l = [&](tvm::ffi::Array<tvm::tirx::PrimVar> ovars) {
201 tvm::ffi::Array<tvm::PrimExpr> indices;
202 tvm::ffi::Array<tvm::PrimExpr> sel;
203 tvm::ffi::Array<tvm::PrimExpr> pad_idx;
204 for (
size_t i = 0; i < t->shape.size(); ++i) {
205 if (i >= pad_before_int32.size()) {
206 indices.push_back(ovars[i]);
209 if (!topi::detail::EqualCheck(pad_before_int32[i], 0)) {
210 sel.push_back(ovars[i] >= pad_before_int32[i]);
211 indices.push_back(ovars[i] - pad_before_int32[i]);
213 indices.push_back(ovars[i]);
215 if (!topi::detail::EqualCheck(pad_after_int32[i], 0)) {
216 sel.push_back(analyzer->Simplify(ovars[i].as_or_throw<
PrimExpr>() <
217 pad_before_int32[i] + t->shape[i]));
219 if (pad_mode ==
"edge") {
223 t->shape[i] - 1, ovars[i] - pad_before[i])));
224 }
else if (pad_mode ==
"reflect") {
226 ovars[i].as_or_throw<PrimExpr>() < pad_before[i], pad_before[i] - ovars[i],
228 t->shape[i] * 2 - ovars[i] + pad_before[i] - 2,
229 ovars[i] - pad_before[i])));
232 if (sel.size() != 0) {
233 if (pad_mode ==
"constant") {
237 t(indices), pad_value);
238 }
else if (pad_mode ==
"edge" || pad_mode ==
"reflect") {
242 t(indices), t(pad_idx));
271 int pad_h = 0,
int pad_w = 0,
int stride_h = 1,
int stride_w = 1,
272 std::string name =
"T_conv2d_nchw",
274 TVM_FFI_ICHECK_EQ(4, I->shape.size());
275 TVM_FFI_ICHECK_EQ(4, W->shape.size());
276 auto pH = I->shape[2];
277 auto pW = I->shape[3];
278 tvm::ffi::Array<tvm::PrimExpr> output_shape{
281 indexdiv(I->shape[2] - W->shape[2] + 2 * pad_h, stride_h) + 1,
282 indexdiv(I->shape[3] - W->shape[3] + 2 * pad_w, stride_w) + 1
291 return tvm::sum(T(b, i, stride_h * h + kh, stride_w * w + kw) * W(o, i, kh, kw), {i, kh, kw});
316 int pad_h = 0,
int pad_w = 0,
int stride_h = 1,
int stride_w = 1,
317 std::string name =
"T_conv2d_hwcn",
319 TVM_FFI_ICHECK_EQ(4, I->shape.size());
320 TVM_FFI_ICHECK_EQ(4, W->shape.size());
321 auto pH = I->shape[2];
322 auto pW = I->shape[3];
323 tvm::ffi::Array<tvm::PrimExpr> output_shape{
324 indexdiv(I->shape[2] - W->shape[2] + 2 * pad_h, stride_h) + 1,
325 indexdiv(I->shape[3] - W->shape[3] + 2 * pad_w, stride_w) + 1,
332 auto T = (pad_h == 0 && pad_w == 0) ? I :
pad(I, {pad_h, pad_w});
335 return tvm::sum(T(stride_h * h + kh, stride_w * w + kw, i, b) * W(kh, kw, i, o), {i, kh, kw});
361 int pad_h = 0,
int pad_w = 0,
int stride_h = 1,
363 std::string name =
"T_depthwise_conv2d_nchw",
365 TVM_FFI_ICHECK_EQ(4, I->shape.size());
366 TVM_FFI_ICHECK_EQ(4, W->shape.size());
367 auto pH = I->shape[2];
368 auto pW = I->shape[3];
369 auto pCM = W->shape[1];
370 tvm::ffi::Array<tvm::PrimExpr> output_shape{
373 indexdiv(I->shape[2] - W->shape[2] + 2 * pad_h, stride_h) + 1,
374 indexdiv(I->shape[3] - W->shape[3] + 2 * pad_w, stride_w) + 1
383 return tvm::sum(T(b,
indexdiv(i, pCM), stride_h * h + kh, stride_w * w + kw) *
391 int pad_h = 0,
int pad_w = 0,
int stride_h = 1,
393 std::string name =
"T_depthwise_conv2d_nhwc",
395 TVM_FFI_ICHECK_EQ(4, I->shape.size());
396 TVM_FFI_ICHECK_EQ(4, W->shape.size());
397 auto pH = I->shape[1];
398 auto pW = I->shape[2];
399 auto pCM = W->shape[1];
400 tvm::ffi::Array<tvm::PrimExpr> output_shape{
402 indexdiv(I->shape[1] - W->shape[1] + 2 * pad_h, stride_h) + 1,
403 indexdiv(I->shape[2] - W->shape[2] + 2 * pad_w, stride_w) + 1,
413 return tvm::sum(T(b, stride_h * h + kh, stride_w * w + kw,
indexdiv(i, pCM)) *
441 int pad_h = 0,
int pad_w = 0,
int stride_h = 1,
443 std::string name =
"T_group_conv2d_ngchw",
445 TVM_FFI_ICHECK_EQ(5, I->shape.size());
446 TVM_FFI_ICHECK_EQ(5, W->shape.size());
447 auto pH = I->shape[2];
448 auto pW = I->shape[3];
449 tvm::ffi::Array<tvm::PrimExpr> output_shape{
453 indexdiv(I->shape[3] - W->shape[3] + 2 * pad_h, stride_h) + 1,
454 indexdiv(I->shape[4] - W->shape[4] + 2 * pad_w, stride_w) + 1
460 auto T = (pad_h == 0 && pad_w == 0)
463 auto l = [&](tvm::ffi::Array<tvm::tirx::PrimVar> args) {
469 return tvm::sum(I(b, g, i, stride_h * h + kh, stride_w * w + kw) * W(g, i, o, kh, kw),
489 const tvm::ffi::Array<int64_t>& block_shape,
490 const tvm::ffi::Array<tvm::PrimExpr>& pad_before,
491 const tvm::ffi::Array<tvm::PrimExpr>& pad_after,
493 std::string name =
"space_to_batch_nd",
496 TVM_FFI_ICHECK_EQ(pad_before.size(), pad_after.size());
497 TVM_FFI_ICHECK_EQ(block_shape.size(), pad_before.size())
498 <<
"Paddings must be provided for each spatial dimension";
499 tvm::ffi::Array<tvm::PrimExpr> pad_before_int32;
500 tvm::ffi::Array<tvm::PrimExpr> pad_after_int32;
506 for (
const auto& ele : pad_before) {
509 for (
const auto& ele : pad_after) {
514 if (!pad_value.defined()) {
517 padded_t =
pad(data, pad_before_int32, pad_after_int32, pad_value);
519 auto input_shape = data->shape;
520 auto padded_shape = padded_t->shape;
523 tvm::ffi::Array<PrimExpr> r_shape;
524 tvm::ffi::Array<int64_t> axis;
525 tvm::ffi::Array<PrimExpr> o_shape;
527 size_t num_block_dims = block_shape.size();
528 int batch =
static_cast<int>(GetConstInt(input_shape[0]));
530 r_shape.push_back(batch);
532 for (
size_t i = 1; i <= num_block_dims; i++) {
533 int padded_input =
static_cast<int>(GetConstInt(padded_shape[i]));
534 int block_size =
static_cast<int>(block_shape[i - 1]);
535 TVM_FFI_ICHECK_EQ((padded_input % block_size), 0)
538 "Input dimension after padding ("
539 << padded_input <<
")"
540 <<
" must be divisible by its block size (" << block_size <<
")";
543 r_shape.push_back(
div(padded_shape[i], bs));
544 r_shape.push_back(bs);
545 block_shape_prod *= bs;
546 axis.push_back(
static_cast<int64_t
>(r_shape.size() - 1));
549 size_t n = axis.size();
552 for (
size_t i = 0; i < n; i++) {
553 axis.push_back(axis[i] - 1);
556 for (
size_t i = 1; i <= num_block_dims; i++) {
558 o_shape.push_back(
div(padded_shape[i], bs));
561 for (
size_t i = num_block_dims + 1; i < input_shape.size(); i++) {
562 r_shape.push_back(input_shape[i]);
564 static_cast<int64_t
>(r_shape.size() - 1));
565 o_shape.push_back(input_shape[i]);
570 output =
reshape(output, o_shape);
588 const tvm::ffi::Array<int64_t>& block_shape,
589 const tvm::ffi::Array<tvm::PrimExpr>& crop_begin_list,
590 const tvm::ffi::Array<tvm::PrimExpr>& crop_end_list,
591 std::string name =
"batch_to_space_nd",
594 ffi::Array<PrimExpr> in_shape = data->shape;
595 ffi::Array<PrimExpr> r_shape;
596 ffi::Array<int64_t> axis;
597 size_t num_block_dims = block_shape.size();
598 size_t num_input_dims = in_shape.size();
600 int batch =
static_cast<int>(GetConstInt(in_shape[0]));
602 for (
size_t i = 0; i < num_block_dims; i++) {
604 r_shape.push_back(bs);
605 block_shape_prod *= bs;
607 axis.push_back(
static_cast<int64_t
>(r_shape.size()));
608 r_shape.push_back(batch / block_shape_prod);
610 for (
size_t i = 1; i < num_input_dims; i++) {
611 axis.push_back(
static_cast<int64_t
>(r_shape.size()));
612 if (axis.size() < (num_block_dims + num_input_dims)) {
614 static_cast<int64_t
>(r_shape.size() - (num_block_dims + 1)));
616 r_shape.push_back(in_shape[i]);
619 ffi::Array<PrimExpr> r_p_shape;
620 r_p_shape.push_back(batch / block_shape_prod);
621 for (
size_t i = 1; i <= num_block_dims; i++) {
623 r_p_shape.push_back(in_shape[i] * bs);
625 for (
size_t i = num_block_dims + 1; i < num_input_dims; i++) {
626 r_p_shape.push_back(in_shape[i]);
635 ffi::Array<ffi::Optional<IntImm>> begin_idx, end_idx;
636 ffi::Array<IntImm> strides;
638 for (
size_t i = 0; i < r_p_shape.size(); ++i) {
639 strides.push_back(
IntImm(index_ty, 1));
640 if (i > 0 && i <= num_block_dims) {
642 int64_t begin_i = GetConstInt(crop_begin_list[i - 1]);
643 int64_t end_i = GetConstInt(crop_end_list[i - 1]);
644 int64_t out_i = GetConstInt(r_p_shape[i]);
645 TVM_FFI_ICHECK_GT(out_i, (begin_i + end_i))
646 <<
"Incorrect crop sizes for (" << i <<
")th dim, can not crop more than"
647 <<
" output size" << out_i <<
" vs " << (begin_i + end_i);
648 begin_idx.push_back(
IntImm(index_ty, begin_i));
649 end_idx.push_back(
IntImm(index_ty, out_i - end_i));
652 begin_idx.push_back(
IntImm(index_ty, 0));
653 end_idx.push_back(
IntImm(index_ty, GetConstInt(r_p_shape[i])));
675 std::string reduction =
"mean",
int ignore_index = -100,
676 const std::string name =
"nll_loss",
const std::string tag =
kBroadcast) {
677 if (predictions.ndim() == 1) {
682 [&](
const tvm::ffi::Array<tvm::tirx::PrimVar>& target_indices) {
688 if (reduction ==
"mean") {
691 [&](
const tvm::ffi::Array<tvm::tirx::PrimVar>& target_indices) {
704 [&](
const tvm::ffi::Array<tvm::tirx::PrimVar>& target_indices) {
705 auto c = targets(target_indices);
706 tvm::ffi::Array<tvm::PrimExpr> pred_indices;
707 pred_indices.push_back(target_indices[0]);
708 pred_indices.push_back(c);
709 for (size_t i = 1; i < target_indices.size(); i++) {
710 pred_indices.push_back(target_indices[i]);
712 return tvm::tirx::Select(c != ignore_index, -predictions(pred_indices) * weights(c),
716 TVM_FFI_ICHECK(T->shape.size() != 0);
717 if (reduction ==
"mean") {
720 [&](
const tvm::ffi::Array<tvm::tirx::PrimVar>& target_indices) {
721 auto c = targets(target_indices);
722 return tvm::tirx::Select(c != ignore_index, weights(c),
723 tvm::tirx::MakeConst(tvm::PrimType(predictions->dtype), 0));
727 topi::sum(W, tvm::ffi::Array<int64_t>(
nullptr)));
728 }
else if (reduction ==
"sum") {
729 return topi::sum(T, tvm::ffi::Array<int64_t>(
nullptr));
Algebra expression simplifications.
Managed reference class to IntImmNode.
Definition: expr.h:378
static IntImm Bool(bool value, Span span=Span())
Construct a scalar boolean constant.
Definition: expr.h:393
static IntImm Int64(int64_t value, Span span=Span())
Construct a scalar int64 constant.
Definition: expr.h:411
Typed reference/view over any Expr whose ExprNode::ty is PrimType.
Definition: base_expr.h:354
Definition: base_expr.h:113
static PrimType Int(int bits, int lanes=1)
Construct a signed integer type with fixed lanes.
Range container
Definition: expr.h:484
Definition: source_map.h:111
Managed reference to AnalyzerObj.
Definition: analyzer.h:913
Managed Tensor. The array is backed by reference counted blocks.
Definition: tensor.h:49
Tensor structure representing a possible input, or intermediate computation result.
Definition: tensor.h:100
Checked scalar view over a VarNode.
Definition: var.h:127
Managed reference to SelectNode.
Definition: expr.h:526
Utility functions for handling constants in TVM expressions.
Tensor expression language DSL.
Definition: extracted_task.h:32
IterVar reduce_axis(Range dom, std::string name="rv")
Create a new IterVar for reduction operations.
Tensor compute(ffi::Array< PrimExpr > shape, FCompute fcompute, std::string name="tensor", std::string tag="", ffi::Map< ffi::String, ffi::Any > attrs={})
Construct a new tensor by computing over shape, using the computation rule: result_tensor[axis] = fco...
PrimExpr foldl(FReduce freduce, PrimExpr init_value, const ffi::Array< PrimExpr > &values, Span span=Span())
Left fold.
Definition: op.h:913
PrimExpr MakeConst(PrimType dtype, ValueType value, Span span=Span())
Make a const value with certain data type.
Definition: op.h:1012
Tensor sum(const Tensor &data, const ffi::Optional< ffi::Array< int64_t >> &axis, bool keepdims=false, bool atleast1d=false)
Creates an operation that sums array elements over a given axis.
Definition: reduction.h:337
constexpr auto kElementWise
Definition: tags.h:32
Tensor transpose(const Tensor &x, ffi::Optional< ffi::Array< int64_t >> opt_axes, std::string name="T_transpose", std::string tag=kInjective)
Permute the dimensions of an array.
Definition: transform.h:205
Tensor reshape(const Tensor &x, ffi::Array< PrimExpr > newshape, std::string name="T_reshape", std::string tag=kInjective)
Reshape a tensor.
Definition: transform.h:329
Tensor shape(const Tensor &src, PrimType dtype, const std::string name="T_shape", const std::string tag=kInjective)
Get the shape of input tensor.
Definition: transform.h:2010
tvm::te::Tensor batch_to_space_nd(const tvm::te::Tensor &data, const tvm::ffi::Array< int64_t > &block_shape, const tvm::ffi::Array< tvm::PrimExpr > &crop_begin_list, const tvm::ffi::Array< tvm::PrimExpr > &crop_end_list, std::string name="batch_to_space_nd", std::string tag=kInjective)
Reshape the batch dimension into spatial dimensions.
Definition: nn.h:587
constexpr auto kBroadcast
Definition: tags.h:36
constexpr auto kInjective
Definition: tags.h:33
constexpr auto kConv2dNCHW
Definition: tags.h:38
tvm::te::Tensor prelu(const tvm::te::Tensor &x, const tvm::te::Tensor &slope, const int axis=1, std::string name="T_prelu", std::string tag=kBroadcast)
Creates an operation that performs a parametric rectified linear unit.
Definition: nn.h:100
tvm::te::Tensor group_conv2d_ngchw(const tvm::te::Tensor &I, const tvm::te::Tensor &W, int pad_h=0, int pad_w=0, int stride_h=1, int stride_w=1, std::string name="T_group_conv2d_ngchw", std::string tag=kGroupConv2d)
Creates an operation that performs a 2-D group convolution with an NGCHW-layout.
Definition: nn.h:440
tvm::te::Tensor leaky_relu(const tvm::te::Tensor &t, double alpha=0.1, std::string name="T_leaky_relu", std::string tag=kElementWise)
Creates an operation that performs a leaky rectified linear unit.
Definition: nn.h:76
tvm::PrimExpr divide(const tvm::PrimExpr &a, const tvm::PrimExpr &b)
Definition: broadcast.h:241
constexpr auto kDepthwiseConv2dNCHW
Definition: tags.h:40
tvm::te::Tensor space_to_batch_nd(const tvm::te::Tensor &data, const tvm::ffi::Array< int64_t > &block_shape, const tvm::ffi::Array< tvm::PrimExpr > &pad_before, const tvm::ffi::Array< tvm::PrimExpr > &pad_after, PrimExpr pad_value=PrimExpr(), std::string name="space_to_batch_nd", std::string tag=kInjective)
Divide spatial dimensions of the input into a grid of blocks.
Definition: nn.h:488
tvm::te::Tensor depthwise_conv2d_nchw(const tvm::te::Tensor &I, const tvm::te::Tensor &W, int pad_h=0, int pad_w=0, int stride_h=1, int stride_w=1, std::string name="T_depthwise_conv2d_nchw", std::string tag=kDepthwiseConv2dNCHW)
Creates an operation that performs a 2-D depthwise convolution with an NCHW-layout.
Definition: nn.h:360
constexpr auto kGroupConv2d
Definition: tags.h:45
tvm::te::Tensor pad(const tvm::te::Tensor &t, const tvm::ffi::Array< tvm::PrimExpr > &pad_before, tvm::ffi::Array< tvm::PrimExpr > pad_after=tvm::ffi::Array< tvm::PrimExpr >(), PrimExpr pad_value=PrimExpr(), std::string name="T_pad", std::string tag=kElementWise, std::string pad_mode="constant", const ffi::Array< PrimExpr > *dyn_output_shape=nullptr)
Creates an operation that performs padding.
Definition: nn.h:156
constexpr auto kConv2dHWCN
Definition: tags.h:39
constexpr auto kDepthwiseConv2dNHWC
Definition: tags.h:41
tvm::te::Tensor conv2d_nchw(const tvm::te::Tensor &I, const tvm::te::Tensor &W, int pad_h=0, int pad_w=0, int stride_h=1, int stride_w=1, std::string name="T_conv2d_nchw", std::string tag=kConv2dNCHW)
Creates an operation that performs a 2-D convolution with an NCHW-layout.
Definition: nn.h:270
tvm::te::Tensor conv2d_hwcn(const tvm::te::Tensor &I, const tvm::te::Tensor &W, int pad_h=0, int pad_w=0, int stride_h=1, int stride_w=1, std::string name="T_conv2d_hwcn", std::string tag=kConv2dHWCN)
Creates an operation for 2-D convolution layer with an HWCN-layout.
Definition: nn.h:315
Tensor strided_slice(const Tensor &x, const ffi::Array< ffi::Optional< IntImm >> &begin, const ffi::Array< ffi::Optional< IntImm >> &end, const ffi::Array< IntImm > &strides, std::string slice_mode="end", std::string name="T_strided_slice", std::string tag=kInjective)
strided_slice of a tensor
Definition: transform.h:965
tvm::te::Tensor relu(const tvm::te::Tensor &t, T threshold=static_cast< T >(0), std::string name="T_relu", std::string tag=kElementWise)
Creates an operation that performs a rectified linear unit.
Definition: nn.h:55
Tensor nll_loss(const Tensor &predictions, const Tensor &targets, const Tensor &weights, std::string reduction="mean", int ignore_index=-100, const std::string name="nll_loss", const std::string tag=kBroadcast)
Negative log likelihood loss.
Definition: nn.h:674
tvm::te::Tensor depthwise_conv2d_nhwc(const tvm::te::Tensor &I, const tvm::te::Tensor &W, int pad_h=0, int pad_w=0, int stride_h=1, int stride_w=1, std::string name="T_depthwise_conv2d_nhwc", std::string tag=kDepthwiseConv2dNHWC)
Definition: nn.h:390
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition: analyzer.h:40
PrimExpr div(PrimExpr a, PrimExpr b, Span span=Span())
compute division in C semantics.
PrimExpr logical_and(PrimExpr a, PrimExpr b, Span span=Span())
and
PrimExpr if_then_else(PrimExpr cond, PrimExpr true_value, PrimExpr false_value, Span span=Span())
Conditional expression.
PrimExpr cast(PrimType t, PrimExpr value, Span span=Span())
cast value to type.
PrimExpr indexdiv(PrimExpr a, PrimExpr b, Span span=Span())
compute floor(a / b) where a and b are non-negative.
PrimExpr sum(PrimExpr source, ffi::Array< tirx::IterVar > axis, ffi::Array< PrimExpr > init={}, Span span=Span())
sum of source expression over axis
PrimExpr indexmod(PrimExpr a, PrimExpr b, Span span=Span())
compute the remainder floor(a / b) where a and b are non-negative.
Operation node can generate one or multiple Tensors.
Reduction op constructors.
Common operators defined for Expr.