"src/nni_manager/git@developer.sourcefind.cn:OpenDAS/nni.git" did not exist on "ca2253c389a5739b0500c4ceb6015101113fe336"
loop_vectorize_dynamic.cc 18.3 KB
Newer Older
1
2
3
4
5
6
/*!
 * \file loop_vectorize_dynamic.cc
 * \brief A tool to automatically vectorize a for loop with dynamic shape
 * \brief Reference to loop_vectorize.cc and vectorize_loop.cc
 */

7
#include <cstdint>
8
#include <tvm/arith/iter_affine_map.h>
9
#include <tvm/ffi/reflection/registry.h>
10
#include <tvm/tir/builtin.h>
11
#include <tvm/tir/op.h>
12
13
14
#include <tvm/tir/stmt_functor.h>

#include <numeric>
15
#include <utility>
16
17
18

#include "../layout/layout.h"
#include "../layout/utils.h"
19
#include "../op/builtin.h"
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include "arith/int_operator.h"
#include "arith/ir_visitor_with_analyzer.h"
#include "common/loop_vectorization_utils.h"

namespace tvm {
namespace tl {

using namespace tir;
using arith::IRMutatorWithAnalyzer;

struct VectorizePlanResult {
  int vector_size;
  bool dynamic;
  PrimExpr condition;
};

36
37
bool IndiceCanVectorizeDynamic(const PrimExpr &expr, Var var,
                               const PrimExpr &iter_var_size,
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
                               int target_vectorized_size,
                               arith::Analyzer *analyzer) {
  ICHECK(target_vectorized_size >= 1);
  if (target_vectorized_size == 1)
    return true;
  if (!analyzer->CanProveEqual(FloorMod(iter_var_size, target_vectorized_size),
                               0))
    return false;
  Var v0("v0"), v1("v1");
  analyzer->Bind(v0, Range(0, target_vectorized_size));
  analyzer->Bind(v1, Range(0, FloorDiv(iter_var_size, target_vectorized_size)));
  PrimExpr expr_transformed = analyzer->Simplify(
      Substitute(expr, {{var, v0 + v1 * target_vectorized_size}}));

  Vectorizer vectorizer(v0, IntImm(v0->dtype, target_vectorized_size));
  PrimExpr expr_vectorized = vectorizer.VisitExpr(expr_transformed);
  auto ramp_node = expr_vectorized.as<RampNode>();
  if (!ramp_node) {
    // Broadcast value
    if (expr_vectorized.dtype().lanes() == 1)
      return true;
    else
      return false;
  } else {
    return is_one(ramp_node->stride);
  }
}

class VectorizePlannerDynamic : public arith::IRVisitorWithAnalyzer {
public:
68
69
70
71
72
73
74
75
76
77
78
  VectorizePlannerDynamic(int dynamic_alignment,
                          bool disable_dynamic_tail_split)
      : dynamic_alignment_(dynamic_alignment),
        disable_dynamic_tail_split_(disable_dynamic_tail_split),
        vector_load_bits_max_(128) {
    if (disable_dynamic_tail_split_) {
      vector_size_ = dynamic_alignment_;
    } else {
      vector_size_ = vector_load_bits_max_;
    }
  }
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140

  int Plan(const For &node) {
    this->operator()(node);
    // Always Enable vectorization
    // if (!has_nonlocal_memory_access_) return 1;
    return vector_size_;
  }

  bool GetDynamic() { return dynamic_; }

  PrimExpr GetCondition() { return condition_; }

private:
  void VisitStmt_(const ForNode *node) final {
    inner_for_ = node;
    iter_map_.Set(node->loop_var, Range(node->min, node->extent));
    arith::IRVisitorWithAnalyzer::VisitStmt_(node);
  }

  void VisitExpr_(const BufferLoadNode *node) final {
    if (node->buffer.scope() == "shared" || node->buffer.scope() == "global" ||
        node->buffer.scope() == "shared.dyn")
      has_nonlocal_memory_access_ = true;
    if (node->buffer->shape.size() == 1) {
      // TODO(lei): This should be improved as
      // constant buffer that tl hack to use as local register.
      auto boundary_check = node->buffer->shape[0].as<IntImmNode>();
      if (boundary_check && boundary_check->value == 1) {
        return arith::IRVisitorWithAnalyzer::VisitExpr_(node);
      }
    }
    UpdateVectorSize(node->indices, node->buffer);
    return arith::IRVisitorWithAnalyzer::VisitExpr_(node);
  }

