OmniSciDB  c07336695a
QueryMemoryDescriptor.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2018 MapD Technologies, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "QueryMemoryDescriptor.h"
18 
19 #include "../Execute.h"
20 #include "../ExpressionRewrite.h"
21 #include "../GroupByAndAggregate.h"
22 #include "../StreamingTopN.h"
23 #include "../UsedColumnsVisitor.h"
24 #include "ColSlotContext.h"
25 
27 extern bool g_enable_columnar_output;
28 
29 namespace {
30 
31 bool is_int_and_no_bigger_than(const SQLTypeInfo& ti, const size_t byte_width) {
32  if (!ti.is_integer()) {
33  return false;
34  }
35  return get_bit_width(ti) <= (byte_width * 8);
36 }
37 
38 std::vector<ssize_t> target_expr_group_by_indices(
39  const std::list<std::shared_ptr<Analyzer::Expr>>& groupby_exprs,
40  const std::vector<Analyzer::Expr*>& target_exprs) {
41  std::vector<ssize_t> indices(target_exprs.size(), -1);
42  for (size_t target_idx = 0; target_idx < target_exprs.size(); ++target_idx) {
43  const auto target_expr = target_exprs[target_idx];
44  if (dynamic_cast<const Analyzer::AggExpr*>(target_expr)) {
45  continue;
46  }
47  const auto var_expr = dynamic_cast<const Analyzer::Var*>(target_expr);
48  if (var_expr && var_expr->get_which_row() == Analyzer::Var::kGROUPBY) {
49  indices[target_idx] = var_expr->get_varno() - 1;
50  continue;
51  }
52  }
53  return indices;
54 }
55 
56 std::vector<ssize_t> target_expr_proj_indices(const RelAlgExecutionUnit& ra_exe_unit,
57  const Catalog_Namespace::Catalog& cat) {
58  if (ra_exe_unit.input_descs.size() > 1 ||
59  !ra_exe_unit.sort_info.order_entries.empty()) {
60  return {};
61  }
62  std::vector<ssize_t> target_indices(ra_exe_unit.target_exprs.size(), -1);
63  UsedColumnsVisitor columns_visitor;
64  std::unordered_set<int> used_columns;
65  for (const auto& simple_qual : ra_exe_unit.simple_quals) {
66  const auto crt_used_columns = columns_visitor.visit(simple_qual.get());
67  used_columns.insert(crt_used_columns.begin(), crt_used_columns.end());
68  }
69  for (const auto& qual : ra_exe_unit.quals) {
70  const auto crt_used_columns = columns_visitor.visit(qual.get());
71  used_columns.insert(crt_used_columns.begin(), crt_used_columns.end());
72  }
73  for (const auto& target : ra_exe_unit.target_exprs) {
74  const auto col_var = dynamic_cast<const Analyzer::ColumnVar*>(target);
75  if (col_var) {
76  const auto cd = get_column_descriptor_maybe(
77  col_var->get_column_id(), col_var->get_table_id(), cat);
78  if (!cd || !cd->isVirtualCol) {
79  continue;
80  }
81  }
82  const auto crt_used_columns = columns_visitor.visit(target);
83  used_columns.insert(crt_used_columns.begin(), crt_used_columns.end());
84  }
85  for (size_t target_idx = 0; target_idx < ra_exe_unit.target_exprs.size();
86  ++target_idx) {
87  const auto target_expr = ra_exe_unit.target_exprs[target_idx];
88  CHECK(target_expr);
89  const auto& ti = target_expr->get_type_info();
90  const bool is_real_str_or_array =
91  (ti.is_string() && ti.get_compression() == kENCODING_NONE) || ti.is_array();
92  if (is_real_str_or_array) {
93  continue;
94  }
95  if (ti.is_geometry()) {
96  // TODO(adb): Ideally we could determine which physical columns are required for a
97  // given query and fetch only those. For now, we bail on the memory optimization,
98  // since it is possible that adding the physical columns could have unintended
99  // consequences further down the execution path.
100  return {};
101  }
102  const auto col_var = dynamic_cast<const Analyzer::ColumnVar*>(target_expr);
103  if (!col_var) {
104  continue;
105  }
106  if (!is_real_str_or_array &&
107  used_columns.find(col_var->get_column_id()) == used_columns.end()) {
108  target_indices[target_idx] = 0;
109  }
110  }
111  return target_indices;
112 }
113 
115  if (range.getType() == ExpressionRangeType::Invalid) {
116  return sizeof(int64_t);
117  }
118  switch (range.getType()) {
120  return range.getIntMax() < EMPTY_KEY_32 - 1 ? sizeof(int32_t) : sizeof(int64_t);
123  return sizeof(int64_t); // No compaction for floating point yet.
124  default:
125  UNREACHABLE();
126  }
127  return sizeof(int64_t);
128 }
129 
130 // TODO(miyu): make sure following setting of compact width is correct in all cases.
132  const std::vector<InputTableInfo>& query_infos,
133  const Executor* executor) {
134  int8_t compact_width{4};
135  for (const auto groupby_expr : ra_exe_unit.groupby_exprs) {
136  const auto expr_range = getExpressionRange(groupby_expr.get(), query_infos, executor);
137  compact_width =
138  std::max(compact_width, pick_baseline_key_component_width(expr_range));
139  }
140  return compact_width;
141 }
142 
143 } // namespace
144 
145 std::unique_ptr<QueryMemoryDescriptor> QueryMemoryDescriptor::init(
146  const Executor* executor,
147  const RelAlgExecutionUnit& ra_exe_unit,
148  const std::vector<InputTableInfo>& query_infos,
149  const ColRangeInfo& col_range_info,
150  const KeylessInfo& keyless_info,
151  const bool allow_multifrag,
152  const ExecutorDeviceType device_type,
153  const int8_t crt_min_byte_width,
154  const bool sort_on_gpu_hint,
155  const size_t shard_count,
156  const size_t max_groups_buffer_entry_count,
157  RenderInfo* render_info,
158  const CountDistinctDescriptors count_distinct_descriptors,
159  const bool must_use_baseline_sort,
160  const bool output_columnar_hint) {
161  auto group_col_widths = get_col_byte_widths(ra_exe_unit.groupby_exprs, {});
162  const bool is_group_by{!group_col_widths.empty()};
163 
164  auto col_slot_context = ColSlotContext(ra_exe_unit.target_exprs, {});
165 
166  const auto min_slot_size = QueryMemoryDescriptor::pick_target_compact_width(
167  ra_exe_unit, query_infos, crt_min_byte_width);
168 
169  col_slot_context.setAllSlotsPaddedSize(min_slot_size);
170  col_slot_context.validate();
171 
172  if (!is_group_by) {
173  CHECK(!must_use_baseline_sort);
174 
175  return std::make_unique<QueryMemoryDescriptor>(
176  executor,
177  ra_exe_unit,
178  query_infos,
179  allow_multifrag,
180  false,
181  false,
182  -1,
183  ColRangeInfo{ra_exe_unit.estimator ? QueryDescriptionType::Estimator
185  0,
186  0,
187  0,
188  false},
189  col_slot_context,
190  std::vector<int8_t>{},
191  /*group_col_compact_width*/ 0,
192  std::vector<ssize_t>{},
193  /*entry_count*/ 1,
195  false,
196  count_distinct_descriptors,
197  false,
198  output_columnar_hint,
199  render_info && render_info->isPotentialInSituRender(),
200  must_use_baseline_sort);
201  }
202 
203  size_t entry_count = 1;
204  auto actual_col_range_info = col_range_info;
205  auto sharing = GroupByMemSharing::Shared;
206  bool interleaved_bins_on_gpu = false;
207  bool keyless_hash = false;
208  bool shared_mem_for_group_by = false;
209  int8_t group_col_compact_width = 0;
210  int32_t idx_target_as_key = -1;
211  auto output_columnar = output_columnar_hint;
212  std::vector<ssize_t> target_groupby_indices;
213 
214  switch (col_range_info.hash_type_) {
216  if (render_info) {
217  render_info->setInSituDataIfUnset(false);
218  }
219 
220  if (group_col_widths.size() > 1) {
221  // col range info max contains the expected cardinality of the output
222  entry_count = static_cast<size_t>(actual_col_range_info.max);
223  actual_col_range_info.bucket = 0;
224  } else {
225  // single column perfect hash
226  idx_target_as_key = keyless_info.target_index;
227  keyless_hash =
228  (!sort_on_gpu_hint ||
230  col_range_info.max, col_range_info.min, col_range_info.bucket)) &&
231  !col_range_info.bucket && !must_use_baseline_sort && keyless_info.keyless;
232  entry_count = std::max(
233  GroupByAndAggregate::getBucketedCardinality(col_range_info), int64_t(1));
234  const size_t interleaved_max_threshold{512};
235 
236  size_t gpu_smem_max_threshold{0};
237  if (device_type == ExecutorDeviceType::GPU) {
238  const auto cuda_mgr = executor->getCatalog()->getDataMgr().getCudaMgr();
239  CHECK(cuda_mgr);
240  /*
241  * We only use shared memory strategy if GPU hardware provides native shared
242  *memory atomics support. From CUDA Toolkit documentation:
243  *https://docs.nvidia.com/cuda/pascal-tuning-guide/index.html#atomic-ops "Like
244  *Maxwell, Pascal [and Volta] provides native shared memory atomic operations
245  *for 32-bit integer arithmetic, along with native 32 or 64-bit compare-and-swap
246  *(CAS)."
247  *
248  **/
249  if (cuda_mgr->isArchMaxwellOrLaterForAll()) {
250  // TODO(Saman): threshold should be eventually set as an optimized policy per
251  // architecture.
252  gpu_smem_max_threshold =
253  std::min((cuda_mgr->isArchVoltaForAll()) ? 4095LU : 2047LU,
254  (cuda_mgr->getMaxSharedMemoryForAll() / sizeof(int64_t) - 1));
255  }
256  }
257 
258  if (must_use_baseline_sort) {
259  target_groupby_indices = target_expr_group_by_indices(ra_exe_unit.groupby_exprs,
260  ra_exe_unit.target_exprs);
261  col_slot_context =
262  ColSlotContext(ra_exe_unit.target_exprs, target_groupby_indices);
263  }
264 
265  const auto group_expr = ra_exe_unit.groupby_exprs.front().get();
266  shared_mem_for_group_by =
267  g_enable_smem_group_by && keyless_hash && keyless_info.shared_mem_support &&
268  (entry_count <= gpu_smem_max_threshold) &&
271  count_distinct_descriptors) &&
272  !output_columnar; // TODO(Saman): add columnar support with the new smem
273  // support.
274 
275  bool has_varlen_sample_agg = false;
276  for (const auto& target_expr : ra_exe_unit.target_exprs) {
277  if (target_expr->get_contains_agg()) {
278  const auto agg_expr = dynamic_cast<Analyzer::AggExpr*>(target_expr);
279  CHECK(agg_expr);
280  if (agg_expr->get_aggtype() == kSAMPLE &&
281  agg_expr->get_type_info().is_varlen()) {
282  has_varlen_sample_agg = true;
283  break;
284  }
285  }
286  }
287 
288  interleaved_bins_on_gpu = keyless_hash && !has_varlen_sample_agg &&
289  (entry_count <= interleaved_max_threshold) &&
290  (device_type == ExecutorDeviceType::GPU) &&
292  count_distinct_descriptors) &&
293  !output_columnar;
294  }
295  break;
296  }
298  if (render_info) {
299  render_info->setInSituDataIfUnset(false);
300  }
301  entry_count = shard_count
302  ? (max_groups_buffer_entry_count + shard_count - 1) / shard_count
303  : max_groups_buffer_entry_count;
304  target_groupby_indices = target_expr_group_by_indices(ra_exe_unit.groupby_exprs,
305  ra_exe_unit.target_exprs);
306  col_slot_context = ColSlotContext(ra_exe_unit.target_exprs, target_groupby_indices);
307 
308  group_col_compact_width =
309  output_columnar ? 8
310  : pick_baseline_key_width(ra_exe_unit, query_infos, executor);
311 
312  actual_col_range_info =
314  break;
315  }
317  CHECK(!must_use_baseline_sort);
318 
319  if (use_streaming_top_n(ra_exe_unit, output_columnar)) {
320  entry_count = ra_exe_unit.sort_info.offset + ra_exe_unit.sort_info.limit;
321  } else {
322  if (ra_exe_unit.use_bump_allocator) {
323  output_columnar = false;
324  entry_count = 0;
325  } else {
326  entry_count = ra_exe_unit.scan_limit
327  ? static_cast<size_t>(ra_exe_unit.scan_limit)
328  : max_groups_buffer_entry_count;
329  }
330  }
331 
332  const auto catalog = executor->getCatalog();
333  CHECK(catalog);
334  target_groupby_indices = executor->plan_state_->allow_lazy_fetch_
335  ? target_expr_proj_indices(ra_exe_unit, *catalog)
336  : std::vector<ssize_t>{};
337 
338  col_slot_context = ColSlotContext(ra_exe_unit.target_exprs, target_groupby_indices);
339  break;
340  }
341  default:
342  UNREACHABLE() << "Unknown query type";
343  }
344 
345  return std::make_unique<QueryMemoryDescriptor>(
346  executor,
347  ra_exe_unit,
348  query_infos,
349  allow_multifrag,
350  keyless_hash,
351  interleaved_bins_on_gpu,
352  idx_target_as_key,
353  actual_col_range_info,
354  col_slot_context,
355  group_col_widths,
356  group_col_compact_width,
357  target_groupby_indices,
358  entry_count,
359  sharing,
360  shared_mem_for_group_by,
361  count_distinct_descriptors,
362  sort_on_gpu_hint,
363  output_columnar,
364  render_info && render_info->isPotentialInSituRender(),
365  must_use_baseline_sort);
366 }
367 
369  const Executor* executor,
370  const RelAlgExecutionUnit& ra_exe_unit,
371  const std::vector<InputTableInfo>& query_infos,
372  const bool allow_multifrag,
373  const bool keyless_hash,
374  const bool interleaved_bins_on_gpu,
375  const int32_t idx_target_as_key,
376  const ColRangeInfo& col_range_info,
377  const ColSlotContext& col_slot_context,
378  const std::vector<int8_t>& group_col_widths,
379  const int8_t group_col_compact_width,
380  const std::vector<ssize_t>& target_groupby_indices,
381  const size_t entry_count,
382  const GroupByMemSharing sharing,
383  const bool shared_mem_for_group_by,
384  const CountDistinctDescriptors count_distinct_descriptors,
385  const bool sort_on_gpu_hint,
386  const bool output_columnar_hint,
387  const bool render_output,
388  const bool must_use_baseline_sort)
389  : executor_(executor)
390  , allow_multifrag_(allow_multifrag)
391  , query_desc_type_(col_range_info.hash_type_)
392  , keyless_hash_(keyless_hash)
393  , interleaved_bins_on_gpu_(interleaved_bins_on_gpu)
394  , idx_target_as_key_(idx_target_as_key)
395  , group_col_widths_(group_col_widths)
396  , group_col_compact_width_(group_col_compact_width)
397  , target_groupby_indices_(target_groupby_indices)
398  , entry_count_(entry_count)
399  , min_val_(col_range_info.min)
400  , max_val_(col_range_info.max)
401  , bucket_(col_range_info.bucket)
402  , has_nulls_(col_range_info.has_nulls)
403  , sharing_(sharing)
404  , count_distinct_descriptors_(count_distinct_descriptors)
405  , output_columnar_(false)
406  , render_output_(render_output)
407  , must_use_baseline_sort_(must_use_baseline_sort)
408  , force_4byte_float_(false)
409  , col_slot_context_(col_slot_context) {
412 
413  // TODO(Saman): should remove this after implementing shared memory path
414  // completely through codegen We should not use the current shared memory path if
415  // more than 8 bytes per group is required
417  shared_mem_for_group_by && (getRowSize() <= sizeof(int64_t))) {
418  // TODO(adb / saman): Move this into a different enum so we can remove
419  // GroupByMemSharing
421  interleaved_bins_on_gpu_ = false;
422  }
423 
424  // Note that output_columnar_ currently defaults to false to avoid issues with
425  // getRowSize above. If output columnar is enable then shared_mem_for_group_by is not,
426  // and the above condition would never be true.
427 
428  sort_on_gpu_ = sort_on_gpu_hint && canOutputColumnar() && !keyless_hash_;
429 
430  if (sort_on_gpu_) {
431  CHECK(!ra_exe_unit.use_bump_allocator);
432  output_columnar_ = true;
433  } else {
434  switch (query_desc_type_) {
436  output_columnar_ = output_columnar_hint;
437  break;
442  break;
444  output_columnar_ = output_columnar_hint;
445  break;
450  break;
451  default:
452  output_columnar_ = false;
453  break;
454  }
455  }
456 
458  // TODO(adb): Ensure fixed size buffer allocations are correct with all logical column
459  // sizes
460  CHECK(!ra_exe_unit.use_bump_allocator);
463  }
464 }
465 
467  : executor_(nullptr)
468  , allow_multifrag_(false)
470  , keyless_hash_(false)
471  , interleaved_bins_on_gpu_(false)
472  , idx_target_as_key_(0)
474  , entry_count_(0)
475  , min_val_(0)
476  , max_val_(0)
477  , bucket_(0)
478  , has_nulls_(false)
480  , sort_on_gpu_(false)
481  , output_columnar_(false)
482  , render_output_(false)
483  , must_use_baseline_sort_(false)
484  , force_4byte_float_(false) {}
485 
487  const size_t entry_count,
488  const QueryDescriptionType query_desc_type)
489  : executor_(nullptr)
490  , allow_multifrag_(false)
491  , query_desc_type_(query_desc_type)
492  , keyless_hash_(false)
493  , interleaved_bins_on_gpu_(false)
494  , idx_target_as_key_(0)
496  , entry_count_(entry_count)
497  , min_val_(0)
498  , max_val_(0)
499  , bucket_(0)
500  , has_nulls_(false)
502  , sort_on_gpu_(false)
503  , output_columnar_(false)
504  , render_output_(false)
505  , must_use_baseline_sort_(false)
506  , force_4byte_float_(false) {}
507 
509  const int64_t min_val,
510  const int64_t max_val,
511  const bool has_nulls,
512  const std::vector<int8_t>& group_col_widths)
513  : executor_(nullptr)
514  , allow_multifrag_(false)
515  , query_desc_type_(query_desc_type)
516  , keyless_hash_(false)
517  , interleaved_bins_on_gpu_(false)
518  , idx_target_as_key_(0)
519  , group_col_widths_(group_col_widths)
521  , entry_count_(0)
522  , min_val_(min_val)
523  , max_val_(max_val)
524  , bucket_(0)
525  , has_nulls_(false)
527  , sort_on_gpu_(false)
528  , output_columnar_(false)
529  , render_output_(false)
530  , must_use_baseline_sort_(false)
531  , force_4byte_float_(false) {}
532 
534  // Note that this method does not check ptr reference members (e.g. executor_) or
535  // entry_count_
536  if (query_desc_type_ != other.query_desc_type_) {
537  return false;
538  }
539  if (keyless_hash_ != other.keyless_hash_) {
540  return false;
541  }
543  return false;
544  }
545  if (idx_target_as_key_ != other.idx_target_as_key_) {
546  return false;
547  }
548  if (force_4byte_float_ != other.force_4byte_float_) {
549  return false;
550  }
551  if (group_col_widths_ != other.group_col_widths_) {
552  return false;
553  }
555  return false;
556  }
558  return false;
559  }
560  if (min_val_ != other.min_val_) {
561  return false;
562  }
563  if (max_val_ != other.max_val_) {
564  return false;
565  }
566  if (bucket_ != other.bucket_) {
567  return false;
568  }
569  if (has_nulls_ != other.has_nulls_) {
570  return false;
571  }
572  if (sharing_ != other.sharing_) {
573  return false;
574  }
576  return false;
577  } else {
578  // Count distinct descriptors can legitimately differ in device only.
579  for (size_t i = 0; i < count_distinct_descriptors_.size(); ++i) {
580  auto ref_count_distinct_desc = other.count_distinct_descriptors_[i];
581  auto count_distinct_desc = count_distinct_descriptors_[i];
582  count_distinct_desc.device_type = ref_count_distinct_desc.device_type;
583  if (ref_count_distinct_desc != count_distinct_desc) {
584  return false;
585  }
586  }
587  }
588  if (sort_on_gpu_ != other.sort_on_gpu_) {
589  return false;
590  }
591  if (output_columnar_ != other.output_columnar_) {
592  return false;
593  }
594  if (col_slot_context_ != other.col_slot_context_) {
595  return false;
596  }
597  return true;
598 }
599 
600 std::unique_ptr<QueryExecutionContext> QueryMemoryDescriptor::getQueryExecutionContext(
601  const RelAlgExecutionUnit& ra_exe_unit,
602  const Executor* executor,
603  const ExecutorDeviceType device_type,
604  const ExecutorDispatchMode dispatch_mode,
605  const int device_id,
606  const int64_t num_rows,
607  const std::vector<std::vector<const int8_t*>>& col_buffers,
608  const std::vector<std::vector<uint64_t>>& frag_offsets,
609  std::shared_ptr<RowSetMemoryOwner> row_set_mem_owner,
610  const bool output_columnar,
611  const bool sort_on_gpu,
612  RenderInfo* render_info) const {
613  if (frag_offsets.empty()) {
614  return nullptr;
615  }
616  return std::unique_ptr<QueryExecutionContext>(
617  new QueryExecutionContext(ra_exe_unit,
618  *this,
619  executor,
620  device_type,
621  dispatch_mode,
622  device_id,
623  num_rows,
624  col_buffers,
625  frag_offsets,
626  row_set_mem_owner,
627  output_columnar,
628  sort_on_gpu,
629  render_info));
630 }
631 
633  const RelAlgExecutionUnit& ra_exe_unit,
634  const std::vector<InputTableInfo>& query_infos,
635  const int8_t crt_min_byte_width) {
636  if (g_bigint_count) {
637  return sizeof(int64_t);
638  }
639  int8_t compact_width{0};
640  auto col_it = ra_exe_unit.input_col_descs.begin();
641  int unnest_array_col_id{std::numeric_limits<int>::min()};
642  for (const auto groupby_expr : ra_exe_unit.groupby_exprs) {
643  const auto uoper = dynamic_cast<Analyzer::UOper*>(groupby_expr.get());
644  if (uoper && uoper->get_optype() == kUNNEST) {
645  const auto& arg_ti = uoper->get_operand()->get_type_info();
646  CHECK(arg_ti.is_array());
647  const auto& elem_ti = arg_ti.get_elem_type();
648  if (elem_ti.is_string() && elem_ti.get_compression() == kENCODING_DICT) {
649  unnest_array_col_id = (*col_it)->getColId();
650  } else {
651  compact_width = crt_min_byte_width;
652  break;
653  }
654  }
655  ++col_it;
656  }
657  if (!compact_width &&
658  (ra_exe_unit.groupby_exprs.size() != 1 || !ra_exe_unit.groupby_exprs.front())) {
659  compact_width = crt_min_byte_width;
660  }
661  if (!compact_width) {
662  col_it = ra_exe_unit.input_col_descs.begin();
663  std::advance(col_it, ra_exe_unit.groupby_exprs.size());
664  for (const auto target : ra_exe_unit.target_exprs) {
665  const auto& ti = target->get_type_info();
666  const auto agg = dynamic_cast<const Analyzer::AggExpr*>(target);
667  if (agg && agg->get_arg()) {
668  compact_width = crt_min_byte_width;
669  break;
670  }
671 
672  if (agg) {
673  CHECK_EQ(kCOUNT, agg->get_aggtype());
674  CHECK(!agg->get_is_distinct());
675  ++col_it;
676  continue;
677  }
678 
679  if (is_int_and_no_bigger_than(ti, 4) ||
680  (ti.is_string() && ti.get_compression() == kENCODING_DICT)) {
681  ++col_it;
682  continue;
683  }
684 
685  const auto uoper = dynamic_cast<Analyzer::UOper*>(target);
686  if (uoper && uoper->get_optype() == kUNNEST &&
687  (*col_it)->getColId() == unnest_array_col_id) {
688  const auto arg_ti = uoper->get_operand()->get_type_info();
689  CHECK(arg_ti.is_array());
690  const auto& elem_ti = arg_ti.get_elem_type();
691  if (elem_ti.is_string() && elem_ti.get_compression() == kENCODING_DICT) {
692  ++col_it;
693  continue;
694  }
695  }
696 
697  compact_width = crt_min_byte_width;
698  break;
699  }
700  }
701  if (!compact_width) {
702  size_t total_tuples{0};
703  for (const auto& qi : query_infos) {
704  total_tuples += qi.info.getNumTuples();
705  }
706  return total_tuples <= static_cast<size_t>(std::numeric_limits<uint32_t>::max()) ||
707  unnest_array_col_id != std::numeric_limits<int>::min()
708  ? 4
709  : crt_min_byte_width;
710  } else {
711  // TODO(miyu): relax this condition to allow more cases just w/o padding
712  for (auto wid : get_col_byte_widths(ra_exe_unit.target_exprs, {})) {
713  compact_width = std::max(compact_width, wid);
714  }
715  return compact_width;
716  }
717 }
718 
721 }
722 
725  size_t total_bytes{0};
726  if (keyless_hash_) {
727  CHECK_EQ(size_t(1), group_col_widths_.size());
728  } else {
729  total_bytes += group_col_widths_.size() * getEffectiveKeyWidth();
730  total_bytes = align_to_int64(total_bytes);
731  }
732  total_bytes += getColsSize();
733  return align_to_int64(total_bytes);
734 }
735 
737  return (interleaved_bins_on_gpu_ ? executor_->warpSize() : 1);
738 }
739 
742 }
743 
752 }
753 
759  const size_t num_entries_per_column) const {
760  return col_slot_context_.getTotalBytesOfColumnarBuffers(num_entries_per_column);
761 }
762 
773  const size_t projection_count) const {
774  constexpr size_t row_index_width = sizeof(int64_t);
775  return getTotalBytesOfColumnarBuffers(projection_count) +
776  row_index_width * projection_count;
777 }
778 
779 size_t QueryMemoryDescriptor::getColOnlyOffInBytes(const size_t col_idx) const {
780  return col_slot_context_.getColOnlyOffInBytes(col_idx);
781 }
782 
783 /*
784  * Returns the memory offset in bytes for a specific agg column in the output
785  * memory buffer. Depending on the query type, there may be some extra portion
786  * of memory prepended at the beginning of the buffer. A brief description of
787  * the memory layout is as follows:
788  * 1. projections: index column (64bit) + all target columns
789  * 2. group by: all group columns (64-bit each) + all agg columns
790  * 2a. if keyless, there is no prepending group column stored at the beginning
791  */
792 size_t QueryMemoryDescriptor::getColOffInBytes(const size_t col_idx) const {
793  const auto warp_count = getWarpCount();
794  if (output_columnar_) {
795  CHECK_EQ(size_t(1), warp_count);
796  size_t offset{0};
797  if (!keyless_hash_) {
799  }
800  for (size_t index = 0; index < col_idx; ++index) {
802  }
803  return offset;
804  }
805 
806  size_t offset{0};
807  if (keyless_hash_) {
808  CHECK_EQ(size_t(1), group_col_widths_.size());
809  } else {
810  offset += group_col_widths_.size() * getEffectiveKeyWidth();
811  offset = align_to_int64(offset);
812  }
813  offset += getColOnlyOffInBytes(col_idx);
814  return offset;
815 }
816 
817 /*
818  * Returns the memory offset for a particular group column in the prepended group
819  * columns portion of the memory.
820  */
822  const size_t group_idx) const {
824  CHECK(group_idx < getGroupbyColCount());
825  size_t offset{0};
826  for (size_t col_idx = 0; col_idx < group_idx; col_idx++) {
827  // TODO(Saman): relax that int64_bit part immediately
828  offset += align_to_int64(
829  std::max(groupColWidth(col_idx), static_cast<int8_t>(sizeof(int64_t))) *
830  getEntryCount());
831  }
832  return offset;
833 }
834 
835 /*
836  * Returns total amount of memory prepended at the beginning of the output memory
837  * buffer.
838  */
841  size_t buffer_size{0};
842  for (size_t group_idx = 0; group_idx < getGroupbyColCount(); group_idx++) {
843  buffer_size += align_to_int64(
844  std::max(groupColWidth(group_idx), static_cast<int8_t>(sizeof(int64_t))) *
845  getEntryCount());
846  }
847  return buffer_size;
848 }
849 
850 size_t QueryMemoryDescriptor::getColOffInBytesInNextBin(const size_t col_idx) const {
851  auto warp_count = getWarpCount();
852  if (output_columnar_) {
853  CHECK_EQ(size_t(1), group_col_widths_.size());
854  CHECK_EQ(size_t(1), warp_count);
855  return getPaddedSlotWidthBytes(col_idx);
856  }
857 
858  return warp_count * getRowSize();
859 }
860 
861 size_t QueryMemoryDescriptor::getNextColOffInBytes(const int8_t* col_ptr,
862  const size_t bin,
863  const size_t col_idx) const {
865  size_t offset{0};
866  auto warp_count = getWarpCount();
867  const auto chosen_bytes = getPaddedSlotWidthBytes(col_idx);
868  const auto total_slot_count = getSlotCount();
869  if (col_idx + 1 == total_slot_count) {
870  if (output_columnar_) {
871  return (entry_count_ - bin) * chosen_bytes;
872  } else {
873  return static_cast<size_t>(align_to_int64(col_ptr + chosen_bytes) - col_ptr);
874  }
875  }
876 
877  const auto next_chosen_bytes = getPaddedSlotWidthBytes(col_idx + 1);
878  if (output_columnar_) {
879  CHECK_EQ(size_t(1), group_col_widths_.size());
880  CHECK_EQ(size_t(1), warp_count);
881 
882  offset = align_to_int64(entry_count_ * chosen_bytes);
883 
884  offset += bin * (next_chosen_bytes - chosen_bytes);
885  return offset;
886  }
887 
888  if (next_chosen_bytes == sizeof(int64_t)) {
889  return static_cast<size_t>(align_to_int64(col_ptr + chosen_bytes) - col_ptr);
890  } else {
891  return chosen_bytes;
892  }
893 }
894 
896  const RelAlgExecutionUnit& ra_exe_unit,
897  const unsigned thread_count,
898  const ExecutorDeviceType device_type) const {
899  if (use_streaming_top_n(ra_exe_unit, output_columnar_)) {
900  const size_t n = ra_exe_unit.sort_info.offset + ra_exe_unit.sort_info.limit;
901  return streaming_top_n::get_heap_size(getRowSize(), n, thread_count);
902  }
903  return getBufferSizeBytes(device_type, entry_count_);
904 }
905 
918  const size_t entry_count) const {
920  CHECK_GE(group_col_widths_.size(), size_t(1));
921  auto row_bytes = align_to_int64(getColsSize());
922 
923  return (interleavedBins(device_type) ? executor_->warpSize() : 1) * entry_count *
924  row_bytes;
925  }
926 
927  constexpr size_t row_index_width = sizeof(int64_t);
928  size_t total_bytes{0};
929  if (output_columnar_) {
931  ? row_index_width * entry_count
932  : sizeof(int64_t) * group_col_widths_.size() * entry_count) +
934  } else {
935  total_bytes = getRowSize() * entry_count;
936  }
937 
938  return total_bytes;
939 }
940 
942  const ExecutorDeviceType device_type) const {
943  return getBufferSizeBytes(device_type, entry_count_);
944 }
945 
947  output_columnar_ = val;
950  }
951 }
952 
953 /*
954  * Indicates the query types that are currently allowed to use the logical
955  * sized columns instead of padded sized ones.
956  */
958  // In distributed mode, result sets are serialized using rowwise iterators, so we use
959  // consistent slot widths for now
960  return output_columnar_ && !g_cluster &&
962 }
963 
965  size_t total_slot_count = col_slot_context_.getSlotCount();
966 
967  if (target_groupby_indices_.empty()) {
968  return total_slot_count;
969  }
970  return total_slot_count - std::count_if(target_groupby_indices_.begin(),
972  [](const ssize_t i) { return i >= 0; });
973 }
974 
977  getGroupbyColCount() == 1);
978 }
979 
982 }
983 
985  if (g_cluster) {
986  return true;
987  }
989  return true;
990  }
991  if (executor_->isCPUOnly() || render_output_ ||
995  getGroupbyColCount() > 1)) {
996  return true;
997  }
1001 }
1002 
1004  return device_type == ExecutorDeviceType::GPU && !render_output_ &&
1006 }
1007 
1009  return interleaved_bins_on_gpu_ && device_type == ExecutorDeviceType::GPU;
1010 }
1011 
1013  CHECK(device_type == ExecutorDeviceType::CPU || device_type == ExecutorDeviceType::GPU);
1014  if (device_type == ExecutorDeviceType::CPU) {
1015  return 0;
1016  }
1017  // if performing keyless aggregate query with a single column group-by:
1019  CHECK_EQ(getRowSize(),
1020  sizeof(int64_t)); // Currently just designed for this scenario
1021  size_t shared_mem_size =
1022  (/*bin_count=*/entry_count_ + 1) * sizeof(int64_t); // one extra for NULL values
1023  CHECK(shared_mem_size <=
1024  executor_->getCatalog()->getDataMgr().getCudaMgr()->getMaxSharedMemoryForAll());
1025  return shared_mem_size;
1026  }
1027  return 0;
1028 }
1029 
1031  const ExecutorDeviceType device_type) const {
1032  if (device_type != ExecutorDeviceType::GPU) {
1033  return false;
1034  } else {
1035  auto cuda_mgr = executor_->getCatalog()->getDataMgr().getCudaMgr();
1036  CHECK(cuda_mgr);
1037  return cuda_mgr->isArchVoltaForAll();
1038  }
1039 }
1040 
1042  return col_slot_context_.getColCount();
1043 }
1044 
1047 }
1048 
1049 const int8_t QueryMemoryDescriptor::getPaddedSlotWidthBytes(const size_t slot_idx) const {
1050  return col_slot_context_.getSlotInfo(slot_idx).padded_size;
1051 }
1052 
1054  const size_t slot_idx) const {
1055  return col_slot_context_.getSlotInfo(slot_idx).logical_size;
1056 }
1057 
1059  const size_t col_idx) const {
1060  const auto& col_slots = col_slot_context_.getSlotsForCol(col_idx);
1061  CHECK_EQ(col_slots.size(), size_t(1));
1062  return col_slots.front();
1063 }
1064 
1065 void QueryMemoryDescriptor::useConsistentSlotWidthSize(const int8_t slot_width_size) {
1066  col_slot_context_.setAllSlotsSize(slot_width_size);
1067 }
1068 
1070  // Note: Actual row size may include padding (see ResultSetBufferAccessors.h)
1072 }
1073 
1075  const int8_t actual_min_byte_width) const {
1076  return col_slot_context_.getMinPaddedByteSize(actual_min_byte_width);
1077 }
1078 
1080  const std::vector<std::tuple<int8_t, int8_t>>& slots_for_col) {
1081  col_slot_context_.addColumn(slots_for_col);
1082 }
1083 
1086 }
1087 
1090 }
1091 
1096 }
1097 
1098 namespace {
1099 
1100 inline std::string boolToString(const bool val) {
1101  return val ? "True" : "False";
1102 }
1103 
1104 inline std::string queryDescTypeToString(const QueryDescriptionType val) {
1105  switch (val) {
1107  return "Perfect Hash";
1109  return "Baseline Hash";
1111  return "Projection";
1113  return "Non-grouped Aggregate";
1115  return "Estimator";
1116  default:
1117  UNREACHABLE();
1118  }
1119  return "";
1120 }
1121 
1122 } // namespace
1123 
1124 std::string QueryMemoryDescriptor::toString() const {
1125  std::string str;
1126  str += "Query Memory Descriptor State\n";
1127  str += "\tQuery Type: " + queryDescTypeToString(query_desc_type_) + "\n";
1128  str += "\tAllow Multifrag: " + boolToString(allow_multifrag_) + "\n";
1129  str += "\tKeyless Hash: " + boolToString(keyless_hash_) + "\n";
1130  str += "\tInterleaved Bins on GPU: " + boolToString(interleaved_bins_on_gpu_) + "\n";
1131  str += "\tBlocks Share Memory: " + boolToString(blocksShareMemory()) + "\n";
1132  str += "\tThreads Share Memory: " + boolToString(threadsShareMemory()) + "\n";
1133  str += "\tUses Fast Group Values: " + boolToString(usesGetGroupValueFast()) + "\n";
1134  str += "\tLazy Init Groups (GPU): " +
1136  str += "\tEntry Count: " + std::to_string(entry_count_) + "\n";
1137  str += "\tMin Val (perfect hash only): " + std::to_string(min_val_) + "\n";
1138  str += "\tMax Val (perfect hash only): " + std::to_string(max_val_) + "\n";
1139  str += "\tBucket Val (perfect hash only): " + std::to_string(bucket_) + "\n";
1140  str += "\tSort on GPU: " + boolToString(sort_on_gpu_) + "\n";
1141  str += "\tOutput Columnar: " + boolToString(output_columnar_) + "\n";
1142  str += "\tRender Output: " + boolToString(render_output_) + "\n";
1143  str += "\tUse Baseline Sort: " + boolToString(must_use_baseline_sort_) + "\n";
1144  str += "\t" + col_slot_context_.toString();
1145  return str;
1146 }
1147 
1148 std::vector<TargetInfo> target_exprs_to_infos(
1149  const std::vector<Analyzer::Expr*>& targets,
1150  const QueryMemoryDescriptor& query_mem_desc) {
1151  std::vector<TargetInfo> target_infos;
1152  for (const auto target_expr : targets) {
1153  auto target = get_target_info(target_expr, g_bigint_count);
1154  if (query_mem_desc.getQueryDescriptionType() ==
1156  set_notnull(target, false);
1157  target.sql_type.set_notnull(false);
1158  }
1159  target_infos.push_back(target);
1160  }
1161  return target_infos;
1162 }
size_t getColCount() const
std::vector< Analyzer::Expr * > target_exprs
static bool many_entries(const int64_t max_val, const int64_t min_val, const int64_t bucket)
#define CHECK_EQ(x, y)
Definition: Logger.h:195
bool use_streaming_top_n(const RelAlgExecutionUnit &ra_exe_unit, const bool output_columnar)
static int64_t getBucketedCardinality(const ColRangeInfo &col_range_info)
size_t getTotalBytesOfColumnarProjections(const size_t projection_count) const
void alignPaddedSlots(const bool sort_on_gpu)
int8_t updateActualMinByteWidth(const int8_t actual_min_byte_width) const
const bool shared_mem_support
bool g_enable_smem_group_by
int8_t logical_size
size_t getPrependedGroupBufferSizeInBytes() const
const int8_t const int64_t * num_rows
class for a per-database catalog. also includes metadata for the current database and the current use...
Definition: Catalog.h:81
size_t sharedMemBytes(const ExecutorDeviceType) const
size_t getSlotCount() const
const bool keyless
std::vector< int8_t > get_col_byte_widths(const T &col_expr_list, const std::vector< ssize_t > &col_exprs_to_not_project)
const int8_t getSlotIndexForSingleSlotCol(const size_t col_idx) const
ExecutorDeviceType
int8_t getMinPaddedByteSize(const int8_t actual_min_byte_width) const
TargetInfo get_target_info(const PointerType target_expr, const bool bigint_count)
Definition: TargetInfo.h:65
const std::list< Analyzer::OrderEntry > order_entries
bool setInSituDataIfUnset(const bool is_in_situ_data)
Definition: RenderInfo.cpp:89
QueryDescriptionType hash_type_
#define UNREACHABLE()
Definition: Logger.h:231
void setOutputColumnar(const bool val)
static bool supportedExprForGpuSharedMemUsage(Analyzer::Expr *expr)
#define CHECK_GE(x, y)
Definition: Logger.h:200
const std::list< std::shared_ptr< Analyzer::Expr > > groupby_exprs
const std::vector< InputDescriptor > input_descs
int64_t getIntMax() const
ExpressionRangeType getType() const
std::vector< ssize_t > target_expr_group_by_indices(const std::list< std::shared_ptr< Analyzer::Expr >> &groupby_exprs, const std::vector< Analyzer::Expr *> &target_exprs)
void setAllSlotsSize(const int8_t slot_width_size)
std::string to_string(char const *&&v)
const int8_t getPaddedSlotWidthBytes(const size_t slot_idx) const
const SlotSize & getSlotInfo(const size_t slot_idx) const
void useConsistentSlotWidthSize(const int8_t slot_width_size)
size_t getTotalBytesOfColumnarBuffers(const size_t entry_count) const
ExecutorDispatchMode
const size_t limit
bool g_enable_columnar_output
Definition: Execute.cpp:84
bool isPotentialInSituRender() const
Definition: RenderInfo.cpp:55
std::string queryDescTypeToString(const QueryDescriptionType val)
size_t getNextColOffInBytes(const int8_t *col_ptr, const size_t bin, const size_t col_idx) const
bool is_integer() const
Definition: sqltypes.h:448
size_t get_bit_width(const SQLTypeInfo &ti)
size_t getAllSlotsPaddedSize() const
size_t getTotalBytesOfColumnarBuffers() const
const ColumnDescriptor * get_column_descriptor_maybe(const int col_id, const int table_id, const Catalog_Namespace::Catalog &cat)
Definition: Execute.h:168
std::vector< CountDistinctDescriptor > CountDistinctDescriptors
Definition: CountDistinct.h:35
const SortInfo sort_info
Provides column info and slot info for the output buffer and some metadata helpers.
bool interleavedBins(const ExecutorDeviceType) const
bool isWarpSyncRequired(const ExecutorDeviceType) const
std::unique_ptr< QueryExecutionContext > getQueryExecutionContext(const RelAlgExecutionUnit &, const Executor *executor, const ExecutorDeviceType device_type, const ExecutorDispatchMode dispatch_mode, const int device_id, const int64_t num_rows, const std::vector< std::vector< const int8_t *>> &col_buffers, const std::vector< std::vector< uint64_t >> &frag_offsets, std::shared_ptr< RowSetMemoryOwner >, const bool output_columnar, const bool sort_on_gpu, RenderInfo *) const
static int8_t pick_target_compact_width(const RelAlgExecutionUnit &ra_exe_unit, const std::vector< InputTableInfo > &query_infos, const int8_t crt_min_byte_width)
size_t getBufferSizeBytes(const RelAlgExecutionUnit &ra_exe_unit, const unsigned thread_count, const ExecutorDeviceType device_type) const
bool g_bigint_count
CountDistinctDescriptors count_distinct_descriptors_
ExpressionRange getExpressionRange(const Analyzer::BinOper *expr, const std::vector< InputTableInfo > &query_infos, const Executor *, boost::optional< std::list< std::shared_ptr< Analyzer::Expr >>> simple_quals)
bool operator==(const QueryMemoryDescriptor &other) const
const int32_t target_index
int8_t groupColWidth(const size_t key_idx) const
void addColumn(const std::vector< std::tuple< int8_t, int8_t >> &slots_for_col)
bool is_real_str_or_array(const TargetInfo &target_info)
size_t getColOnlyOffInBytes(const size_t col_idx) const
const std::vector< size_t > & getSlotsForCol(const size_t col_idx) const
std::string toString() const
size_t getCompactByteWidth() const
QueryDescriptionType query_desc_type_
int8_t padded_size
size_t getColOffInBytesInNextBin(const size_t col_idx) const
Definition: sqldefs.h:71
size_t getAllSlotsAlignedPaddedSize() const
T visit(const Analyzer::Expr *expr) const
Descriptor for the result set buffer layout.
bool is_int_and_no_bigger_than(const SQLTypeInfo &ti, const size_t byte_width)
std::vector< TargetInfo > target_exprs_to_infos(const std::vector< Analyzer::Expr *> &targets, const QueryMemoryDescriptor &query_mem_desc)
int get_varno() const
Definition: Analyzer.h:274
std::list< std::shared_ptr< Analyzer::Expr > > quals
const SQLTypeInfo & get_type_info() const
Definition: Analyzer.h:77
size_t get_heap_size(const size_t row_size, const size_t n, const size_t thread_count)
void setAllSlotsPaddedSizeToLogicalSize()
#define CHECK(condition)
Definition: Logger.h:187
size_t getColOnlyOffInBytes(const size_t slot_idx) const
GroupByMemSharing
std::vector< int8_t > group_col_widths_
int8_t pick_baseline_key_component_width(const ExpressionRange &range)
#define EMPTY_KEY_32
QueryDescriptionType
Definition: Types.h:26
bool g_cluster
const int8_t getLogicalSlotWidthBytes(const size_t slot_idx) const
size_t getColOffInBytes(const size_t col_idx) const
std::vector< ssize_t > target_expr_proj_indices(const RelAlgExecutionUnit &ra_exe_unit, const Catalog_Namespace::Catalog &cat)
static std::unique_ptr< QueryMemoryDescriptor > init(const Executor *executor, const RelAlgExecutionUnit &ra_exe_unit, const std::vector< InputTableInfo > &query_infos, const ColRangeInfo &col_range_info, const KeylessInfo &keyless_info, const bool allow_multifrag, const ExecutorDeviceType device_type, const int8_t crt_min_byte_width, const bool sort_on_gpu_hint, const size_t shard_count, const size_t max_groups_buffer_entry_count, RenderInfo *render_info, const CountDistinctDescriptors count_distinct_descriptors, const bool must_use_baseline_sort, const bool output_columnar_hint)
std::list< std::shared_ptr< const InputColDescriptor > > input_col_descs
void addColSlotInfo(const std::vector< std::tuple< int8_t, int8_t >> &slots_for_col)
const size_t offset
static bool countDescriptorsLogicallyEmpty(const CountDistinctDescriptors &count_distinct_descriptors)
void setAllUnsetSlotsPaddedSize(const int8_t padded_size)
QueryDescriptionType getQueryDescriptionType() const
bool lazyInitGroups(const ExecutorDeviceType) const
std::vector< ssize_t > target_groupby_indices_
FORCE_INLINE HOST DEVICE T align_to_int64(T addr)
int8_t pick_baseline_key_width(const RelAlgExecutionUnit &ra_exe_unit, const std::vector< InputTableInfo > &query_infos, const Executor *executor)
size_t getPrependedGroupColOffInBytes(const size_t group_idx) const
std::list< std::shared_ptr< Analyzer::Expr > > simple_quals
void set_notnull(TargetInfo &target, const bool not_null)
size_t getEffectiveKeyWidth() const
void validate() const
void sort_on_gpu(int64_t *val_buff, int32_t *key_buff, const uint64_t entry_count, const bool desc, const uint32_t chosen_bytes, ThrustAllocator &alloc)
const Expr * get_operand() const
Definition: Analyzer.h:364