File: grouped_reduction.cpp

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (210 lines) | stat: -rw-r--r-- 7,275 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
68
69
70
71
72
73
74
75
76
77
78
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
141
142
143
144
145
146
147
148
149
150
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#include <torch/csrc/jit/codegen/cuda/ir_builder.h>
#include <torch/csrc/jit/codegen/cuda/ir_utils.h>
#include <torch/csrc/jit/codegen/cuda/root_domain_map.h>
#include <torch/csrc/jit/codegen/cuda/transform_iter.h>

#include <torch/csrc/jit/codegen/cuda/grouped_reduction.h>

namespace torch {
namespace jit {
namespace fuser {
namespace cuda {

namespace {

// Return if ref and other are transformed in the same way.
bool hasMatchingTransformations(TensorView* ref, TensorView* other) {
  std::unordered_map<IterDomain*, IterDomain*> ref_2_other;
  for (const auto i : c10::irange(ref->getRootDomain().size())) {
    ref_2_other.emplace(
        ref->getRootDomain().at(i), other->getRootDomain().at(i));
  }

  auto replay =
      BestEffortReplay(
          other->domain()->domain(), ref->domain()->domain(), ref_2_other)
          .getReplay();

  for (const auto i : c10::irange(ref->nDims())) {
    auto ref_id = ref->axis(i);
    auto other_id = other->axis(i);
    auto it = replay.find(ref_id);
    if (it == replay.end() || it->second != other_id) {
      return false;
    }
  }

  return true;
}

// Validate grouping of reductions and return a new max producer position
unsigned int validateReductionGrouping(
    const std::vector<Val*>& inputs,
    const std::vector<Val*>& outputs) {
  TORCH_INTERNAL_ASSERT(inputs.size() == outputs.size());
  TORCH_INTERNAL_ASSERT(!inputs.empty());

  auto fusion = dynamic_cast<Fusion*>(outputs[0]->container());
  TORCH_INTERNAL_ASSERT(
      fusion != nullptr, "Grouping of reductions must be done within a Fusion");

  ExactRootDomainMap exact_map(fusion);

  // Pick the first output TV as a reference and compare it with the
  // rest. Do not allow grouping if any mismatch is detected.
  auto ref_tv = outputs[0]->as<TensorView>();
  const auto ref_domain = ref_tv->getRootDomain();
  const auto num_root_dims = ref_domain.size();
  const auto num_dims = ref_tv->nDims();
  const auto ref_ca_pos = ref_tv->getComputeAtPosition();
  auto max_producer_pos = ref_tv->getMaxProducerPosition();
  for (const auto i : c10::irange(inputs.size())) {
    auto output_tv = outputs.at(i)->as<TensorView>();
    const auto& output_domain = output_tv->getRootDomain();
    if (ref_tv == output_tv) {
      continue;
    }
    TORCH_INTERNAL_ASSERT(
        output_domain.size() == num_root_dims,
        "Invalid grouped reduction due to mismatched number of root dimensions. "
        "Expected: ",
        num_root_dims,
        ". Detected: ",
        output_domain.size(),
        ". Invalid output tensor: ",
        output_tv->toString());
    TORCH_INTERNAL_ASSERT(
        output_tv->nDims() == num_dims,
        "Invalid grouped reduction due to mismatched number of dimensions. "
        "Expected: ",
        num_dims,
        ". Detected: ",
        output_tv->nDims(),
        ". Invalid output tensor: ",
        output_tv->toString());
    for (const auto i : c10::irange(num_root_dims)) {
      auto ref_id = ref_domain.at(i);
      auto output_id = output_domain.at(i);
      // If an IterDomain is broadcast, require the other
      // corresponding IterDomains are also broadcast. This may not be
      // necessary but not completely certain.
      TORCH_INTERNAL_ASSERT(
          ref_id->isBroadcast() == output_id->isBroadcast(),
          "Invalid grouped reduction due to mismatched broadcast root domains. ",
          "Reference domain: ",
          ref_id->toString(),
          ". Mismatched domain: ",
          output_id->toString(),
          ". Invalid tensor: ",
          output_tv->toString());
      if (ref_id->isBroadcast()) {
        continue;
      }
      TORCH_INTERNAL_ASSERT(
          ref_id->isReduction() == output_id->isReduction(),
          "Invalid grouped reduction due to mismatched reduction root domains. ",
          "Reference domain: ",
          ref_id->toString(),
          ". Mismatched domain: ",
          output_id->toString(),
          ". Invalid tensor: ",
          output_tv->toString());
      TORCH_INTERNAL_ASSERT(
          exact_map.areMapped(ref_id, output_id) || ref_id->sameAs(output_id),
          "Invalid grouped reduction due to mismatched root domains. ",
          "Reference domain: ",
          ref_id->toString(),
          ". Mismatched domain: ",
          output_id->toString(),
          ". Invalid tensor: ",
          output_tv->toString());
    }

    TORCH_INTERNAL_ASSERT(
        hasMatchingTransformations(ref_tv, output_tv),
        "Invalid grouped reduction due to mismatched transformations. ",
        "Reference tensor: ",
        ref_tv->toString(),
        ". Mismatched tensor: ",
        output_tv->toString());

    // Must have the same computeAt position
    TORCH_INTERNAL_ASSERT(
        output_tv->getComputeAtPosition() == ref_ca_pos,
        "Invalid grouped reduction due to mismatched computeAt position. ",
        "Reference tensor: ",
        ref_tv->toString(),
        ". Mismatched tensor: ",
        output_tv->toString());

    max_producer_pos =
        std::max(max_producer_pos, output_tv->getMaxProducerPosition());
  }

  // Must not have any data dependency from outputs to inputs
  const auto all_dep_vals = DependencyCheck::getAllValsBetween(
      {outputs.begin(), outputs.end()}, inputs);
  if (!all_dep_vals.empty()) {
    std::stringstream ss;
    ss << "Invalid dependency:";
    for (auto val : all_dep_vals) {
      ss << " " << val->toString();
    }
    TORCH_INTERNAL_ASSERT(all_dep_vals.empty(), ss.str());
  }

  return max_producer_pos;
}

} // namespace

void groupReductions(const std::vector<TensorView*>& reduction_outputs) {
  TORCH_CHECK(!reduction_outputs.empty(), "No tensor is given");

  auto container = reduction_outputs[0]->container();

  const auto num_reductions = reduction_outputs.size();

  std::vector<BinaryOpType> op_types(num_reductions);
  std::vector<Val*> init_vals(num_reductions);
  std::vector<Val*> outputs(num_reductions);
  std::vector<Val*> inputs(num_reductions);

  for (const auto i : c10::irange(num_reductions)) {
    auto reduction_out = reduction_outputs.at(i);
    TORCH_CHECK(
        reduction_out->definition() != nullptr,
        "Invalid tensor to group: ",
        reduction_out->toString(),
        ". Definition not found");
    auto rop = dynamic_cast<ReductionOp*>(reduction_out->definition());
    TORCH_CHECK(
        rop != nullptr,
        "Invalid tensor to group: ",
        reduction_out->toString(),
        ". Not an output of a ReductionOp: ",
        reduction_out->definition()->toString());
    // Fused reduction is only enabled during the lowering, so at this
    // point it should be false.
    TORCH_INTERNAL_ASSERT(
        !rop->isAllreduce(), "Invalid ReductionOp: ", rop->toString());
    op_types.at(i) = rop->getReductionOpType();
    init_vals.at(i) = rop->init();
    outputs.at(i) = rop->out();
    inputs.at(i) = rop->in();
  }

  auto max_producer_pos = validateReductionGrouping(inputs, outputs);

  for (auto output : ir_utils::filterByType<TensorView>(outputs)) {
    output->setMaxProducer(max_producer_pos);
  }

  IrBuilder::create<GroupedReductionOp>(
      container, op_types, init_vals, outputs, inputs);
}

} // namespace cuda
} // namespace fuser
} // namespace jit
} // namespace torch