  void VisitStmt_(const BufferStoreNode *node) final {
    if (node->buffer.scope() == "shared" || node->buffer.scope() == "global" ||
        node->buffer.scope() == "shared.dyn")
      has_nonlocal_memory_access_ = true;
    UpdateVectorSize(node->indices, node->buffer);
    return arith::IRVisitorWithAnalyzer::VisitStmt_(node);
  }

  void VisitStmt_(const IfThenElseNode *node) final {
    CheckConditionVectorized(node->condition);
    return arith::IRVisitorWithAnalyzer::VisitStmt_(node);
  }

  void VisitExpr_(const CallNode *node) final {
    if (node->op == builtin::if_then_else()) {
      CheckConditionVectorized(node->args[0]);
    } else if (node->op == builtin::call_extern()) {
      // do not vectorize extern calls
      vector_size_ = 1;
    }
    return arith::IRVisitorWithAnalyzer::VisitExpr_(node);
  }

  void CheckConditionVectorized(const PrimExpr &cond) {
    // TODO: may perform some checks here
  }

141
  void UpdateVectorSize(const Array<PrimExpr> &indices, const Buffer &buffer) {
142
143
144
145
146
147
148
149
150
    if (!inner_for_)
      return;
    auto extent_ptr = inner_for_->extent.as<IntImmNode>();
    if (!extent_ptr)
      return;

    const DataType &access_type = buffer->dtype;
    // i // 2, i % 8 can also be vectorized as factor 16
    int max_vector_size = vector_load_bits_max_ / access_type.bits();
151

152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
    // so we should disable this GCD optimization
    max_vector_size = arith::ZeroAwareGCD(max_vector_size, extent_ptr->value);

    auto last_dim = buffer->shape.back();
    auto mod_set = analyzer_.modular_set(last_dim);
    // when dynamic shape like [m, k]: coeff=1, base=0, GCD will block
    // conditionally tail vectorize
    if (buffer->shape.back().as<IntImmNode>()) {
      max_vector_size = arith::ZeroAwareGCD(max_vector_size, mod_set->coeff);

      auto gcd_base = arith::ZeroAwareGCD(max_vector_size, mod_set->base);
      // If gcd_base is equal to the last dimension,
      // we should analyze the second-to-last dimension
      // in relation to the last dimension.
      if (gcd_base < Downcast<IntImm>(last_dim)->value) {
        max_vector_size = gcd_base;
      }

      vector_size_ = arith::ZeroAwareGCD(max_vector_size, vector_size_);

      PrimExpr elem_offset = 0;
      PrimExpr stride = 1;
      for (int i = indices.size() - 1; i >= 0; --i) {
        elem_offset = elem_offset + indices[i] * stride;
        stride = stride * buffer->shape[i];
      }
      while (!IndiceCanVectorizeDynamic(elem_offset, inner_for_->loop_var,
                                        inner_for_->extent, vector_size_,
                                        &analyzer_)) {
        vector_size_ /= 2;
      }
183
    } else {
184
185
      // dynamic shape load: get the vectorization condition
      dynamic_ = true;
186
187
188
189
      if (!disable_dynamic_tail_split_ &&
          vector_size_ >= vector_load_bits_max_ / buffer->dtype.bits()) {
        vector_size_ = vector_load_bits_max_ / buffer->dtype.bits();
      }
190
191
192
193
194
195
      PrimExpr offset = buffer.OffsetOf(indices).back();
      // condition for alignment, maybe useless
      condition_ = (FloorMod(offset, vector_size_) == 0);
    }
  }

196
197
198
199
200
201
  // Use dynamic alignment from pass config
  int vector_load_bits_max_;
  int dynamic_alignment_;
  bool disable_dynamic_tail_split_;

  int vector_size_;
202

203
  const ForNode *inner_for_{};
204
205
206
207
208
209
210
211
212
213
214
  Map<Var, Range> iter_map_;
  bool has_nonlocal_memory_access_ = false;
  // conditionally vectorize
  bool dynamic_ = false;
  PrimExpr condition_;
};

class VectorizedBodyMutator : public StmtExprMutator {
public:
  VectorizedBodyMutator(Var inner_var, int vector_size,
                        std::vector<PrimExpr> conditions)
215
216
      : inner_var_(std::move(inner_var)), vector_size_(vector_size),
        conditions_(std::move(conditions)) {}
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

private:
  PrimExpr VisitExpr_(const CallNode *op) final {
    if (op->op.same_as(builtin::if_then_else())) {
      // TODO: Currently not ramp, but only reserve the "then" part (because
      // conditions are move outside this vectorized loop)
      PrimExpr ifexpr = op->args[0];
      PrimExpr thenexpr = op->args[1];
      bool flag = false;
      for (auto &cond : conditions_) {
        if (ifexpr.get() == cond.get()) {
          flag = true;
        }
      }
      if (flag) {
        return thenexpr;
      } else {
234
        return tvm::ffi::GetRef<PrimExpr>(op);
235
236
      }
    } else {
237
      return tvm::ffi::GetRef<PrimExpr>(op);
238
239
240
241
242
243
244
245
    }
  }

