Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
211
212
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
245
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
/*++
 
Module Name:
 
    test_snchwc_partition.cpp
 
Abstract:
 
    Tests the cost-to-work-index mapping used by the NCHWc grouped convolution
    algorithms to partition work proportionally to FLOP cost.
 
    The mapping is exercised directly rather than through a convolution so that
    the two properties the partitioning depends on -- exact tiling of the work
    space, and balanced cost per thread -- can be asserted across shapes that
    would be expensive to convolve.
 
--*/
 
#include <gtest/gtest.h>
 
#include <algorithm>
#include <vector>
 
#include "core/mlas/lib/mlasi.h"
 
namespace {
 
//
// Mirrors the derived quantities computed by MLAS_NCHWC_GROUPED_CONV_ALGORITHM
// and PrepareWorkWeighted for a given convolution shape.
//
 
struct PartitionShape {
  size_t BlockSize;
  size_t FilterSetSize;
  size_t OutputChannels;
  size_t OutputHeight;
  size_t BatchGroupCount;  // BatchCount * GroupCount
 
  size_t TotalBlockedFilters() const { return OutputChannels / BlockSize; }
 
  size_t FilterSetCount() const {
    return (OutputChannels + (BlockSize * FilterSetSize) - 1) / (BlockSize * FilterSetSize);
  }
 
  size_t LastSetFilterCount() const {
    return TotalBlockedFilters() - (FilterSetCount() - 1) * FilterSetSize;
  }
 
  size_t TotalCost() const { return BatchGroupCount * TotalBlockedFilters() * OutputHeight; }
 
  size_t TotalWork() const { return BatchGroupCount * FilterSetCount() * OutputHeight; }
 
  size_t CostToWorkIndex(size_t Cost) const {
    return MlasNchwcCostToWorkIndex(Cost, OutputHeight, FilterSetCount(), FilterSetSize,
                                    TotalBlockedFilters(), LastSetFilterCount());
  }
 
  //
  // Cost of a single work item: items of the ragged last filter set of each
  // (batch, group) segment cost less than items of full sets.
  //
 
  size_t WorkItemCost(size_t WorkIndex) const {
    const size_t Set = (WorkIndex / OutputHeight) % FilterSetCount();
    return (Set + 1 == FilterSetCount()) ? LastSetFilterCount() : FilterSetSize;
  }
 
  size_t RangeCost(size_t Begin, size_t End) const {
    size_t Cost = 0;
    for (size_t i = Begin; i < End; i++) {
      Cost += WorkItemCost(i);
    }
    return Cost;
  }
 
  std::string Describe() const {
    return "OutputChannels=" + std::to_string(OutputChannels) +
           " OutputHeight=" + std::to_string(OutputHeight) +
           " BatchGroupCount=" + std::to_string(BatchGroupCount) +
           " FilterSetCount=" + std::to_string(FilterSetCount()) +
           " LastSetFilterCount=" + std::to_string(LastSetFilterCount());
  }
};
 
//
// The shape grid. Output channel counts are chosen to cover every ragged tail
// the mapping has to handle: 16 and 32 are shorter than one filter set, 64 and
// 256 divide evenly, and 48/96/144/208 leave last sets of 3, 2, 1 and 1 blocks.
//
 
std::vector<PartitionShape> AllShapes() {
  const size_t OutputChannelValues[] = {16, 32, 48, 64, 96, 144, 208, 256};
  const size_t OutputHeightValues[] = {1, 2, 7, 13, 52};
  const size_t BatchGroupValues[] = {1, 2, 8};
 
  std::vector<PartitionShape> Shapes;
 
  for (size_t OutputChannels : OutputChannelValues) {
    for (size_t OutputHeight : OutputHeightValues) {
      for (size_t BatchGroupCount : BatchGroupValues) {
        Shapes.push_back(PartitionShape{16, 4, OutputChannels, OutputHeight, BatchGroupCount});
      }
    }
  }
 
  return Shapes;
}
 
const ptrdiff_t ThreadCounts[] = {1, 2, 3, 4, 5, 8, 16, 32};
 
}  // namespace
 