  Var inner_var_;
  int vector_size_;
  std::vector<PrimExpr> conditions_;
};

246
class VectorizedConditionExtractor : public StmtExprVisitor {
247
public:
248
  VectorizedConditionExtractor() = default;
249
  std::vector<PrimExpr> GetConditions(const Stmt &body) {
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    this->VisitStmt(body);
    return conditions_;
  }

private:
  void VisitExpr_(const CallNode *op) final {
    if (op->op.same_as(builtin::if_then_else())) {
      PrimExpr cond = op->args[0];
      conditions_.emplace_back(cond);
    }
    StmtExprVisitor::VisitExpr_(op);
  }

  void VisitStmt_(const IfThenElseNode *node) final {
    conditions_.emplace_back(node->condition);
    StmtExprVisitor::VisitStmt_(node);
  }

  std::vector<PrimExpr> conditions_;
};

271
272
273
// backward-compatibility: extracter -> extractor
using VectorizedConditionExtracter = VectorizedConditionExtractor;

274
275
276
class NestedLoopChecker : public StmtExprVisitor {
public:
  NestedLoopChecker() : loop_num_(0) {}
277
  int GetNestLoopNum(const Stmt &body) {
278
279
280
281
282
283
284
285
286
287
288
289
    this->VisitStmt(body);
    return loop_num_;
  }

private:
  void VisitStmt_(const ForNode *node) final {
    loop_num_++;
    StmtExprVisitor::VisitStmt_(node);
  }
  int loop_num_;
};

290
291
292
293
// Modify every subexpression in the condition
class VectorizedConditionMutator : public StmtExprMutator {
public:
  VectorizedConditionMutator(Var inner_var, int extent)
294
      : inner_var_(std::move(inner_var)), vector_size_(extent) {}
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348

private:
  PrimExpr VisitExpr_(const GENode *node) final {
    PrimExpr lhs = StmtExprMutator::VisitExpr(node->a);
    PrimExpr rhs = StmtExprMutator::VisitExpr(node->b);
    auto span = node->span;
    Map<Var, PrimExpr> vmap_lhs, vmap_rhs;
    vmap_lhs.Set(inner_var_, 0);
    PrimExpr lhs_bound = Substitute(lhs, vmap_lhs);
    vmap_rhs.Set(inner_var_, vector_size_ - 1);
    PrimExpr rhs_bound = Substitute(rhs, vmap_rhs);
    return GE(lhs_bound, rhs_bound, span);
  }

  PrimExpr VisitExpr_(const GTNode *node) final {
    PrimExpr lhs = StmtExprMutator::VisitExpr(node->a);
    PrimExpr rhs = StmtExprMutator::VisitExpr(node->b);
    auto span = node->span;
    Map<Var, PrimExpr> vmap_lhs, vmap_rhs;
    vmap_lhs.Set(inner_var_, 0);
    PrimExpr lhs_bound = Substitute(lhs, vmap_lhs);
    vmap_rhs.Set(inner_var_, vector_size_ - 1);
    PrimExpr rhs_bound = Substitute(rhs, vmap_rhs);
    return GT(lhs_bound, rhs_bound, span);
  }

  PrimExpr VisitExpr_(const LENode *node) final {
    PrimExpr lhs = StmtExprMutator::VisitExpr(node->a);
    PrimExpr rhs = StmtExprMutator::VisitExpr(node->b);
    auto span = node->span;
    Map<Var, PrimExpr> vmap_lhs, vmap_rhs;
    vmap_lhs.Set(inner_var_, vector_size_ - 1);
    PrimExpr lhs_bound = Substitute(lhs, vmap_lhs);
    vmap_rhs.Set(inner_var_, 0);
    PrimExpr rhs_bound = Substitute(rhs, vmap_rhs);
    return LE(lhs_bound, rhs_bound, span);
  }

  PrimExpr VisitExpr_(const LTNode *node) final {
    PrimExpr lhs = StmtExprMutator::VisitExpr(node->a);
    PrimExpr rhs = StmtExprMutator::VisitExpr(node->b);
    auto span = node->span;
    Map<Var, PrimExpr> vmap_lhs, vmap_rhs;
    vmap_lhs.Set(inner_var_, vector_size_ - 1);
    PrimExpr lhs_bound = Substitute(lhs, vmap_lhs);
    vmap_rhs.Set(inner_var_, 0);
    PrimExpr rhs_bound = Substitute(rhs, vmap_rhs);
    return LT(lhs_bound, rhs_bound, span);
  }

  Var inner_var_;
  int vector_size_;
};

349
350
class VectorizeRewriterDynamic : public StmtExprMutator {
public:
351
  VectorizeRewriterDynamic(const VectorizePlanResult &plan,
352
                           bool disable_dynamic_tail_split)
353
      : vector_size_(plan.vector_size), condition_(plan.condition),
354
355
        dynamic_(plan.dynamic),
        disable_dynamic_tail_split_(disable_dynamic_tail_split) {}
356
357
358

private:
  Stmt VisitStmt_(const ForNode *node) final {
359
360
361
362
363
364
365
    // Get pass config `tl.disable_dynamic_tail_split`
    tvm::transform::PassContext ctxt = tvm::transform::PassContext::Current();
    Optional<Bool> opt_disable_dynamic_tail_split =
        ctxt->GetConfig(kDisableDynamicTailSplit, Optional<Bool>());
    bool disable_dynamic_tail_split =
        opt_disable_dynamic_tail_split.value_or(Bool(false));

366
367
    inner_for_ = node;
    auto ret = StmtExprMutator::VisitStmt_(node);
368
    if (inner_for_ != node) {
369
370
      return ret;
    }
371
372
373
374
375
376
377
378
379
380
    For fnode = ret.as<For>().value();
    auto old_var = fnode->loop_var;
    if (!fnode->extent.as<IntImmNode>()) {
      return ret;
    }
    int extent = Downcast<IntImm>(fnode->extent)->value;

    if (!dynamic_) {
      return fnode;
    }
381
382
383
384
385
386
387

    if (!disable_dynamic_tail_split) {
      // To handle the fact that cp.async only support address aligned with
      // access size
      vector_size_ = 1;
    }

388
389
390
391
392
393
394
395
396
    ICHECK(extent % vector_size_ == 0)
        << "extent: " << extent << " vector_size_: " << vector_size_;
    ICHECK(is_zero(fnode->min));
    Var inner_var = Var("vec");
    Var outer_var = Var(old_var->name_hint);
    Map<Var, PrimExpr> vmap;
    vmap.Set(fnode->loop_var, outer_var * vector_size_ + inner_var);
    Stmt body = Substitute(fnode->body, vmap);

397
398
    VectorizedConditionExtractor extractor;
    std::vector<PrimExpr> conditions = extractor.GetConditions(body);
399

400
401
402
    VectorizedConditionMutator condition_mutator(inner_var, vector_size_);

    // Adaptively set vectorized variable to the min/max value of the extent
403
    PrimExpr condition_bound;
404
    if (!conditions.empty()) {
405
406
407
408
      condition_bound = condition_mutator(conditions[0]);
      for (int i = 1; i < conditions.size(); ++i) {
        condition_bound = condition_bound && condition_mutator(conditions[i]);
      }
409
410
    }

411
412
413
414
415
416
417
418
419
420
    if (!disable_dynamic_tail_split) {
      // If dynamic_tail_split is true, we will vectorize the loop with
      // if-then-else conditions modify body in the vectorized loop
      VectorizedBodyMutator mutator(inner_var, vector_size_, conditions);
      Stmt vectorize_body = mutator(body);

      // add condition ifthenelse here
      For vectorize_for =
          For(inner_var, 0, vector_size_, ForKind::kVectorized, vectorize_body);
      For serial_for = For(inner_var, 0, vector_size_, ForKind::kSerial, body);
421
      if (!conditions.empty()) {
422
423
424
425
        body = IfThenElse(condition_bound, vectorize_for, serial_for);
      } else {
        body = vectorize_for;
      }
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
      body = For(outer_var, 0, extent / vector_size_, fnode->kind, body,
                 fnode->thread_binding, fnode->annotations, fnode->span);
      return body;
    } else {
      // If dynamic_tail_split is false, we will directly vectorize the loop
      // without dynamic tail split and if_then_else, which may lead to error
      VectorizedBodyMutator mutator(inner_var, vector_size_, conditions);
      Stmt vectorize_body = mutator(body);

      For vectorize_for =
          For(inner_var, 0, vector_size_, ForKind::kVectorized, vectorize_body);
      body =
          For(outer_var, 0, extent / vector_size_, fnode->kind, vectorize_for,
              fnode->thread_binding, fnode->annotations, fnode->span);
      return body;
    }
442
443
  }

444
  const ForNode *inner_for_{};
445
  int vector_size_;
446
447
  const PrimExpr condition_;
  const bool dynamic_;
448
  const bool disable_dynamic_tail_split_;
449
450
};

451
452
453
454
455
VectorizePlanResult
GetVectorizePlanResultDynamic(const For &loop, int dynamic_alignment,
                              bool disable_dynamic_tail_split) {
  VectorizePlannerDynamic planner(dynamic_alignment,
                                  disable_dynamic_tail_split);
456
457
458
459
460
461
462
463
  int vector_size = planner.Plan(loop);
  bool dynamic = planner.GetDynamic();
  PrimExpr condition = planner.GetCondition();
  return {vector_size, dynamic, condition};
}

class LoopVectorizerDynamic : public IRMutatorWithAnalyzer {
public:
464
465
  static Stmt Substitute(Stmt stmt, bool disable_dynamic_tail_split,
                         int dynamic_alignment) {
466
    arith::Analyzer analyzer;
467
468
    LoopVectorizerDynamic substituter(&analyzer, disable_dynamic_tail_split,
                                      dynamic_alignment);
469
470
471
472
473
    stmt = substituter.VisitStmt(stmt);
    return stmt;
  }

private:
474
475
476
477
478
  LoopVectorizerDynamic(arith::Analyzer *analyzer,
                        bool disable_dynamic_tail_split, int dynamic_alignment)
      : arith::IRMutatorWithAnalyzer(analyzer),
        disable_dynamic_tail_split_(disable_dynamic_tail_split),
        dynamic_alignment_(dynamic_alignment) {}
479
480
481