//
// Partitioning a cost interval and converting both endpoints must produce work
// ranges that exactly tile [0, TotalWork): no gap, no overlap, nothing dropped.
// The convolution's correctness rests entirely on this property -- a gap would
// silently leave output rows uncomputed.
//
 
TEST(SnchwcPartition, RangesTileWorkSpace) {
  for (const PartitionShape& Shape : AllShapes()) {
    for (ptrdiff_t tids : ThreadCounts) {
      size_t Expected = 0;
 
      for (ptrdiff_t Index = 0; Index < tids; Index++) {
        size_t CostStart;
        size_t CostCount;
        MlasPartitionWork(Index, tids, Shape.TotalCost(), &CostStart, &CostCount);
 
        const size_t Begin = Shape.CostToWorkIndex(CostStart);
        const size_t End = Shape.CostToWorkIndex(CostStart + CostCount);
 
        ASSERT_LE(Begin, End) << Shape.Describe() << " tids=" << tids << " Index=" << Index;
        ASSERT_EQ(Begin, Expected) << "gap or overlap; " << Shape.Describe()
                                   << " tids=" << tids << " Index=" << Index;
        Expected = End;
      }
 
      ASSERT_EQ(Expected, Shape.TotalWork())
          << "work space not fully covered; " << Shape.Describe() << " tids=" << tids;
    }
  }
}
 
//
// The mapping must be monotone and bounded over the whole cost domain, which is
// what lets the tiling above hold for any partition MlasPartitionWork produces.
//
 
TEST(SnchwcPartition, MonotoneAndBounded) {
  for (const PartitionShape& Shape : AllShapes()) {
    size_t Previous = 0;
 
    for (size_t Cost = 0; Cost <= Shape.TotalCost(); Cost++) {
      const size_t WorkIndex = Shape.CostToWorkIndex(Cost);
 
      ASSERT_GE(WorkIndex, Previous) << "not monotone at Cost=" << Cost << "; " << Shape.Describe();
      ASSERT_LE(WorkIndex, Shape.TotalWork())
          << "out of bounds at Cost=" << Cost << "; " << Shape.Describe();
 
      Previous = WorkIndex;
    }
 
    ASSERT_EQ(Shape.CostToWorkIndex(0), size_t{0}) << Shape.Describe();
    ASSERT_EQ(Shape.CostToWorkIndex(Shape.TotalCost()), Shape.TotalWork()) << Shape.Describe();
  }
}
 
//
// The point of the weighted split: each thread's share of the actual work --
// measured in block-rows, not work items -- must land near TotalCost/tids.
// A uniform split by work index fails this whenever the last filter set is
// ragged, which is the regression this guards.
//
 
TEST(SnchwcPartition, CostIsBalancedAcrossThreads) {
  for (const PartitionShape& Shape : AllShapes()) {
    for (ptrdiff_t tids : ThreadCounts) {
      if (Shape.TotalCost() < static_cast<size_t>(tids)) {
        continue;  // covered by EmptyPartitionsAreWellFormed
      }
 
      const size_t Ideal = Shape.TotalCost() / static_cast<size_t>(tids);
 
      //
      // A thread's range boundary can only fall on a work item, so its cost can
      // deviate from ideal by at most the cost of one item at each end.
      //
 
      const size_t Tolerance = 2 * Shape.FilterSetSize;
 
      for (ptrdiff_t Index = 0; Index < tids; Index++) {
        size_t CostStart;
        size_t CostCount;
        MlasPartitionWork(Index, tids, Shape.TotalCost(), &CostStart, &CostCount);
 
        const size_t Begin = Shape.CostToWorkIndex(CostStart);
        const size_t End = Shape.CostToWorkIndex(CostStart + CostCount);
        const size_t ActualCost = Shape.RangeCost(Begin, End);
 
        const size_t Deviation = (ActualCost > Ideal) ? (ActualCost - Ideal) : (Ideal - ActualCost);
 
        ASSERT_LE(Deviation, Tolerance)
            << "thread " << Index << " of " << tids << " got " << ActualCost
            << " block-rows, ideal " << Ideal << "; " << Shape.Describe();
      }
    }
  }
}
 
//
// When there is less cost than there are threads, the surplus threads receive an
// empty interval starting at TotalCost. That must map to TotalWork so the caller
// computes WorkRemaining == 0 and skips SeekToWork -- seeking to TotalWork would
// advance the convolution buffer pointers past the end of their tensors.
//
 
TEST(SnchwcPartition, EmptyPartitionsAreWellFormed) {
  for (const PartitionShape& Shape : AllShapes()) {
    for (ptrdiff_t tids : ThreadCounts) {
      if (Shape.TotalCost() >= static_cast<size_t>(tids)) {
        continue;
      }
 
      bool SawEmpty = false;
 
      for (ptrdiff_t Index = 0; Index < tids; Index++) {
        size_t CostStart;
        size_t CostCount;
        MlasPartitionWork(Index, tids, Shape.TotalCost(), &CostStart, &CostCount);
 
        const size_t Begin = Shape.CostToWorkIndex(CostStart);
        const size_t End = Shape.CostToWorkIndex(CostStart + CostCount);
 
        if (CostCount == 0) {
          SawEmpty = true;
          ASSERT_EQ(Begin, End) << "empty cost interval produced work; " << Shape.Describe()
                                << " tids=" << tids << " Index=" << Index;
          ASSERT_LE(Begin, Shape.TotalWork())
              << "empty partition seeks out of bounds; " << Shape.Describe()
              << " tids=" << tids << " Index=" << Index;
        }
      }
 
      ASSERT_TRUE(SawEmpty) << "expected surplus threads; " << Shape.Describe()
                            << " tids=" << tids;
    }
  }
}
 
//
// The worked example from the mapping's documentation: 96 output channels give
// 6 blocked filters, so two filter sets costing 4 and 2 block-rows per output
// row. With 4 threads a uniform split by work index would hand two threads the
// 4-block set and two the 2-block set -- a 2x imbalance -- while the weighted
// split moves the boundary into the cheaper set to even the cost out.
//
 
TEST(SnchwcPartition, WorkedExampleFromDocumentation) {
  const PartitionShape Shape{16, 4, 96, 52, 1};
 
  ASSERT_EQ(Shape.TotalBlockedFilters(), size_t{6});
  ASSERT_EQ(Shape.FilterSetCount(), size_t{2});
  ASSERT_EQ(Shape.LastSetFilterCount(), size_t{2});
  ASSERT_EQ(Shape.TotalCost(), size_t{6 * 52});
  ASSERT_EQ(Shape.TotalWork(), size_t{2 * 52});
 
  const ptrdiff_t tids = 4;
  const size_t Ideal = Shape.TotalCost() / tids;  // 78 block-rows
 
  size_t Worst = 0;
 
  for (ptrdiff_t Index = 0; Index < tids; Index++) {
    size_t CostStart;
    size_t CostCount;
    MlasPartitionWork(Index, tids, Shape.TotalCost(), &CostStart, &CostCount);
 
    const size_t ActualCost = Shape.RangeCost(Shape.CostToWorkIndex(CostStart),
                                              Shape.CostToWorkIndex(CostStart + CostCount));
    Worst = std::max(Worst, ActualCost);
  }
 
  //
  // Scheduling efficiency is Ideal/Worst. The uniform split gives 4*52/(2*52*... )
  // -- concretely, its worst thread takes 104 block-rows against an ideal of 78,
  // i.e. 75%. The weighted split must stay within one work item of ideal.
  //
 
  ASSERT_LE(Worst, Ideal + Shape.FilterSetSize)
      << "worst thread took " << Worst << " block-rows against ideal " << Ideal;
}