  Stmt VisitStmt_(const ForNode *op) final {
    For for_node = Downcast<For>(IRMutatorWithAnalyzer::VisitStmt_(op));
482
483
484
    VectorizePlanResult res{vector_load_bits_max_, false, 0};
    res = GetVectorizePlanResultDynamic(for_node, dynamic_alignment_,
                                        disable_dynamic_tail_split_);
485
486
    NestedLoopChecker checker;
    int nest_num = checker.GetNestLoopNum(for_node);
487
488
489
    if (nest_num > 1 ||
        for_node->kind == ForKind::kVectorized) { // only rewrite the innermost
                                                  // non-vectorized loop
490
491
      return for_node;
    }
492
    auto rewriter = VectorizeRewriterDynamic(res, disable_dynamic_tail_split_);
493
494
    return Downcast<For>(rewriter(for_node));
  }
495
496
497
498

  const int vector_load_bits_max_ = 128;
  int dynamic_alignment_;
  bool disable_dynamic_tail_split_;
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
};

class VectorizeSkipperDynamic : public StmtMutator {
public:
  Stmt VisitStmt_(const ForNode *op) final {
    Stmt stmt = StmtMutator::VisitStmt_(op);
    op = stmt.as<ForNode>();
    if (op->kind == ForKind::kVectorized) {
      return For(op->loop_var, op->min, op->extent, ForKind::kSerial, op->body);
    } else {
      return stmt;
    }
  }
};

tvm::transform::Pass LoopVectorizeDynamic() {
  using namespace tir::transform;
516
  auto pass_func = [=](PrimFunc f, const IRModule &m, PassContext ctx) {
517
518
519
520
521
522
523
524
525
526
527
528
    bool disable_dynamic_tail_split =
        ctx->GetConfig<Bool>(kDisableDynamicTailSplit, Bool(true)).value();
    int dynamic_alignment =
        (int)(ctx->GetConfig<Integer>(kDynamicAlignment, Integer(8))
                  .value_or(Integer(8))
                  ->value);
    // Ensure tl.dynamic_alignment is a power of 2
    if (disable_dynamic_tail_split &&
        ((dynamic_alignment & (dynamic_alignment - 1)) != 0)) {
      LOG(FATAL) << "tl.dynamic_alignment must be a power of 2, but got "
                 << dynamic_alignment;
    }
529
    auto *n = f.CopyOnWrite();
530
531
    n->body = LoopVectorizerDynamic::Substitute(
        std::move(n->body), disable_dynamic_tail_split, dynamic_alignment);
532
533
534
535
536
537
    return f;
  };
  return CreatePrimFuncPass(pass_func, 0, "tl.LoopVectorizeDynamic", {});
}

// Register the pass globally so it can be used in the compilation pipeline
538
TVM_FFI_STATIC_INIT_BLOCK() {
539
540
541
  namespace refl = tvm::ffi::reflection;
  refl::GlobalDef().def("tl.transform.LoopVectorizeDynamic",
                        LoopVectorizeDynamic);
542
}
543
544
545

} // namespace tl
} // namespace tvm