repo_id
stringlengths 21
96
| file_path
stringlengths 31
155
| content
stringlengths 1
92.9M
| __index_level_0__
int64 0
0
|
---|---|---|---|
rapidsai_public_repos/cudf/cpp/src/quantiles
|
rapidsai_public_repos/cudf/cpp/src/quantiles/tdigest/tdigest_column_view.cpp
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/tdigest/tdigest.hpp>
#include <cudf/lists/lists_column_view.hpp>
#include <cudf/structs/structs_column_view.hpp>
#include <cudf/tdigest/tdigest_column_view.hpp>
namespace cudf {
namespace tdigest {
tdigest_column_view::tdigest_column_view(column_view const& col) : column_view(col)
{
// sanity check that this is actually tdigest data
CUDF_EXPECTS(col.type().id() == type_id::STRUCT, "Encountered invalid tdigest column");
CUDF_EXPECTS(col.size() > 0, "tdigest columns must have > 0 rows");
CUDF_EXPECTS(col.offset() == 0, "Encountered a sliced tdigest column");
CUDF_EXPECTS(not col.nullable(), "Encountered nullable tdigest column");
structs_column_view scv(col);
CUDF_EXPECTS(scv.num_children() == 3, "Encountered invalid tdigest column");
CUDF_EXPECTS(scv.child(min_column_index).type().id() == type_id::FLOAT64,
"Encountered invalid tdigest column");
CUDF_EXPECTS(scv.child(max_column_index).type().id() == type_id::FLOAT64,
"Encountered invalid tdigest column");
lists_column_view lcv(scv.child(centroid_column_index));
auto data = lcv.child();
CUDF_EXPECTS(data.type().id() == type_id::STRUCT, "Encountered invalid tdigest column");
CUDF_EXPECTS(data.num_children() == 2,
"Encountered tdigest column with an invalid number of children");
auto mean = data.child(mean_column_index);
CUDF_EXPECTS(mean.type().id() == type_id::FLOAT64, "Encountered invalid tdigest mean column");
auto weight = data.child(weight_column_index);
CUDF_EXPECTS(weight.type().id() == type_id::FLOAT64, "Encountered invalid tdigest weight column");
}
lists_column_view tdigest_column_view::centroids() const { return child(centroid_column_index); }
column_view tdigest_column_view::means() const
{
auto c = centroids();
structs_column_view inner(c.parent().child(lists_column_view::child_column_index));
return inner.child(mean_column_index);
}
column_view tdigest_column_view::weights() const
{
auto c = centroids();
structs_column_view inner(c.parent().child(lists_column_view::child_column_index));
return inner.child(weight_column_index);
}
double const* tdigest_column_view::min_begin() const
{
return child(min_column_index).begin<double>();
}
double const* tdigest_column_view::max_begin() const
{
return child(max_column_index).begin<double>();
}
} // namespace tdigest
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/quantiles
|
rapidsai_public_repos/cudf/cpp/src/quantiles/tdigest/tdigest.cu
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <quantiles/tdigest/tdigest_util.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/tdigest/tdigest.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/detail/valid_if.cuh>
#include <cudf/lists/lists_column_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/advance.h>
#include <thrust/binary_search.h>
#include <thrust/distance.h>
#include <thrust/execution_policy.h>
#include <thrust/fill.h>
#include <thrust/functional.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/reduce.h>
#include <thrust/scan.h>
using namespace cudf::tdigest;
namespace cudf {
namespace tdigest {
namespace detail {
// https://developer.nvidia.com/blog/lerp-faster-cuda/
template <typename T>
__device__ inline T lerp(T v0, T v1, T t)
{
return fma(t, v1, fma(-t, v0, v0));
}
struct centroid {
double mean;
double weight;
};
struct make_centroid {
double const* means;
double const* weights;
__device__ centroid operator()(size_type i) { return {means[i], weights[i]}; }
};
// kernel for computing percentiles on input tdigest (mean, weight) centroid data.
template <typename CentroidIter>
__global__ void compute_percentiles_kernel(device_span<size_type const> tdigest_offsets,
column_device_view percentiles,
CentroidIter centroids_,
double const* min_,
double const* max_,
double const* cumulative_weight_,
double* output)
{
auto const tid = cudf::detail::grid_1d::global_thread_id();
auto const num_tdigests = tdigest_offsets.size() - 1;
auto const tdigest_index = tid / percentiles.size();
if (tdigest_index >= num_tdigests) { return; }
auto const pindex = tid % percentiles.size();
// size of the digest we're querying
auto const tdigest_size = tdigest_offsets[tdigest_index + 1] - tdigest_offsets[tdigest_index];
// no work to do. values will be set to null
if (tdigest_size == 0 || !percentiles.is_valid(pindex)) { return; }
output[tid] = [&]() {
double const percentage = percentiles.element<double>(pindex);
double const* cumulative_weight = cumulative_weight_ + tdigest_offsets[tdigest_index];
// centroids for this particular tdigest
CentroidIter centroids = centroids_ + tdigest_offsets[tdigest_index];
// min and max for the digest
double const* min_val = min_ + tdigest_index;
double const* max_val = max_ + tdigest_index;
double const total_weight = cumulative_weight[tdigest_size - 1];
// The following Arrow code serves as a basis for this computation
// https://github.com/apache/arrow/blob/master/cpp/src/arrow/util/tdigest.cc#L280
double const weighted_q = percentage * total_weight;
if (weighted_q <= 1) {
return *min_val;
} else if (weighted_q >= total_weight - 1) {
return *max_val;
}
// determine what centroid this weighted quantile falls within.
size_type const centroid_index = static_cast<size_type>(thrust::distance(
cumulative_weight,
thrust::lower_bound(
thrust::seq, cumulative_weight, cumulative_weight + tdigest_size, weighted_q)));
centroid c = centroids[centroid_index];
// diff == how far from the "center" of the centroid we are,
// in unit weights.
// visually:
//
// centroid of weight 7
// C <-- center of the centroid
// |-------|
// | | |
// X Y Z
// X has a diff of -2 (2 units to the left of the center of the centroid)
// Y has a diff of 0 (directly in the middle of the centroid)
// Z has a diff of 3 (3 units to the right of the center of the centroid)
double const diff = weighted_q + c.weight / 2 - cumulative_weight[centroid_index];
// if we're completely within a centroid of weight 1, just return that.
if (c.weight == 1 && std::abs(diff) < 0.5) { return c.mean; }
// otherwise, interpolate between two centroids.
// get the two centroids we want to interpolate between
auto const look_left = diff < 0;
auto const [lhs, rhs] = [&]() {
if (look_left) {
// if we're at the first centroid, "left" of us is the min value
auto const first_centroid = centroid_index == 0;
auto const lhs = first_centroid ? centroid{*min_val, 0} : centroids[centroid_index - 1];
auto const rhs = c;
return std::pair<centroid, centroid>{lhs, rhs};
} else {
// if we're at the last centroid, "right" of us is the max value
auto const last_centroid = (centroid_index == tdigest_size - 1);
auto const lhs = c;
auto const rhs = last_centroid ? centroid{*max_val, 0} : centroids[centroid_index + 1];
return std::pair<centroid, centroid>{lhs, rhs};
}
}();
// compute interpolation value t
// total interpolation range. the total range of "space" between the lhs and rhs centroids.
auto const tip = lhs.weight / 2 + rhs.weight / 2;
// if we're looking left, diff is negative, so shift it so that we are interpolating
// from lhs -> rhs.
auto const t = (look_left) ? (diff + tip) / tip : diff / tip;
// interpolate
return lerp(lhs.mean, rhs.mean, t);
}();
}
/**
* @brief Calculate approximate percentiles on a provided tdigest column.
*
* Produces a LIST column where each row `i` represents output from querying the
* corresponding tdigest of from row `i` in `input`. The length of each output list
* is the number of percentiles specified in `percentiles`
*
* @param input tdigest input data. One tdigest per row.
* @param percentiles Desired percentiles in range [0, 1].
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device
* memory
*
* @returns Column of doubles containing requested percentile values.
*/
std::unique_ptr<column> compute_approx_percentiles(tdigest_column_view const& input,
column_view const& percentiles,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
tdigest_column_view tdv(input);
// offsets, representing the size of each tdigest
auto offsets = tdv.centroids().offsets();
// compute summed weights
auto weight = tdv.weights();
auto cumulative_weights = cudf::make_fixed_width_column(data_type{type_id::FLOAT64},
weight.size(),
mask_state::UNALLOCATED,
stream,
rmm::mr::get_current_device_resource());
auto keys = cudf::detail::make_counting_transform_iterator(
0,
[offsets_begin = offsets.begin<size_type>(),
offsets_end = offsets.end<size_type>()] __device__(size_type i) {
return thrust::distance(
offsets_begin,
thrust::prev(thrust::upper_bound(thrust::seq, offsets_begin, offsets_end, i)));
});
thrust::inclusive_scan_by_key(rmm::exec_policy(stream),
keys,
keys + weight.size(),
weight.begin<double>(),
cumulative_weights->mutable_view().begin<double>());
auto percentiles_cdv = column_device_view::create(percentiles, stream);
// leaf is a column of size input.size() * percentiles.size()
auto const num_output_values = input.size() * percentiles.size();
// null percentiles become null results.
auto [null_mask, null_count] = [&]() {
return percentiles.null_count() != 0
? cudf::detail::valid_if(
thrust::make_counting_iterator<size_type>(0),
thrust::make_counting_iterator<size_type>(0) + num_output_values,
[percentiles = *percentiles_cdv] __device__(size_type i) {
return percentiles.is_valid(i % percentiles.size());
},
stream,
mr)
: std::pair<rmm::device_buffer, size_type>{rmm::device_buffer{}, 0};
}();
auto result = cudf::make_fixed_width_column(
data_type{type_id::FLOAT64}, num_output_values, std::move(null_mask), null_count, stream, mr);
auto centroids = cudf::detail::make_counting_transform_iterator(
0, make_centroid{tdv.means().begin<double>(), tdv.weights().begin<double>()});
constexpr size_type block_size = 256;
cudf::detail::grid_1d const grid(percentiles.size() * input.size(), block_size);
compute_percentiles_kernel<<<grid.num_blocks, block_size, 0, stream.value()>>>(
{offsets.begin<size_type>(), static_cast<size_t>(offsets.size())},
*percentiles_cdv,
centroids,
tdv.min_begin(),
tdv.max_begin(),
cumulative_weights->view().begin<double>(),
result->mutable_view().begin<double>());
return result;
}
std::unique_ptr<column> make_tdigest_column(size_type num_rows,
std::unique_ptr<column>&& centroid_means,
std::unique_ptr<column>&& centroid_weights,
std::unique_ptr<column>&& tdigest_offsets,
std::unique_ptr<column>&& min_values,
std::unique_ptr<column>&& max_values,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(tdigest_offsets->size() == num_rows + 1,
"Encountered unexpected offset count in make_tdigest_column");
CUDF_EXPECTS(centroid_means->size() == centroid_weights->size(),
"Encountered unexpected centroid size mismatch in make_tdigest_column");
CUDF_EXPECTS(min_values->size() == num_rows,
"Encountered unexpected min value count in make_tdigest_column");
CUDF_EXPECTS(max_values->size() == num_rows,
"Encountered unexpected max value count in make_tdigest_column");
// inner struct column
auto const centroids_size = centroid_means->size();
std::vector<std::unique_ptr<column>> inner_children;
inner_children.push_back(std::move(centroid_means));
inner_children.push_back(std::move(centroid_weights));
auto tdigest_data =
cudf::make_structs_column(centroids_size, std::move(inner_children), 0, {}, stream, mr);
// grouped into lists
auto tdigest = cudf::make_lists_column(
num_rows, std::move(tdigest_offsets), std::move(tdigest_data), 0, {}, stream, mr);
// create the final column
std::vector<std::unique_ptr<column>> children;
children.push_back(std::move(tdigest));
children.push_back(std::move(min_values));
children.push_back(std::move(max_values));
return make_structs_column(num_rows, std::move(children), 0, {}, stream, mr);
}
std::unique_ptr<column> make_empty_tdigest_column(rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto offsets = cudf::make_fixed_width_column(
data_type(type_id::INT32), 2, mask_state::UNALLOCATED, stream, mr);
thrust::fill(rmm::exec_policy(stream),
offsets->mutable_view().begin<size_type>(),
offsets->mutable_view().end<size_type>(),
0);
auto min_col =
cudf::make_numeric_column(data_type(type_id::FLOAT64), 1, mask_state::UNALLOCATED, stream, mr);
thrust::fill(rmm::exec_policy(stream),
min_col->mutable_view().begin<double>(),
min_col->mutable_view().end<double>(),
0);
auto max_col =
cudf::make_numeric_column(data_type(type_id::FLOAT64), 1, mask_state::UNALLOCATED, stream, mr);
thrust::fill(rmm::exec_policy(stream),
max_col->mutable_view().begin<double>(),
max_col->mutable_view().end<double>(),
0);
return make_tdigest_column(1,
make_empty_column(type_id::FLOAT64),
make_empty_column(type_id::FLOAT64),
std::move(offsets),
std::move(min_col),
std::move(max_col),
stream,
mr);
}
/**
* @brief Create an empty tdigest scalar.
*
* An empty tdigest scalar is a struct_scalar that contains a single row of length 0
*
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory.
*
* @returns An empty tdigest scalar.
*/
std::unique_ptr<scalar> make_empty_tdigest_scalar(rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto contents = make_empty_tdigest_column(stream, mr)->release();
return std::make_unique<struct_scalar>(
std::move(*std::make_unique<table>(std::move(contents.children))), true, stream, mr);
}
} // namespace detail
std::unique_ptr<column> percentile_approx(tdigest_column_view const& input,
column_view const& percentiles,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
tdigest_column_view tdv(input);
CUDF_EXPECTS(percentiles.type().id() == type_id::FLOAT64,
"percentile_approx expects float64 percentile inputs");
// output is a list column with each row containing percentiles.size() percentile values
auto offsets = cudf::make_fixed_width_column(
data_type{type_id::INT32}, input.size() + 1, mask_state::UNALLOCATED, stream, mr);
auto const all_empty_rows =
thrust::count_if(rmm::exec_policy(stream),
detail::size_begin(input),
detail::size_begin(input) + input.size(),
[] __device__(auto const x) { return x == 0; }) == input.size();
auto row_size_iter = thrust::make_constant_iterator(all_empty_rows ? 0 : percentiles.size());
thrust::exclusive_scan(rmm::exec_policy(stream),
row_size_iter,
row_size_iter + input.size() + 1,
offsets->mutable_view().begin<size_type>());
if (percentiles.size() == 0 || all_empty_rows) {
return cudf::make_lists_column(
input.size(),
std::move(offsets),
cudf::make_empty_column(type_id::FLOAT64),
input.size(),
cudf::detail::create_null_mask(
input.size(), mask_state::ALL_NULL, rmm::cuda_stream_view(stream), mr),
stream,
mr);
}
// if any of the input digests are empty, nullify the corresponding output rows (values will be
// uninitialized)
auto [bitmask, null_count] = [stream, mr, &tdv]() {
auto tdigest_is_empty = thrust::make_transform_iterator(
detail::size_begin(tdv),
[] __device__(size_type tdigest_size) -> size_type { return tdigest_size == 0; });
auto const null_count =
thrust::reduce(rmm::exec_policy(stream), tdigest_is_empty, tdigest_is_empty + tdv.size(), 0);
if (null_count == 0) {
return std::pair<rmm::device_buffer, size_type>{rmm::device_buffer{}, null_count};
}
return cudf::detail::valid_if(
tdigest_is_empty, tdigest_is_empty + tdv.size(), thrust::logical_not{}, stream, mr);
}();
return cudf::make_lists_column(input.size(),
std::move(offsets),
detail::compute_approx_percentiles(input, percentiles, stream, mr),
null_count,
std::move(bitmask),
stream,
mr);
}
} // namespace tdigest
std::unique_ptr<column> percentile_approx(tdigest_column_view const& input,
column_view const& percentiles,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return tdigest::percentile_approx(input, percentiles, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/groupby/groupby.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/groupby.hpp>
#include <cudf/detail/groupby/group_replace_nulls.hpp>
#include <cudf/detail/groupby/sort_helper.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/groupby.hpp>
#include <cudf/reduction/detail/histogram.hpp>
#include <cudf/strings/string_view.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <cudf/utilities/traits.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <memory>
#include <utility>
namespace cudf {
namespace groupby {
// Constructor
groupby::groupby(table_view const& keys,
null_policy include_null_keys,
sorted keys_are_sorted,
std::vector<order> const& column_order,
std::vector<null_order> const& null_precedence)
: _keys{keys},
_include_null_keys{include_null_keys},
_keys_are_sorted{keys_are_sorted},
_column_order{column_order},
_null_precedence{null_precedence}
{
}
// Select hash vs. sort groupby implementation
std::pair<std::unique_ptr<table>, std::vector<aggregation_result>> groupby::dispatch_aggregation(
host_span<aggregation_request const> requests,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// If sort groupby has been called once on this groupby object, then
// always use sort groupby from now on. Because once keys are sorted,
// all the aggs that can be done by hash groupby are efficiently done by
// sort groupby as well.
// Only use hash groupby if the keys aren't sorted and all requests can be
// satisfied with a hash implementation
if (_keys_are_sorted == sorted::NO and not _helper and
detail::hash::can_use_hash_groupby(requests)) {
return detail::hash::groupby(_keys, requests, _include_null_keys, stream, mr);
} else {
return sort_aggregate(requests, stream, mr);
}
}
// Destructor
// Needs to be in source file because sort_groupby_helper was forward declared
groupby::~groupby() = default;
namespace {
/**
* @brief Factory to construct empty result columns.
*
* Adds special handling for COLLECT_LIST/COLLECT_SET, because:
* 1. `make_empty_column()` does not support construction of nested columns.
* 2. Empty lists need empty child columns, to persist type information.
* Adds special handling for RANK, because it needs to return double type column when rank_method is
* AVERAGE or percentage is true.
*/
struct empty_column_constructor {
column_view values;
aggregation const& agg;
template <typename ValuesType, aggregation::Kind k>
std::unique_ptr<cudf::column> operator()() const
{
using namespace cudf;
using namespace cudf::detail;
if constexpr (k == aggregation::Kind::COLLECT_LIST || k == aggregation::Kind::COLLECT_SET) {
return make_lists_column(
0, make_empty_column(type_to_id<size_type>()), empty_like(values), 0, {});
}
if constexpr (k == aggregation::Kind::HISTOGRAM) {
return make_lists_column(0,
make_empty_column(type_to_id<size_type>()),
cudf::reduction::detail::make_empty_histogram_like(values),
0,
{});
}
if constexpr (k == aggregation::Kind::MERGE_HISTOGRAM) { return empty_like(values); }
if constexpr (k == aggregation::Kind::RANK) {
auto const& rank_agg = dynamic_cast<cudf::detail::rank_aggregation const&>(agg);
if (rank_agg._method == cudf::rank_method::AVERAGE or
rank_agg._percentage != rank_percentage::NONE)
return make_empty_column(type_to_id<double>());
return make_empty_column(target_type(values.type(), k));
}
// If `values` is LIST typed, and the aggregation results match the type,
// construct empty results based on `values`.
// Most generally, this applies if input type matches output type.
//
// Note: `target_type_t` is not recursive, and `ValuesType` does not consider children.
// It is important that `COLLECT_LIST` and `COLLECT_SET` are handled before this
// point, because `COLLECT_LIST(LIST)` produces `LIST<LIST>`, but `target_type_t`
// wouldn't know the difference.
if constexpr (std::is_same_v<target_type_t<ValuesType, k>, ValuesType>) {
return empty_like(values);
}
return make_empty_column(target_type(values.type(), k));
}
};
/// Make an empty table with appropriate types for requested aggs
template <typename RequestType>
auto empty_results(host_span<RequestType const> requests)
{
std::vector<aggregation_result> empty_results;
std::transform(
requests.begin(), requests.end(), std::back_inserter(empty_results), [](auto const& request) {
std::vector<std::unique_ptr<column>> results;
std::transform(
request.aggregations.begin(),
request.aggregations.end(),
std::back_inserter(results),
[&request](auto const& agg) {
return cudf::detail::dispatch_type_and_aggregation(
request.values.type(), agg->kind, empty_column_constructor{request.values, *agg});
});
return aggregation_result{std::move(results)};
});
return empty_results;
}
/// Verifies the agg requested on the request's values is valid
template <typename RequestType>
void verify_valid_requests(host_span<RequestType const> requests)
{
CUDF_EXPECTS(
std::all_of(
requests.begin(),
requests.end(),
[](auto const& request) {
return std::all_of(
request.aggregations.begin(), request.aggregations.end(), [&request](auto const& agg) {
auto values_type = cudf::is_dictionary(request.values.type())
? cudf::dictionary_column_view(request.values).keys().type()
: request.values.type();
return cudf::detail::is_valid_aggregation(values_type, agg->kind);
});
}),
"Invalid type/aggregation combination.");
}
} // namespace
// Compute aggregation requests
std::pair<std::unique_ptr<table>, std::vector<aggregation_result>> groupby::aggregate(
host_span<aggregation_request const> requests, rmm::mr::device_memory_resource* mr)
{
return aggregate(requests, cudf::get_default_stream(), mr);
}
// Compute aggregation requests
std::pair<std::unique_ptr<table>, std::vector<aggregation_result>> groupby::aggregate(
host_span<aggregation_request const> requests,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
CUDF_EXPECTS(
std::all_of(requests.begin(),
requests.end(),
[this](auto const& request) { return request.values.size() == _keys.num_rows(); }),
"Size mismatch between request values and groupby keys.");
verify_valid_requests(requests);
if (_keys.num_rows() == 0) { return {empty_like(_keys), empty_results(requests)}; }
return dispatch_aggregation(requests, stream, mr);
}
// Compute scan requests
std::pair<std::unique_ptr<table>, std::vector<aggregation_result>> groupby::scan(
host_span<scan_request const> requests, rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
CUDF_EXPECTS(
std::all_of(requests.begin(),
requests.end(),
[this](auto const& request) { return request.values.size() == _keys.num_rows(); }),
"Size mismatch between request values and groupby keys.");
verify_valid_requests(requests);
if (_keys.num_rows() == 0) { return std::pair(empty_like(_keys), empty_results(requests)); }
return sort_scan(requests, cudf::get_default_stream(), mr);
}
groupby::groups groupby::get_groups(table_view values, rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
auto const stream = cudf::get_default_stream();
auto grouped_keys = helper().sorted_keys(stream, mr);
auto const& group_offsets = helper().group_offsets(stream);
auto const group_offsets_vector = cudf::detail::make_std_vector_sync(group_offsets, stream);
if (not values.is_empty()) {
auto grouped_values = cudf::detail::gather(values,
helper().key_sort_order(stream),
cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
return groupby::groups{
std::move(grouped_keys), std::move(group_offsets_vector), std::move(grouped_values)};
} else {
return groupby::groups{std::move(grouped_keys), std::move(group_offsets_vector)};
}
}
std::pair<std::unique_ptr<table>, std::unique_ptr<table>> groupby::replace_nulls(
table_view const& values,
host_span<cudf::replace_policy const> replace_policies,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
CUDF_EXPECTS(_keys.num_rows() == values.num_rows(),
"Size mismatch between group labels and value.");
CUDF_EXPECTS(static_cast<cudf::size_type>(replace_policies.size()) == values.num_columns(),
"Size mismatch between num_columns and replace_policies.");
if (values.is_empty()) { return std::pair(empty_like(_keys), empty_like(values)); }
auto const stream = cudf::get_default_stream();
auto const& group_labels = helper().group_labels(stream);
std::vector<std::unique_ptr<column>> results;
results.reserve(values.num_columns());
std::transform(
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(values.num_columns()),
std::back_inserter(results),
[&](auto i) {
bool nullable = values.column(i).nullable();
auto final_mr = nullable ? rmm::mr::get_current_device_resource() : mr;
auto grouped_values = helper().grouped_values(values.column(i), stream, final_mr);
return nullable ? detail::group_replace_nulls(
*grouped_values, group_labels, replace_policies[i], stream, mr)
: std::move(grouped_values);
});
return std::pair(std::move(helper().sorted_keys(stream, mr)),
std::make_unique<table>(std::move(results)));
}
// Get the sort helper object
detail::sort::sort_groupby_helper& groupby::helper()
{
if (_helper) return *_helper;
_helper = std::make_unique<detail::sort::sort_groupby_helper>(
_keys, _include_null_keys, _keys_are_sorted, _null_precedence);
return *_helper;
};
std::pair<std::unique_ptr<table>, std::unique_ptr<table>> groupby::shift(
table_view const& values,
host_span<size_type const> offsets,
std::vector<std::reference_wrapper<scalar const>> const& fill_values,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
CUDF_EXPECTS(values.num_columns() == static_cast<size_type>(fill_values.size()),
"Mismatch number of fill_values and columns.");
CUDF_EXPECTS(
std::all_of(thrust::make_counting_iterator(0),
thrust::make_counting_iterator(values.num_columns()),
[&](auto i) { return values.column(i).type() == fill_values[i].get().type(); }),
"values and fill_value should have the same type.");
auto stream = cudf::get_default_stream();
std::vector<std::unique_ptr<column>> results;
auto const& group_offsets = helper().group_offsets(stream);
std::transform(
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(values.num_columns()),
std::back_inserter(results),
[&](size_type i) {
auto grouped_values =
helper().grouped_values(values.column(i), stream, rmm::mr::get_current_device_resource());
return cudf::detail::segmented_shift(
grouped_values->view(), group_offsets, offsets[i], fill_values[i].get(), stream, mr);
});
return std::pair(helper().sorted_keys(stream, mr),
std::make_unique<cudf::table>(std::move(results)));
}
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/hash/groupby_kernels.cuh
|
/*
* Copyright (c) 2020-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "multi_pass_kernels.cuh"
#include <cudf/detail/aggregation/aggregation.cuh>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/groupby.hpp>
#include <cudf/utilities/bit.hpp>
#include <thrust/pair.h>
namespace cudf {
namespace groupby {
namespace detail {
namespace hash {
/**
* @brief Compute single-pass aggregations and store results into a sparse
* `output_values` table, and populate `map` with indices of unique keys
*
* The hash map is built by inserting every row `i` from the `keys` and
* `values` tables as a single (key,value) pair. When the pair is inserted, if
* the key was not already present in the map, then the corresponding value is
* simply copied to the output. If the key was already present in the map,
* then the inserted `values` row is aggregated with the existing row. This
* aggregation is done for every element `j` in the row by applying aggregation
* operation `j` between the new and existing element.
*
* Instead of storing the entire rows from `input_keys` and `input_values` in
* the hashmap, we instead store the row indices. For example, when inserting
* row at index `i` from `input_keys` into the hash map, the value `i` is what
* gets stored for the hash map's "key". It is assumed the `map` was constructed
* with a custom comparator that uses these row indices to check for equality
* between key rows. For example, comparing two keys `k0` and `k1` will compare
* the two rows `input_keys[k0] ?= input_keys[k1]`
*
* Likewise, we store the row indices for the hash maps "values". These indices
* index into the `output_values` table. For a given key `k` (which is an index
* into `input_keys`), the corresponding value `v` indexes into `output_values`
* and stores the result of aggregating rows from `input_values` from rows of
* `input_keys` equivalent to the row at `k`.
*
* The exact size of the result is not known a priori, but can be upper bounded
* by the number of rows in `input_keys` & `input_values`. Therefore, it is
* assumed `output_values` has sufficient storage for an equivalent number of
* rows. In this way, after all rows are aggregated, `output_values` will likely
* be "sparse", meaning that not all rows contain the result of an aggregation.
*
* @tparam Map The type of the hash map
*/
template <typename Map>
struct compute_single_pass_aggs_fn {
Map map;
table_device_view input_values;
mutable_table_device_view output_values;
aggregation::Kind const* __restrict__ aggs;
bitmask_type const* __restrict__ row_bitmask;
bool skip_rows_with_nulls;
/**
* @brief Construct a new compute_single_pass_aggs_fn functor object
*
* @param map Hash map object to insert key,value pairs into.
* @param input_values The table whose rows will be aggregated in the values
* of the hash map
* @param output_values Table that stores the results of aggregating rows of
* `input_values`.
* @param aggs The set of aggregation operations to perform across the
* columns of the `input_values` rows
* @param row_bitmask Bitmask where bit `i` indicates the presence of a null
* value in row `i` of input keys. Only used if `skip_rows_with_nulls` is `true`
* @param skip_rows_with_nulls Indicates if rows in `input_keys` containing
* null values should be skipped. It `true`, it is assumed `row_bitmask` is a
* bitmask where bit `i` indicates the presence of a null value in row `i`.
*/
compute_single_pass_aggs_fn(Map map,
table_device_view input_values,
mutable_table_device_view output_values,
aggregation::Kind const* aggs,
bitmask_type const* row_bitmask,
bool skip_rows_with_nulls)
: map(map),
input_values(input_values),
output_values(output_values),
aggs(aggs),
row_bitmask(row_bitmask),
skip_rows_with_nulls(skip_rows_with_nulls)
{
}
__device__ void operator()(size_type i)
{
if (not skip_rows_with_nulls or cudf::bit_is_set(row_bitmask, i)) {
auto result = map.insert(thrust::make_pair(i, i));
cudf::detail::aggregate_row<true, true>(
output_values, result.first->second, input_values, i, aggs);
}
}
};
} // namespace hash
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/hash/groupby.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/common/utils.hpp>
#include <groupby/hash/groupby_kernels.cuh>
#include <cudf/aggregation.hpp>
#include <cudf/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/aggregation/aggregation.cuh>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/aggregation/result_cache.hpp>
#include <cudf/detail/binaryop.hpp>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/groupby.hpp>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/replace.hpp>
#include <cudf/detail/unary.hpp>
#include <cudf/detail/utilities/algorithm.cuh>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/groupby.hpp>
#include <cudf/hashing/detail/default_hash.cuh>
#include <cudf/scalar/scalar.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/table/table.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/traits.cuh>
#include <cudf/utilities/traits.hpp>
#include <hash/concurrent_unordered_map.cuh>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/copy.h>
#include <thrust/for_each.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <memory>
#include <unordered_set>
#include <utility>
#include <cuda/std/atomic>
namespace cudf {
namespace groupby {
namespace detail {
namespace hash {
namespace {
// TODO: replace it with `cuco::static_map`
// https://github.com/rapidsai/cudf/issues/10401
template <typename ComparatorType>
using map_type = concurrent_unordered_map<
cudf::size_type,
cudf::size_type,
cudf::experimental::row::hash::device_row_hasher<cudf::hashing::detail::default_hash,
cudf::nullate::DYNAMIC>,
ComparatorType>;
/**
* @brief List of aggregation operations that can be computed with a hash-based
* implementation.
*/
constexpr std::array<aggregation::Kind, 12> hash_aggregations{aggregation::SUM,
aggregation::PRODUCT,
aggregation::MIN,
aggregation::MAX,
aggregation::COUNT_VALID,
aggregation::COUNT_ALL,
aggregation::ARGMIN,
aggregation::ARGMAX,
aggregation::SUM_OF_SQUARES,
aggregation::MEAN,
aggregation::STD,
aggregation::VARIANCE};
// Could be hash: SUM, PRODUCT, MIN, MAX, COUNT_VALID, COUNT_ALL, ANY, ALL,
// Compound: MEAN(SUM, COUNT_VALID), VARIANCE, STD(MEAN (SUM, COUNT_VALID), COUNT_VALID),
// ARGMAX, ARGMIN
// TODO replace with std::find in C++20 onwards.
template <class T, size_t N>
constexpr bool array_contains(std::array<T, N> const& haystack, T needle)
{
for (auto const& val : haystack) {
if (val == needle) return true;
}
return false;
}
/**
* @brief Indicates whether the specified aggregation operation can be computed
* with a hash-based implementation.
*
* @param t The aggregation operation to verify
* @return true `t` is valid for a hash based groupby
* @return false `t` is invalid for a hash based groupby
*/
bool constexpr is_hash_aggregation(aggregation::Kind t)
{
return array_contains(hash_aggregations, t);
}
class groupby_simple_aggregations_collector final
: public cudf::detail::simple_aggregations_collector {
public:
using cudf::detail::simple_aggregations_collector::visit;
std::vector<std::unique_ptr<aggregation>> visit(data_type col_type,
cudf::detail::min_aggregation const&) override
{
std::vector<std::unique_ptr<aggregation>> aggs;
aggs.push_back(col_type.id() == type_id::STRING ? make_argmin_aggregation()
: make_min_aggregation());
return aggs;
}
std::vector<std::unique_ptr<aggregation>> visit(data_type col_type,
cudf::detail::max_aggregation const&) override
{
std::vector<std::unique_ptr<aggregation>> aggs;
aggs.push_back(col_type.id() == type_id::STRING ? make_argmax_aggregation()
: make_max_aggregation());
return aggs;
}
std::vector<std::unique_ptr<aggregation>> visit(data_type col_type,
cudf::detail::mean_aggregation const&) override
{
(void)col_type;
CUDF_EXPECTS(is_fixed_width(col_type), "MEAN aggregation expects fixed width type");
std::vector<std::unique_ptr<aggregation>> aggs;
aggs.push_back(make_sum_aggregation());
// COUNT_VALID
aggs.push_back(make_count_aggregation());
return aggs;
}
std::vector<std::unique_ptr<aggregation>> visit(data_type,
cudf::detail::var_aggregation const&) override
{
std::vector<std::unique_ptr<aggregation>> aggs;
aggs.push_back(make_sum_aggregation());
// COUNT_VALID
aggs.push_back(make_count_aggregation());
return aggs;
}
std::vector<std::unique_ptr<aggregation>> visit(data_type,
cudf::detail::std_aggregation const&) override
{
std::vector<std::unique_ptr<aggregation>> aggs;
aggs.push_back(make_sum_aggregation());
// COUNT_VALID
aggs.push_back(make_count_aggregation());
return aggs;
}
std::vector<std::unique_ptr<aggregation>> visit(
data_type, cudf::detail::correlation_aggregation const&) override
{
std::vector<std::unique_ptr<aggregation>> aggs;
aggs.push_back(make_sum_aggregation());
// COUNT_VALID
aggs.push_back(make_count_aggregation());
return aggs;
}
};
template <typename ComparatorType>
class hash_compound_agg_finalizer final : public cudf::detail::aggregation_finalizer {
column_view col;
data_type result_type;
cudf::detail::result_cache* sparse_results;
cudf::detail::result_cache* dense_results;
device_span<size_type const> gather_map;
map_type<ComparatorType> const& map;
bitmask_type const* __restrict__ row_bitmask;
rmm::cuda_stream_view stream;
rmm::mr::device_memory_resource* mr;
public:
using cudf::detail::aggregation_finalizer::visit;
hash_compound_agg_finalizer(column_view col,
cudf::detail::result_cache* sparse_results,
cudf::detail::result_cache* dense_results,
device_span<size_type const> gather_map,
map_type<ComparatorType> const& map,
bitmask_type const* row_bitmask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: col(col),
sparse_results(sparse_results),
dense_results(dense_results),
gather_map(gather_map),
map(map),
row_bitmask(row_bitmask),
stream(stream),
mr(mr)
{
result_type = cudf::is_dictionary(col.type()) ? cudf::dictionary_column_view(col).keys().type()
: col.type();
}
auto to_dense_agg_result(cudf::aggregation const& agg)
{
auto s = sparse_results->get_result(col, agg);
auto dense_result_table = cudf::detail::gather(table_view({std::move(s)}),
gather_map,
out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
return std::move(dense_result_table->release()[0]);
}
// Enables conversion of ARGMIN/ARGMAX into MIN/MAX
auto gather_argminmax(aggregation const& agg)
{
auto arg_result = to_dense_agg_result(agg);
// We make a view of ARG(MIN/MAX) result without a null mask and gather
// using this map. The values in data buffer of ARG(MIN/MAX) result
// corresponding to null values was initialized to ARG(MIN/MAX)_SENTINEL
// which is an out of bounds index value (-1) and causes the gathered
// value to be null.
column_view null_removed_map(
data_type(type_to_id<size_type>()),
arg_result->size(),
static_cast<void const*>(arg_result->view().template data<size_type>()),
nullptr,
0);
auto gather_argminmax =
cudf::detail::gather(table_view({col}),
null_removed_map,
arg_result->nullable() ? cudf::out_of_bounds_policy::NULLIFY
: cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
return std::move(gather_argminmax->release()[0]);
}
// Declare overloads for each kind of aggregation to dispatch
void visit(cudf::aggregation const& agg) override
{
if (dense_results->has_result(col, agg)) return;
dense_results->add_result(col, agg, to_dense_agg_result(agg));
}
void visit(cudf::detail::min_aggregation const& agg) override
{
if (dense_results->has_result(col, agg)) return;
if (result_type.id() == type_id::STRING) {
auto transformed_agg = make_argmin_aggregation();
dense_results->add_result(col, agg, gather_argminmax(*transformed_agg));
} else {
dense_results->add_result(col, agg, to_dense_agg_result(agg));
}
}
void visit(cudf::detail::max_aggregation const& agg) override
{
if (dense_results->has_result(col, agg)) return;
if (result_type.id() == type_id::STRING) {
auto transformed_agg = make_argmax_aggregation();
dense_results->add_result(col, agg, gather_argminmax(*transformed_agg));
} else {
dense_results->add_result(col, agg, to_dense_agg_result(agg));
}
}
void visit(cudf::detail::mean_aggregation const& agg) override
{
if (dense_results->has_result(col, agg)) return;
auto sum_agg = make_sum_aggregation();
auto count_agg = make_count_aggregation();
this->visit(*sum_agg);
this->visit(*count_agg);
column_view sum_result = dense_results->get_result(col, *sum_agg);
column_view count_result = dense_results->get_result(col, *count_agg);
auto result =
cudf::detail::binary_operation(sum_result,
count_result,
binary_operator::DIV,
cudf::detail::target_type(result_type, aggregation::MEAN),
stream,
mr);
dense_results->add_result(col, agg, std::move(result));
}
void visit(cudf::detail::var_aggregation const& agg) override
{
if (dense_results->has_result(col, agg)) return;
auto sum_agg = make_sum_aggregation();
auto count_agg = make_count_aggregation();
this->visit(*sum_agg);
this->visit(*count_agg);
column_view sum_result = sparse_results->get_result(col, *sum_agg);
column_view count_result = sparse_results->get_result(col, *count_agg);
auto values_view = column_device_view::create(col, stream);
auto sum_view = column_device_view::create(sum_result, stream);
auto count_view = column_device_view::create(count_result, stream);
auto var_result = make_fixed_width_column(
cudf::detail::target_type(result_type, agg.kind), col.size(), mask_state::ALL_NULL, stream);
auto var_result_view = mutable_column_device_view::create(var_result->mutable_view(), stream);
mutable_table_view var_table_view{{var_result->mutable_view()}};
cudf::detail::initialize_with_identity(var_table_view, {agg.kind}, stream);
thrust::for_each_n(
rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
col.size(),
::cudf::detail::var_hash_functor<map_type<ComparatorType>>{
map, row_bitmask, *var_result_view, *values_view, *sum_view, *count_view, agg._ddof});
sparse_results->add_result(col, agg, std::move(var_result));
dense_results->add_result(col, agg, to_dense_agg_result(agg));
}
void visit(cudf::detail::std_aggregation const& agg) override
{
if (dense_results->has_result(col, agg)) return;
auto var_agg = make_variance_aggregation(agg._ddof);
this->visit(*dynamic_cast<cudf::detail::var_aggregation*>(var_agg.get()));
column_view variance = dense_results->get_result(col, *var_agg);
auto result = cudf::detail::unary_operation(variance, unary_operator::SQRT, stream, mr);
dense_results->add_result(col, agg, std::move(result));
}
};
// flatten aggs to filter in single pass aggs
std::tuple<table_view, std::vector<aggregation::Kind>, std::vector<std::unique_ptr<aggregation>>>
flatten_single_pass_aggs(host_span<aggregation_request const> requests)
{
std::vector<column_view> columns;
std::vector<std::unique_ptr<aggregation>> aggs;
std::vector<aggregation::Kind> agg_kinds;
for (auto const& request : requests) {
auto const& agg_v = request.aggregations;
std::unordered_set<aggregation::Kind> agg_kinds_set;
auto insert_agg = [&](column_view const& request_values, std::unique_ptr<aggregation>&& agg) {
if (agg_kinds_set.insert(agg->kind).second) {
agg_kinds.push_back(agg->kind);
aggs.push_back(std::move(agg));
columns.push_back(request_values);
}
};
auto values_type = cudf::is_dictionary(request.values.type())
? cudf::dictionary_column_view(request.values).keys().type()
: request.values.type();
for (auto&& agg : agg_v) {
groupby_simple_aggregations_collector collector;
for (auto& agg_s : agg->get_simple_aggregations(values_type, collector)) {
insert_agg(request.values, std::move(agg_s));
}
}
}
return std::make_tuple(table_view(columns), std::move(agg_kinds), std::move(aggs));
}
/**
* @brief Gather sparse results into dense using `gather_map` and add to
* `dense_cache`
*
* @see groupby_null_templated()
*/
template <typename ComparatorType>
void sparse_to_dense_results(table_view const& keys,
host_span<aggregation_request const> requests,
cudf::detail::result_cache* sparse_results,
cudf::detail::result_cache* dense_results,
device_span<size_type const> gather_map,
map_type<ComparatorType> const& map,
bool keys_have_nulls,
null_policy include_null_keys,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto row_bitmask =
cudf::detail::bitmask_and(keys, stream, rmm::mr::get_current_device_resource()).first;
bool skip_key_rows_with_nulls = keys_have_nulls and include_null_keys == null_policy::EXCLUDE;
bitmask_type const* row_bitmask_ptr =
skip_key_rows_with_nulls ? static_cast<bitmask_type*>(row_bitmask.data()) : nullptr;
for (auto const& request : requests) {
auto const& agg_v = request.aggregations;
auto const& col = request.values;
// Given an aggregation, this will get the result from sparse_results and
// convert and return dense, compacted result
auto finalizer = hash_compound_agg_finalizer(
col, sparse_results, dense_results, gather_map, map, row_bitmask_ptr, stream, mr);
for (auto&& agg : agg_v) {
agg->finalize(finalizer);
}
}
}
// make table that will hold sparse results
auto create_sparse_results_table(table_view const& flattened_values,
std::vector<aggregation::Kind> aggs,
rmm::cuda_stream_view stream)
{
// TODO single allocation - room for performance improvement
std::vector<std::unique_ptr<column>> sparse_columns;
std::transform(
flattened_values.begin(),
flattened_values.end(),
aggs.begin(),
std::back_inserter(sparse_columns),
[stream](auto const& col, auto const& agg) {
bool nullable =
(agg == aggregation::COUNT_VALID or agg == aggregation::COUNT_ALL)
? false
: (col.has_nulls() or agg == aggregation::VARIANCE or agg == aggregation::STD);
auto mask_flag = (nullable) ? mask_state::ALL_NULL : mask_state::UNALLOCATED;
auto col_type = cudf::is_dictionary(col.type())
? cudf::dictionary_column_view(col).keys().type()
: col.type();
return make_fixed_width_column(
cudf::detail::target_type(col_type, agg), col.size(), mask_flag, stream);
});
table sparse_table(std::move(sparse_columns));
mutable_table_view table_view = sparse_table.mutable_view();
cudf::detail::initialize_with_identity(table_view, aggs, stream);
return sparse_table;
}
/**
* @brief Computes all aggregations from `requests` that require a single pass
* over the data and stores the results in `sparse_results`
*/
template <typename ComparatorType>
void compute_single_pass_aggs(table_view const& keys,
host_span<aggregation_request const> requests,
cudf::detail::result_cache* sparse_results,
map_type<ComparatorType>& map,
bool keys_have_nulls,
null_policy include_null_keys,
rmm::cuda_stream_view stream)
{
// flatten the aggs to a table that can be operated on by aggregate_row
auto const [flattened_values, agg_kinds, aggs] = flatten_single_pass_aggs(requests);
// make table that will hold sparse results
table sparse_table = create_sparse_results_table(flattened_values, agg_kinds, stream);
// prepare to launch kernel to do the actual aggregation
auto d_sparse_table = mutable_table_device_view::create(sparse_table, stream);
auto d_values = table_device_view::create(flattened_values, stream);
auto const d_aggs = cudf::detail::make_device_uvector_async(
agg_kinds, stream, rmm::mr::get_current_device_resource());
auto const skip_key_rows_with_nulls =
keys_have_nulls and include_null_keys == null_policy::EXCLUDE;
auto row_bitmask =
skip_key_rows_with_nulls
? cudf::detail::bitmask_and(keys, stream, rmm::mr::get_current_device_resource()).first
: rmm::device_buffer{};
thrust::for_each_n(rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
keys.num_rows(),
hash::compute_single_pass_aggs_fn<map_type<ComparatorType>>{
map,
*d_values,
*d_sparse_table,
d_aggs.data(),
static_cast<bitmask_type*>(row_bitmask.data()),
skip_key_rows_with_nulls});
// Add results back to sparse_results cache
auto sparse_result_cols = sparse_table.release();
for (size_t i = 0; i < aggs.size(); i++) {
// Note that the cache will make a copy of this temporary aggregation
sparse_results->add_result(
flattened_values.column(i), *aggs[i], std::move(sparse_result_cols[i]));
}
}
/**
* @brief Computes and returns a device vector containing all populated keys in
* `map`.
*/
template <typename ComparatorType>
rmm::device_uvector<size_type> extract_populated_keys(map_type<ComparatorType> const& map,
size_type num_keys,
rmm::cuda_stream_view stream)
{
rmm::device_uvector<size_type> populated_keys(num_keys, stream);
auto const get_key = [] __device__(auto const& element) { return element.first; }; // first = key
auto const key_used = [unused = map.get_unused_key()] __device__(auto key) {
return key != unused;
};
auto const key_itr = thrust::make_transform_iterator(map.data(), get_key);
auto const end_it = cudf::detail::copy_if_safe(
key_itr, key_itr + map.capacity(), populated_keys.begin(), key_used, stream);
populated_keys.resize(std::distance(populated_keys.begin(), end_it), stream);
return populated_keys;
}
/**
* @brief Computes groupby using hash table.
*
* First, we create a hash table that stores the indices of unique rows in
* `keys`. The upper limit on the number of values in this map is the number
* of rows in `keys`.
*
* To store the results of aggregations, we create temporary sparse columns
* which have the same size as input value columns. Using the hash map, we
* determine the location within the sparse column to write the result of the
* aggregation into.
*
* The sparse column results of all aggregations are stored into the cache
* `sparse_results`. This enables the use of previously calculated results in
* other aggregations.
*
* All the aggregations which can be computed in a single pass are computed
* first, in a combined kernel. Then using these results, aggregations that
* require multiple passes, will be computed.
*
* Finally, using the hash map, we generate a vector of indices of populated
* values in sparse result columns. Then, for each aggregation originally
* requested in `requests`, we gather sparse results into a column of dense
* results using the aforementioned index vector. Dense results are stored into
* the in/out parameter `cache`.
*/
std::unique_ptr<table> groupby(table_view const& keys,
host_span<aggregation_request const> requests,
cudf::detail::result_cache* cache,
bool const keys_have_nulls,
null_policy const include_null_keys,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto const num_keys = keys.num_rows();
auto const null_keys_are_equal = null_equality::EQUAL;
auto const has_null = nullate::DYNAMIC{cudf::has_nested_nulls(keys)};
auto preprocessed_keys = cudf::experimental::row::hash::preprocessed_table::create(keys, stream);
auto const comparator = cudf::experimental::row::equality::self_comparator{preprocessed_keys};
auto const row_hash = cudf::experimental::row::hash::row_hasher{std::move(preprocessed_keys)};
auto const d_row_hash = row_hash.device_hasher(has_null);
size_type constexpr unused_key{std::numeric_limits<size_type>::max()};
size_type constexpr unused_value{std::numeric_limits<size_type>::max()};
// Cache of sparse results where the location of aggregate value in each
// column is indexed by the hash map
cudf::detail::result_cache sparse_results(requests.size());
auto const comparator_helper = [&](auto const d_key_equal) {
using allocator_type = typename map_type<decltype(d_key_equal)>::allocator_type;
auto const map = map_type<decltype(d_key_equal)>::create(compute_hash_table_size(num_keys),
stream,
unused_key,
unused_value,
d_row_hash,
d_key_equal,
allocator_type());
// Compute all single pass aggs first
compute_single_pass_aggs(
keys, requests, &sparse_results, *map, keys_have_nulls, include_null_keys, stream);
// Extract the populated indices from the hash map and create a gather map.
// Gathering using this map from sparse results will give dense results.
auto gather_map = extract_populated_keys(*map, keys.num_rows(), stream);
// Compact all results from sparse_results and insert into cache
sparse_to_dense_results(keys,
requests,
&sparse_results,
cache,
gather_map,
*map,
keys_have_nulls,
include_null_keys,
stream,
mr);
return cudf::detail::gather(keys,
gather_map,
out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
};
if (cudf::detail::has_nested_columns(keys)) {
auto const d_key_equal = comparator.equal_to<true>(has_null, null_keys_are_equal);
return comparator_helper(d_key_equal);
} else {
auto const d_key_equal = comparator.equal_to<false>(has_null, null_keys_are_equal);
return comparator_helper(d_key_equal);
}
}
} // namespace
/**
* @brief Indicates if a set of aggregation requests can be satisfied with a
* hash-based groupby implementation.
*
* @param requests The set of columns to aggregate and the aggregations to
* perform
* @return true A hash-based groupby should be used
* @return false A hash-based groupby should not be used
*/
bool can_use_hash_groupby(host_span<aggregation_request const> requests)
{
return std::all_of(requests.begin(), requests.end(), [](aggregation_request const& r) {
auto const v_type = is_dictionary(r.values.type())
? cudf::dictionary_column_view(r.values).keys().type()
: r.values.type();
// Currently, input values (not keys) of STRUCT and LIST types are not supported in any of
// hash-based aggregations. For those situations, we fallback to sort-based aggregations.
if (v_type.id() == type_id::STRUCT or v_type.id() == type_id::LIST) { return false; }
return std::all_of(r.aggregations.begin(), r.aggregations.end(), [v_type](auto const& a) {
return cudf::has_atomic_support(cudf::detail::target_type(v_type, a->kind)) and
is_hash_aggregation(a->kind);
});
});
}
// Hash-based groupby
std::pair<std::unique_ptr<table>, std::vector<aggregation_result>> groupby(
table_view const& keys,
host_span<aggregation_request const> requests,
null_policy include_null_keys,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
cudf::detail::result_cache cache(requests.size());
std::unique_ptr<table> unique_keys =
groupby(keys, requests, &cache, cudf::has_nulls(keys), include_null_keys, stream, mr);
return std::pair(std::move(unique_keys), extract_results(requests, cache, stream, mr));
}
} // namespace hash
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/hash/multi_pass_kernels.cuh
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/aggregation.hpp>
#include <cudf/column/column_device_view.cuh>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/utilities/assert.cuh>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/type_dispatcher.hpp>
#include <cuda/atomic>
#include <cmath>
namespace cudf {
namespace detail {
template <typename Map, bool target_has_nulls = true, bool source_has_nulls = true>
struct var_hash_functor {
Map const map;
bitmask_type const* __restrict__ row_bitmask;
mutable_column_device_view target;
column_device_view source;
column_device_view sum;
column_device_view count;
size_type ddof;
var_hash_functor(Map const map,
bitmask_type const* row_bitmask,
mutable_column_device_view target,
column_device_view source,
column_device_view sum,
column_device_view count,
size_type ddof)
: map(map),
row_bitmask(row_bitmask),
target(target),
source(source),
sum(sum),
count(count),
ddof(ddof)
{
}
template <typename Source>
constexpr static bool is_supported()
{
return is_numeric<Source>() && !is_fixed_point<Source>();
}
template <typename Source>
__device__ std::enable_if_t<!is_supported<Source>()> operator()(column_device_view const& source,
size_type source_index,
size_type target_index) noexcept
{
CUDF_UNREACHABLE("Invalid source type for std, var aggregation combination.");
}
template <typename Source>
__device__ std::enable_if_t<is_supported<Source>()> operator()(column_device_view const& source,
size_type source_index,
size_type target_index) noexcept
{
using Target = target_type_t<Source, aggregation::VARIANCE>;
using SumType = target_type_t<Source, aggregation::SUM>;
using CountType = target_type_t<Source, aggregation::COUNT_VALID>;
if (source_has_nulls and source.is_null(source_index)) return;
CountType group_size = count.element<CountType>(target_index);
if (group_size == 0 or group_size - ddof <= 0) return;
auto x = static_cast<Target>(source.element<Source>(source_index));
auto mean = static_cast<Target>(sum.element<SumType>(target_index)) / group_size;
Target result = (x - mean) * (x - mean) / (group_size - ddof);
cuda::atomic_ref<Target, cuda::thread_scope_device> ref{target.element<Target>(target_index)};
ref.fetch_add(result, cuda::std::memory_order_relaxed);
// STD sqrt is applied in finalize()
if (target_has_nulls and target.is_null(target_index)) { target.set_valid(target_index); }
}
__device__ inline void operator()(size_type source_index)
{
if (row_bitmask == nullptr or cudf::bit_is_set(row_bitmask, source_index)) {
auto result = map.find(source_index);
auto target_index = result->second;
auto col = source;
auto source_type = source.type();
if (source_type.id() == type_id::DICTIONARY32) {
col = source.child(cudf::dictionary_column_view::keys_column_index);
source_type = col.type();
source_index = static_cast<size_type>(source.element<dictionary32>(source_index));
}
type_dispatcher(source_type, *this, col, source_index, target_index);
}
}
};
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_product.cu
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/utilities/span.hpp>
#include <groupby/sort/group_single_pass_reduction_util.cuh>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_product(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
return type_dispatcher(values_type,
group_reduction_dispatcher<aggregation::PRODUCT>{},
values,
num_groups,
group_labels,
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_m2.cu
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/null_mask.hpp>
#include <cudf/dictionary/detail/iterator.cuh>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/utilities/span.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/reduce.h>
#include <thrust/transform.h>
namespace cudf {
namespace groupby {
namespace detail {
namespace {
template <typename ResultType, typename Iterator>
struct m2_transform {
column_device_view const d_values;
Iterator const values_iter;
ResultType const* d_means;
size_type const* d_group_labels;
__device__ ResultType operator()(size_type const idx) const noexcept
{
if (d_values.is_null(idx)) { return 0.0; }
auto const x = static_cast<ResultType>(values_iter[idx]);
auto const group_idx = d_group_labels[idx];
auto const mean = d_means[group_idx];
auto const diff = x - mean;
return diff * diff;
}
};
template <typename ResultType, typename Iterator>
void compute_m2_fn(column_device_view const& values,
Iterator values_iter,
cudf::device_span<size_type const> group_labels,
ResultType const* d_means,
ResultType* d_result,
rmm::cuda_stream_view stream)
{
auto m2_fn = m2_transform<ResultType, decltype(values_iter)>{
values, values_iter, d_means, group_labels.data()};
auto const itr = thrust::counting_iterator<size_type>(0);
// Using a temporary buffer for intermediate transform results instead of
// using the transform-iterator directly in thrust::reduce_by_key
// improves compile-time significantly.
auto m2_vals = rmm::device_uvector<ResultType>(values.size(), stream);
thrust::transform(rmm::exec_policy(stream), itr, itr + values.size(), m2_vals.begin(), m2_fn);
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
m2_vals.begin(),
thrust::make_discard_iterator(),
d_result);
}
struct m2_functor {
template <typename T>
std::enable_if_t<std::is_arithmetic_v<T>, std::unique_ptr<column>> operator()(
column_view const& values,
column_view const& group_means,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using result_type = cudf::detail::target_type_t<T, aggregation::Kind::M2>;
auto result = make_numeric_column(data_type(type_to_id<result_type>()),
group_means.size(),
mask_state::UNALLOCATED,
stream,
mr);
auto const values_dv_ptr = column_device_view::create(values, stream);
auto const d_values = *values_dv_ptr;
auto const d_means = group_means.data<result_type>();
auto const d_result = result->mutable_view().data<result_type>();
if (!cudf::is_dictionary(values.type())) {
auto const values_iter = d_values.begin<T>();
compute_m2_fn(d_values, values_iter, group_labels, d_means, d_result, stream);
} else {
auto const values_iter =
cudf::dictionary::detail::make_dictionary_iterator<T>(*values_dv_ptr);
compute_m2_fn(d_values, values_iter, group_labels, d_means, d_result, stream);
}
// M2 column values should have the same bitmask as means's.
if (group_means.nullable()) {
result->set_null_mask(cudf::detail::copy_bitmask(group_means, stream, mr),
group_means.null_count());
}
return result;
}
template <typename T, typename... Args>
std::enable_if_t<!std::is_arithmetic_v<T>, std::unique_ptr<column>> operator()(Args&&...)
{
CUDF_FAIL("Only numeric types are supported in M2 groupby aggregation");
}
};
} // namespace
std::unique_ptr<column> group_m2(column_view const& values,
column_view const& group_means,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
return type_dispatcher(values_type, m2_functor{}, values, group_means, group_labels, stream, mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_quantiles.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "group_reductions.hpp"
#include <quantiles/quantiles_util.hpp>
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/dictionary/detail/iterator.cuh>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/execution_policy.h>
#include <thrust/for_each.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/transform.h>
namespace cudf {
namespace groupby {
namespace detail {
namespace {
template <typename ResultType, typename Iterator>
struct calculate_quantile_fn {
Iterator values_iter;
column_device_view d_group_size;
mutable_column_device_view d_result;
size_type const* d_group_offset;
double const* d_quantiles;
size_type num_quantiles;
interpolation interpolation;
size_type* null_count;
__device__ void operator()(size_type i)
{
size_type segment_size = d_group_size.element<size_type>(i);
auto d_itr = values_iter + d_group_offset[i];
thrust::transform(thrust::seq,
d_quantiles,
d_quantiles + num_quantiles,
d_result.data<ResultType>() + i * num_quantiles,
[d_itr, segment_size, interpolation = interpolation](auto q) {
return cudf::detail::select_quantile_data<ResultType>(
d_itr, segment_size, q, interpolation);
});
size_type offset = i * num_quantiles;
thrust::for_each_n(thrust::seq,
thrust::make_counting_iterator(0),
num_quantiles,
[d_result = d_result, segment_size, offset, this](size_type j) {
if (segment_size == 0) {
d_result.set_null(offset + j);
atomicAdd(this->null_count, 1);
} else {
d_result.set_valid(offset + j);
}
});
}
};
struct quantiles_functor {
template <typename T>
std::enable_if_t<std::is_arithmetic_v<T>, std::unique_ptr<column>> operator()(
column_view const& values,
column_view const& group_sizes,
cudf::device_span<size_type const> group_offsets,
size_type const num_groups,
device_span<double const> quantile,
interpolation interpolation,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using ResultType = cudf::detail::target_type_t<T, aggregation::QUANTILE>;
auto result = make_numeric_column(data_type(type_to_id<ResultType>()),
group_sizes.size() * quantile.size(),
mask_state::UNINITIALIZED,
stream,
mr);
// TODO (dm): Support for no-materialize index indirection values
// TODO (dm): Future optimization: add column order to aggregation request
// so that sorting isn't required. Then add support for pre-sorted
// prepare args to be used by lambda below
auto values_view = column_device_view::create(values, stream);
auto group_size_view = column_device_view::create(group_sizes, stream);
auto result_view = mutable_column_device_view::create(result->mutable_view(), stream);
auto null_count = rmm::device_scalar<cudf::size_type>(0, stream, mr);
// For each group, calculate quantile
if (!cudf::is_dictionary(values.type())) {
auto values_iter = values_view->begin<T>();
thrust::for_each_n(rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
num_groups,
calculate_quantile_fn<ResultType, decltype(values_iter)>{
values_iter,
*group_size_view,
*result_view,
group_offsets.data(),
quantile.data(),
static_cast<size_type>(quantile.size()),
interpolation,
null_count.data()});
} else {
auto values_iter = cudf::dictionary::detail::make_dictionary_iterator<T>(*values_view);
thrust::for_each_n(rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
num_groups,
calculate_quantile_fn<ResultType, decltype(values_iter)>{
values_iter,
*group_size_view,
*result_view,
group_offsets.data(),
quantile.data(),
static_cast<size_type>(quantile.size()),
interpolation,
null_count.data()});
}
result->set_null_count(null_count.value(stream));
return result;
}
template <typename T, typename... Args>
std::enable_if_t<!std::is_arithmetic_v<T>, std::unique_ptr<column>> operator()(Args&&...)
{
CUDF_FAIL("Only arithmetic types are supported in quantiles");
}
};
} // namespace
// TODO: add optional check for is_sorted. Use context.flag_sorted
std::unique_ptr<column> group_quantiles(column_view const& values,
column_view const& group_sizes,
cudf::device_span<size_type const> group_offsets,
size_type const num_groups,
std::vector<double> const& quantiles,
interpolation interp,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto dv_quantiles = cudf::detail::make_device_uvector_async(
quantiles, stream, rmm::mr::get_current_device_resource());
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
return type_dispatcher(values_type,
quantiles_functor{},
values,
group_sizes,
group_offsets,
num_groups,
dv_quantiles,
interp,
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_histogram.cu
|
/*
* Copyright (c) 2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <lists/utilities.hpp>
#include <cudf/aggregation.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/labeling/label_segments.cuh>
#include <cudf/reduction/detail/histogram.hpp>
#include <cudf/structs/structs_column_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/device_buffer.hpp>
#include <thrust/gather.h>
namespace cudf::groupby::detail {
namespace {
std::unique_ptr<column> build_histogram(column_view const& values,
cudf::device_span<size_type const> group_labels,
std::optional<column_view> const& partial_counts,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(static_cast<size_t>(values.size()) == group_labels.size(),
"Size of values column should be the same as that of group labels.",
std::invalid_argument);
// Attach group labels to the input values.
auto const labels_cv = column_view{data_type{type_to_id<size_type>()},
static_cast<size_type>(group_labels.size()),
group_labels.data(),
nullptr,
0};
auto const labeled_values = table_view{{labels_cv, values}};
// Build histogram for the labeled values.
auto [distinct_indices, distinct_counts] =
cudf::reduction::detail::compute_row_frequencies(labeled_values, partial_counts, stream, mr);
// Gather the distinct rows for the output histogram.
auto out_table = cudf::detail::gather(labeled_values,
*distinct_indices,
out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
// Build offsets for the output lists column containing output histograms.
// Each list will be a histogram corresponding to one value group.
auto out_offsets = cudf::lists::detail::reconstruct_offsets(
out_table->get_column(0).view(), num_groups, stream, mr);
std::vector<std::unique_ptr<column>> struct_children;
struct_children.emplace_back(std::move(out_table->release().back()));
struct_children.emplace_back(std::move(distinct_counts));
auto out_structs = make_structs_column(static_cast<size_type>(distinct_indices->size()),
std::move(struct_children),
0,
{},
stream,
mr);
return make_lists_column(
num_groups, std::move(out_offsets), std::move(out_structs), 0, {}, stream, mr);
}
} // namespace
std::unique_ptr<column> group_histogram(column_view const& values,
cudf::device_span<size_type const> group_labels,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Empty group should be handled before reaching here.
CUDF_EXPECTS(num_groups > 0, "Group should not be empty.", std::invalid_argument);
return build_histogram(values, group_labels, std::nullopt, num_groups, stream, mr);
}
std::unique_ptr<column> group_merge_histogram(column_view const& values,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Empty group should be handled before reaching here.
CUDF_EXPECTS(num_groups > 0, "Group should not be empty.", std::invalid_argument);
// The input must be a lists column without nulls.
CUDF_EXPECTS(!values.has_nulls(), "The input column must not have nulls.", std::invalid_argument);
CUDF_EXPECTS(values.type().id() == type_id::LIST,
"The input of MERGE_HISTOGRAM aggregation must be a lists column.",
std::invalid_argument);
// Child of the input lists column must be a structs column without nulls,
// and its second child is a columns of integer type having no nulls.
auto const lists_cv = lists_column_view{values};
auto const histogram_cv = lists_cv.get_sliced_child(stream);
CUDF_EXPECTS(!histogram_cv.has_nulls(),
"Child of the input lists column must not have nulls.",
std::invalid_argument);
CUDF_EXPECTS(histogram_cv.type().id() == type_id::STRUCT && histogram_cv.num_children() == 2,
"The input column has invalid histograms structure.",
std::invalid_argument);
CUDF_EXPECTS(
cudf::is_integral(histogram_cv.child(1).type()) && !histogram_cv.child(1).has_nulls(),
"The input column has invalid histograms structure.",
std::invalid_argument);
// Concatenate the histograms corresponding to the same key values.
// That is equivalent to creating a new lists column (view) from the input lists column
// with new offsets gathered as below.
auto new_offsets = rmm::device_uvector<size_type>(num_groups + 1, stream);
thrust::gather(rmm::exec_policy(stream),
group_offsets.begin(),
group_offsets.end(),
lists_cv.offsets_begin(),
new_offsets.begin());
// Generate labels for the new lists.
auto key_labels = rmm::device_uvector<size_type>(histogram_cv.size(), stream);
cudf::detail::label_segments(
new_offsets.begin(), new_offsets.end(), key_labels.begin(), key_labels.end(), stream);
auto const structs_cv = structs_column_view{histogram_cv};
auto const input_values = structs_cv.get_sliced_child(0, stream);
auto const input_counts = structs_cv.get_sliced_child(1, stream);
return build_histogram(input_values, key_labels, input_counts, num_groups, stream, mr);
}
} // namespace cudf::groupby::detail
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_sum_scan.cu
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/sort/group_scan_util.cuh>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> sum_scan(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return type_dispatcher(values.type(),
group_scan_dispatcher<aggregation::SUM>{},
values,
num_groups,
group_labels,
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_single_pass_reduction_util.cuh
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <reductions/nested_type_minmax_util.cuh>
#include <cudf/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/aggregation/aggregation.cuh>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/utilities/element_argminmax.cuh>
#include <cudf/detail/valid_if.cuh>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/functional.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/reduce.h>
namespace cudf {
namespace groupby {
namespace detail {
/**
* @brief Value accessor for column which supports dictionary column too.
*
* This is similar to `value_accessor` in `column_device_view.cuh` but with support of dictionary
* type.
*
* @tparam T Type of the underlying column. For dictionary column, type of the key column.
*/
template <typename T>
struct value_accessor {
column_device_view const col;
bool const is_dict;
value_accessor(column_device_view const& col) : col(col), is_dict(cudf::is_dictionary(col.type()))
{
}
__device__ T value(size_type i) const
{
if (is_dict) {
auto keys = col.child(dictionary_column_view::keys_column_index);
return keys.element<T>(static_cast<size_type>(col.element<dictionary32>(i)));
} else {
return col.element<T>(i);
}
}
__device__ auto operator()(size_type i) const { return value(i); }
};
/**
* @brief Null replaced value accessor for column which supports dictionary column too.
* For null value, returns null `init` value
*
* @tparam SourceType Type of the underlying column. For dictionary column, type of the key column.
* @tparam TargetType Type that is used for computation.
*/
template <typename SourceType, typename TargetType>
struct null_replaced_value_accessor : value_accessor<SourceType> {
using super_t = value_accessor<SourceType>;
TargetType const init;
bool const has_nulls;
null_replaced_value_accessor(column_device_view const& col,
TargetType const& init,
bool const has_nulls)
: super_t(col), init(init), has_nulls(has_nulls)
{
}
__device__ TargetType operator()(size_type i) const
{
return has_nulls && super_t::col.is_null_nocheck(i)
? init
: static_cast<TargetType>(super_t::value(i));
}
};
// Error case when no other overload or specialization is available
template <aggregation::Kind K, typename T, typename Enable = void>
struct group_reduction_functor {
template <typename... Args>
static std::unique_ptr<column> invoke(Args&&...)
{
CUDF_FAIL("Unsupported groupby reduction type-agg combination.");
}
};
template <aggregation::Kind K>
struct group_reduction_dispatcher {
template <typename T>
std::unique_ptr<column> operator()(column_view const& values,
size_type num_groups,
cudf::device_span<cudf::size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return group_reduction_functor<K, T>::invoke(values, num_groups, group_labels, stream, mr);
}
};
/**
* @brief Check if the given aggregation K with data type T is supported in groupby reduction.
*/
template <aggregation::Kind K, typename T>
static constexpr bool is_group_reduction_supported()
{
switch (K) {
case aggregation::SUM:
return cudf::is_numeric<T>() || cudf::is_duration<T>() || cudf::is_fixed_point<T>();
case aggregation::PRODUCT: return cudf::detail::is_product_supported<T>();
case aggregation::MIN:
case aggregation::MAX: return cudf::is_fixed_width<T>() and is_relationally_comparable<T, T>();
case aggregation::ARGMIN:
case aggregation::ARGMAX: return is_relationally_comparable<T, T>() or cudf::is_nested<T>();
default: return false;
}
}
template <aggregation::Kind K, typename T>
struct group_reduction_functor<
K,
T,
std::enable_if_t<is_group_reduction_supported<K, T>() && !cudf::is_nested<T>()>> {
static std::unique_ptr<column> invoke(column_view const& values,
size_type num_groups,
cudf::device_span<cudf::size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using SourceDType = device_storage_type_t<T>;
using ResultType = cudf::detail::target_type_t<T, K>;
using ResultDType = device_storage_type_t<ResultType>;
auto result_type = is_fixed_point<ResultType>()
? data_type{type_to_id<ResultType>(), values.type().scale()}
: data_type{type_to_id<ResultType>()};
std::unique_ptr<column> result =
make_fixed_width_column(result_type, num_groups, mask_state::UNALLOCATED, stream, mr);
if (values.is_empty()) { return result; }
// Perform segmented reduction.
auto const do_reduction = [&](auto const& inp_iter, auto const& out_iter, auto const& binop) {
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.data(),
group_labels.data() + group_labels.size(),
inp_iter,
thrust::make_discard_iterator(),
out_iter,
thrust::equal_to{},
binop);
};
auto const d_values_ptr = column_device_view::create(values, stream);
auto const result_begin = result->mutable_view().template begin<ResultDType>();
if constexpr (K == aggregation::ARGMAX || K == aggregation::ARGMIN) {
auto const count_iter = thrust::make_counting_iterator<ResultType>(0);
auto const binop = cudf::detail::element_argminmax_fn<T>{
*d_values_ptr, values.has_nulls(), K == aggregation::ARGMIN};
do_reduction(count_iter, result_begin, binop);
} else {
using OpType = cudf::detail::corresponding_operator_t<K>;
auto init = OpType::template identity<ResultDType>();
auto inp_values = cudf::detail::make_counting_transform_iterator(
0,
null_replaced_value_accessor<SourceDType, ResultDType>{
*d_values_ptr, init, values.has_nulls()});
do_reduction(inp_values, result_begin, OpType{});
}
if (values.has_nulls()) {
rmm::device_uvector<bool> validity(num_groups, stream);
do_reduction(cudf::detail::make_validity_iterator(*d_values_ptr),
validity.begin(),
thrust::logical_or{});
auto [null_mask, null_count] =
cudf::detail::valid_if(validity.begin(), validity.end(), thrust::identity{}, stream, mr);
result->set_null_mask(std::move(null_mask), null_count);
}
return result;
}
};
template <aggregation::Kind K, typename T>
struct group_reduction_functor<
K,
T,
std::enable_if_t<is_group_reduction_supported<K, T>() && cudf::is_nested<T>()>> {
static std::unique_ptr<column> invoke(column_view const& values,
size_type num_groups,
cudf::device_span<cudf::size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// This is be expected to be size_type.
using ResultType = cudf::detail::target_type_t<T, K>;
auto result = make_fixed_width_column(
data_type{type_to_id<ResultType>()}, num_groups, mask_state::UNALLOCATED, stream, mr);
if (values.is_empty()) { return result; }
// Perform segmented reduction to find ARGMIN/ARGMAX.
auto const do_reduction = [&](auto const& inp_iter, auto const& out_iter, auto const& binop) {
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.data(),
group_labels.data() + group_labels.size(),
inp_iter,
thrust::make_discard_iterator(),
out_iter,
thrust::equal_to{},
binop);
};
auto const count_iter = thrust::make_counting_iterator<ResultType>(0);
auto const result_begin = result->mutable_view().template begin<ResultType>();
auto const binop_generator =
cudf::reduction::detail::comparison_binop_generator::create<K>(values, stream);
do_reduction(count_iter, result_begin, binop_generator.binop());
if (values.has_nulls()) {
// Generate bitmask for the output by segmented reduction of the input bitmask.
auto const d_values_ptr = column_device_view::create(values, stream);
auto validity = rmm::device_uvector<bool>(num_groups, stream);
do_reduction(cudf::detail::make_validity_iterator(*d_values_ptr),
validity.begin(),
thrust::logical_or{});
auto [null_mask, null_count] =
cudf::detail::valid_if(validity.begin(), validity.end(), thrust::identity{}, stream, mr);
result->set_null_mask(std::move(null_mask), null_count);
}
return result;
}
};
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_nth_element.cu
|
/*
* Copyright (c) 2020-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <thrust/iterator/discard_iterator.h>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/reduce.h>
#include <thrust/scan.h>
#include <thrust/scatter.h>
#include <thrust/transform.h>
#include <thrust/uninitialized_fill.h>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_nth_element(column_view const& values,
column_view const& group_sizes,
cudf::device_span<size_type const> group_labels,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
size_type n,
null_policy null_handling,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(static_cast<size_t>(values.size()) == group_labels.size(),
"Size of values column should be same as that of group labels");
if (num_groups == 0) { return empty_like(values); }
auto nth_index = rmm::device_uvector<size_type>(num_groups, stream);
// TODO: replace with async version
thrust::uninitialized_fill_n(
rmm::exec_policy(stream), nth_index.begin(), num_groups, values.size());
// nulls_policy::INCLUDE (equivalent to pandas nth(dropna=None) but return nulls for n
if (null_handling == null_policy::INCLUDE || !values.has_nulls()) {
// Returns index of nth value.
thrust::transform_if(
rmm::exec_policy(stream),
group_sizes.begin<size_type>(),
group_sizes.end<size_type>(),
group_offsets.begin(),
group_sizes.begin<size_type>(), // stencil
nth_index.begin(),
[n] __device__(auto group_size, auto group_offset) {
return group_offset + ((n < 0) ? group_size + n : n);
},
[n] __device__(auto group_size) { // nth within group
return (n < 0) ? group_size >= (-n) : group_size > n;
});
} else { // skip nulls (equivalent to pandas nth(dropna='any'))
// Returns index of nth value.
auto values_view = column_device_view::create(values, stream);
auto bitmask_iterator =
thrust::make_transform_iterator(cudf::detail::make_validity_iterator(*values_view),
[] __device__(auto b) { return static_cast<size_type>(b); });
rmm::device_uvector<size_type> intra_group_index(values.size(), stream);
// intra group index for valids only.
thrust::exclusive_scan_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
bitmask_iterator,
intra_group_index.begin());
// group_size to recalculate n if n<0
rmm::device_uvector<size_type> group_count = [&] {
if (n < 0) {
rmm::device_uvector<size_type> group_count(num_groups, stream);
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
bitmask_iterator,
thrust::make_discard_iterator(),
group_count.begin());
return group_count;
} else {
return rmm::device_uvector<size_type>(0, stream);
}
}();
// gather the valid index == n
thrust::scatter_if(rmm::exec_policy(stream),
thrust::make_counting_iterator<size_type>(0),
thrust::make_counting_iterator<size_type>(values.size()),
group_labels.begin(), // map
thrust::make_counting_iterator<size_type>(0), // stencil
nth_index.begin(),
[n,
bitmask_iterator,
group_size = group_count.begin(),
group_labels = group_labels.begin(),
intra_group_index = intra_group_index.begin()] __device__(auto i) -> bool {
auto nth = ((n < 0) ? group_size[group_labels[i]] + n : n);
return (bitmask_iterator[i] && intra_group_index[i] == nth);
});
}
auto output_table = cudf::detail::gather(table_view{{values}},
nth_index,
out_of_bounds_policy::NULLIFY,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
if (!output_table->get_column(0).has_nulls()) output_table->get_column(0).set_null_mask({}, 0);
return std::make_unique<column>(std::move(output_table->get_column(0)));
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_count.cu
|
/*
* Copyright (c) 2019-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/aggregation.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/adjacent_difference.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/reduce.h>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_count_valid(column_view const& values,
cudf::device_span<size_type const> group_labels,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(num_groups >= 0, "number of groups cannot be negative");
CUDF_EXPECTS(static_cast<size_t>(values.size()) == group_labels.size(),
"Size of values column should be same as that of group labels");
auto result = make_numeric_column(
data_type(type_to_id<size_type>()), num_groups, mask_state::UNALLOCATED, stream, mr);
if (num_groups == 0) { return result; }
if (values.nullable()) {
auto values_view = column_device_view::create(values, stream);
// make_validity_iterator returns a boolean iterator that sums to 1 (1+1=1)
// so we need to transform it to cast it to an integer type
auto bitmask_iterator =
thrust::make_transform_iterator(cudf::detail::make_validity_iterator(*values_view),
[] __device__(auto b) { return static_cast<size_type>(b); });
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
bitmask_iterator,
thrust::make_discard_iterator(),
result->mutable_view().begin<size_type>());
} else {
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
thrust::make_constant_iterator(1),
thrust::make_discard_iterator(),
result->mutable_view().begin<size_type>());
}
return result;
}
std::unique_ptr<column> group_count_all(cudf::device_span<size_type const> group_offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(num_groups >= 0, "number of groups cannot be negative");
auto result = make_numeric_column(
data_type(type_to_id<size_type>()), num_groups, mask_state::UNALLOCATED, stream, mr);
if (num_groups == 0) { return result; }
thrust::adjacent_difference(rmm::exec_policy(stream),
group_offsets.begin() + 1,
group_offsets.end(),
result->mutable_view().begin<size_type>());
return result;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_count_scan.cu
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/scan.h>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> count_scan(cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
std::unique_ptr<column> result = make_fixed_width_column(
data_type{type_id::INT32}, group_labels.size(), mask_state::UNALLOCATED, stream, mr);
if (group_labels.empty()) { return result; }
auto resultview = result->mutable_view();
// aggregation::COUNT_ALL
thrust::exclusive_scan_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
thrust::make_constant_iterator<size_type>(1),
resultview.begin<size_type>());
return result;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_rank_scan.cu
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common_utils.cuh"
#include <cudf/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/utilities/device_operators.cuh>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/functional.h>
#include <thrust/iterator/reverse_iterator.h>
#include <thrust/pair.h>
#include <thrust/scan.h>
#include <thrust/tabulate.h>
#include <thrust/transform.h>
namespace cudf {
namespace groupby {
namespace detail {
namespace {
template <bool forward, typename permuted_equal_t, typename value_resolver>
struct unique_identifier {
unique_identifier(size_type const* labels,
size_type const* offsets,
permuted_equal_t permuted_equal,
value_resolver resolver)
: _labels(labels), _offsets(offsets), _permuted_equal(permuted_equal), _resolver(resolver)
{
}
auto __device__ operator()(size_type row_index) const noexcept
{
auto const group_start = _offsets[_labels[row_index]];
if constexpr (forward) {
// First value of equal values is 1.
return _resolver(row_index == group_start || !_permuted_equal(row_index, row_index - 1),
row_index - group_start);
} else {
auto const group_end = _offsets[_labels[row_index] + 1];
// Last value of equal values is 1.
return _resolver(row_index + 1 == group_end || !_permuted_equal(row_index, row_index + 1),
row_index - group_start);
}
}
private:
size_type const* _labels;
size_type const* _offsets;
permuted_equal_t _permuted_equal;
value_resolver _resolver;
};
/**
* @brief generate grouped row ranks or dense ranks using a row comparison then scan the results
*
* @tparam forward true if the rank scan computation should use forward iterator traversal (default)
* else reverse iterator traversal
* @tparam value_resolver flag value resolver function with boolean first and row number arguments
* @tparam scan_operator scan function ran on the flag values
* @param grouped_values input column to generate ranks for
* @param value_order column of type INT32 that contains the order of the values in the
* grouped_values column
* @param group_labels ID of group that the corresponding value belongs to
* @param group_offsets group index offsets with group ID indices
* @param resolver flag value resolver
* @param scan_op scan operation ran on the flag results
* @param has_nulls true if nulls are included in the `grouped_values` column
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
* @return std::unique_ptr<column> rank values
*/
template <bool forward, typename value_resolver, typename scan_operator>
std::unique_ptr<column> rank_generator(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
value_resolver resolver,
scan_operator scan_op,
bool has_nulls,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto const grouped_values_view = table_view{{grouped_values}};
auto const comparator =
cudf::experimental::row::equality::self_comparator{grouped_values_view, stream};
auto ranks = make_fixed_width_column(
data_type{type_to_id<size_type>()}, grouped_values.size(), mask_state::UNALLOCATED, stream, mr);
auto mutable_ranks = ranks->mutable_view();
auto const comparator_helper = [&](auto const d_equal) {
auto const permuted_equal =
permuted_row_equality_comparator(d_equal, value_order.begin<size_type>());
thrust::tabulate(rmm::exec_policy(stream),
mutable_ranks.begin<size_type>(),
mutable_ranks.end<size_type>(),
unique_identifier<forward, decltype(permuted_equal), value_resolver>(
group_labels.begin(), group_offsets.begin(), permuted_equal, resolver));
};
if (cudf::detail::has_nested_columns(grouped_values_view)) {
auto const d_equal =
comparator.equal_to<true>(cudf::nullate::DYNAMIC{has_nulls}, null_equality::EQUAL);
comparator_helper(d_equal);
} else {
auto const d_equal =
comparator.equal_to<false>(cudf::nullate::DYNAMIC{has_nulls}, null_equality::EQUAL);
comparator_helper(d_equal);
}
auto [group_labels_begin, mutable_rank_begin] = [&]() {
if constexpr (forward) {
return thrust::pair{group_labels.begin(), mutable_ranks.begin<size_type>()};
} else {
return thrust::pair{thrust::reverse_iterator(group_labels.end()),
thrust::reverse_iterator(mutable_ranks.end<size_type>())};
}
}();
thrust::inclusive_scan_by_key(rmm::exec_policy(stream),
group_labels_begin,
group_labels_begin + group_labels.size(),
mutable_rank_begin,
mutable_rank_begin,
thrust::equal_to{},
scan_op);
return ranks;
}
} // namespace
std::unique_ptr<column> min_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return rank_generator<true>(
grouped_values,
value_order,
group_labels,
group_offsets,
[] __device__(bool unequal, auto row_index_in_group) {
return unequal ? row_index_in_group + 1 : 0;
},
DeviceMax{},
has_nested_nulls(table_view{{grouped_values}}),
stream,
mr);
}
std::unique_ptr<column> max_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return rank_generator<false>(
grouped_values,
value_order,
group_labels,
group_offsets,
[] __device__(bool unequal, auto row_index_in_group) {
return unequal ? row_index_in_group + 1 : std::numeric_limits<size_type>::max();
},
DeviceMin{},
has_nested_nulls(table_view{{grouped_values}}),
stream,
mr);
}
std::unique_ptr<column> first_rank_scan(column_view const& grouped_values,
column_view const&,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto ranks = make_fixed_width_column(
data_type{type_to_id<size_type>()}, group_labels.size(), mask_state::UNALLOCATED, stream, mr);
auto mutable_ranks = ranks->mutable_view();
thrust::tabulate(rmm::exec_policy(stream),
mutable_ranks.begin<size_type>(),
mutable_ranks.end<size_type>(),
[labels = group_labels.begin(),
offsets = group_offsets.begin()] __device__(size_type row_index) {
auto group_start = offsets[labels[row_index]];
return row_index - group_start + 1;
});
return ranks;
}
std::unique_ptr<column> average_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto max_rank = max_rank_scan(grouped_values,
value_order,
group_labels,
group_offsets,
stream,
rmm::mr::get_current_device_resource());
auto min_rank = min_rank_scan(grouped_values,
value_order,
group_labels,
group_offsets,
stream,
rmm::mr::get_current_device_resource());
auto ranks = make_fixed_width_column(
data_type{type_to_id<double>()}, group_labels.size(), mask_state::UNALLOCATED, stream, mr);
auto mutable_ranks = ranks->mutable_view();
thrust::transform(rmm::exec_policy(stream),
max_rank->view().begin<size_type>(),
max_rank->view().end<size_type>(),
min_rank->view().begin<size_type>(),
mutable_ranks.begin<double>(),
[] __device__(auto max_rank, auto min_rank) -> double {
return min_rank + (max_rank - min_rank) / 2.0;
});
return ranks;
}
std::unique_ptr<column> dense_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return rank_generator<true>(
grouped_values,
value_order,
group_labels,
group_offsets,
[] __device__(bool const unequal, size_type const) { return unequal ? 1 : 0; },
DeviceSum{},
has_nested_nulls(table_view{{grouped_values}}),
stream,
mr);
}
std::unique_ptr<column> group_rank_to_percentage(rank_method const method,
rank_percentage const percentage,
column_view const& rank,
column_view const& count,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(percentage != rank_percentage::NONE, "Percentage cannot be NONE");
auto ranks = make_fixed_width_column(
data_type{type_to_id<double>()}, group_labels.size(), mask_state::UNALLOCATED, stream, mr);
auto mutable_ranks = ranks->mutable_view();
auto one_normalized = [] __device__(auto const rank, auto const group_size) {
return group_size == 1 ? 0.0 : ((rank - 1.0) / (group_size - 1));
};
if (method == rank_method::DENSE) {
thrust::tabulate(rmm::exec_policy(stream),
mutable_ranks.begin<double>(),
mutable_ranks.end<double>(),
[percentage,
one_normalized,
is_double = rank.type().id() == type_id::FLOAT64,
dcount = count.begin<size_type>(),
labels = group_labels.begin(),
offsets = group_offsets.begin(),
d_rank = rank.begin<double>(),
s_rank = rank.begin<size_type>()] __device__(size_type row_index) -> double {
double const r = is_double ? d_rank[row_index] : s_rank[row_index];
auto const count = dcount[labels[row_index]];
size_type const last_rank_index = offsets[labels[row_index]] + count - 1;
auto const last_rank = s_rank[last_rank_index];
return percentage == rank_percentage::ZERO_NORMALIZED
? r / last_rank
: one_normalized(r, last_rank);
});
} else {
thrust::tabulate(rmm::exec_policy(stream),
mutable_ranks.begin<double>(),
mutable_ranks.end<double>(),
[percentage,
one_normalized,
is_double = rank.type().id() == type_id::FLOAT64,
dcount = count.begin<size_type>(),
labels = group_labels.begin(),
d_rank = rank.begin<double>(),
s_rank = rank.begin<size_type>()] __device__(size_type row_index) -> double {
double const r = is_double ? d_rank[row_index] : s_rank[row_index];
auto const count = dcount[labels[row_index]];
return percentage == rank_percentage::ZERO_NORMALIZED
? r / count
: one_normalized(r, count);
});
}
ranks->set_null_count(0);
return ranks;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/sort_helper.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common_utils.cuh"
#include <stream_compaction/stream_compaction_common.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/gather.cuh>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/groupby/sort_helper.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/labeling/label_segments.cuh>
#include <cudf/detail/scatter.hpp>
#include <cudf/detail/sequence.hpp>
#include <cudf/detail/sorting.hpp>
#include <cudf/strings/string_view.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/traits.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/distance.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/unique.h>
#include <algorithm>
#include <numeric>
#include <tuple>
namespace cudf {
namespace groupby {
namespace detail {
namespace sort {
sort_groupby_helper::sort_groupby_helper(table_view const& keys,
null_policy include_null_keys,
sorted keys_pre_sorted,
std::vector<null_order> const& null_precedence)
: _keys(keys),
_num_keys(-1),
_keys_pre_sorted(keys_pre_sorted),
_include_null_keys(include_null_keys),
_null_precedence(null_precedence)
{
// Cannot depend on caller's sorting if the column contains nulls,
// and null values are to be excluded.
// Re-sort the data, to filter out nulls more easily.
if (keys_pre_sorted == sorted::YES and include_null_keys == null_policy::EXCLUDE and
has_nulls(keys)) {
_keys_pre_sorted = sorted::NO;
}
};
size_type sort_groupby_helper::num_keys(rmm::cuda_stream_view stream)
{
if (_num_keys > -1) return _num_keys;
if (_include_null_keys == null_policy::EXCLUDE and has_nulls(_keys)) {
// The number of rows w/o null values `n` is indicated by number of valid bits
// in the row bitmask. When `_include_null_keys == NO`, then only rows `[0, n)`
// in the sorted keys are considered for grouping.
_num_keys = keys_bitmask_column(stream).size() - keys_bitmask_column(stream).null_count();
} else {
_num_keys = _keys.num_rows();
}
return _num_keys;
}
column_view sort_groupby_helper::key_sort_order(rmm::cuda_stream_view stream)
{
auto sliced_key_sorted_order = [stream, this]() {
return cudf::detail::slice(this->_key_sorted_order->view(), 0, this->num_keys(stream), stream);
};
if (_key_sorted_order) { return sliced_key_sorted_order(); }
if (_keys_pre_sorted == sorted::YES) {
_key_sorted_order = cudf::detail::sequence(_keys.num_rows(),
numeric_scalar<size_type>(0),
numeric_scalar<size_type>(1),
stream,
rmm::mr::get_current_device_resource());
return sliced_key_sorted_order();
}
if (_include_null_keys == null_policy::INCLUDE || !cudf::has_nulls(_keys)) { // SQL style
auto const precedence = _null_precedence.empty()
? std::vector(_keys.num_columns(), null_order::AFTER)
: _null_precedence;
_key_sorted_order = cudf::detail::stable_sorted_order(
_keys, {}, precedence, stream, rmm::mr::get_current_device_resource());
} else { // Pandas style
// Temporarily prepend the keys table with a column that indicates the
// presence of a null value within a row. This allows moving all rows that
// contain a null value to the end of the sorted order.
auto const augmented_keys = table_view({table_view({keys_bitmask_column(stream)}), _keys});
auto const precedence = [&]() {
auto precedence = _null_precedence.empty()
? std::vector<null_order>(_keys.num_columns(), null_order::AFTER)
: _null_precedence;
precedence.insert(precedence.begin(), null_order::AFTER);
return precedence;
}();
_key_sorted_order = cudf::detail::stable_sorted_order(
augmented_keys, {}, precedence, stream, rmm::mr::get_current_device_resource());
// All rows with one or more null values are at the end of the resulting sorted order.
}
return sliced_key_sorted_order();
}
sort_groupby_helper::index_vector const& sort_groupby_helper::group_offsets(
rmm::cuda_stream_view stream)
{
if (_group_offsets) return *_group_offsets;
auto const size = num_keys(stream);
// Create a temporary variable and only set _group_offsets right before the return.
// This way, a 2nd (parallel) call to this will not be given a partially created object.
auto group_offsets = std::make_unique<index_vector>(size + 1, stream);
auto const comparator = cudf::experimental::row::equality::self_comparator{_keys, stream};
auto const sorted_order = key_sort_order(stream).data<size_type>();
decltype(group_offsets->begin()) result_end;
if (cudf::detail::has_nested_columns(_keys)) {
auto const d_key_equal = comparator.equal_to<true>(
cudf::nullate::DYNAMIC{cudf::has_nested_nulls(_keys)}, null_equality::EQUAL);
// Using a temporary buffer for intermediate transform results from the iterator containing
// the comparator speeds up compile-time significantly without much degradation in
// runtime performance over using the comparator directly in thrust::unique_copy.
auto result = rmm::device_uvector<bool>(size, stream);
auto const itr = thrust::make_counting_iterator<size_type>(0);
auto const row_eq = permuted_row_equality_comparator(d_key_equal, sorted_order);
auto const ufn = cudf::detail::unique_copy_fn<decltype(itr), decltype(row_eq)>{
itr, duplicate_keep_option::KEEP_FIRST, row_eq, size - 1};
thrust::transform(rmm::exec_policy(stream), itr, itr + size, result.begin(), ufn);
result_end = thrust::copy_if(rmm::exec_policy(stream),
itr,
itr + size,
result.begin(),
group_offsets->begin(),
thrust::identity<bool>{});
} else {
auto const d_key_equal = comparator.equal_to<false>(
cudf::nullate::DYNAMIC{cudf::has_nested_nulls(_keys)}, null_equality::EQUAL);
result_end = thrust::unique_copy(rmm::exec_policy(stream),
thrust::counting_iterator<size_type>(0),
thrust::counting_iterator<size_type>(size),
group_offsets->begin(),
permuted_row_equality_comparator(d_key_equal, sorted_order));
}
auto const num_groups = thrust::distance(group_offsets->begin(), result_end);
group_offsets->set_element_async(num_groups, size, stream);
group_offsets->resize(num_groups + 1, stream);
_group_offsets = std::move(group_offsets);
return *_group_offsets;
}
sort_groupby_helper::index_vector const& sort_groupby_helper::group_labels(
rmm::cuda_stream_view stream)
{
if (_group_labels) return *_group_labels;
// Create a temporary variable and only set _group_labels right before the return.
// This way, a 2nd (parallel) call to this will not be given a partially created object.
auto group_labels = std::make_unique<index_vector>(num_keys(stream), stream);
if (num_keys(stream)) {
auto const& offsets = group_offsets(stream);
cudf::detail::label_segments(
offsets.begin(), offsets.end(), group_labels->begin(), group_labels->end(), stream);
}
_group_labels = std::move(group_labels);
return *_group_labels;
}
column_view sort_groupby_helper::unsorted_keys_labels(rmm::cuda_stream_view stream)
{
if (_unsorted_keys_labels) return _unsorted_keys_labels->view();
column_ptr temp_labels = make_numeric_column(
data_type(type_to_id<size_type>()), _keys.num_rows(), mask_state::ALL_NULL, stream);
auto group_labels_view = cudf::column_view(data_type(type_to_id<size_type>()),
group_labels(stream).size(),
group_labels(stream).data(),
nullptr,
0);
auto scatter_map = key_sort_order(stream);
std::unique_ptr<table> t_unsorted_keys_labels =
cudf::detail::scatter(table_view({group_labels_view}),
scatter_map,
table_view({temp_labels->view()}),
stream,
rmm::mr::get_current_device_resource());
_unsorted_keys_labels = std::move(t_unsorted_keys_labels->release()[0]);
return _unsorted_keys_labels->view();
}
column_view sort_groupby_helper::keys_bitmask_column(rmm::cuda_stream_view stream)
{
if (_keys_bitmask_column) return _keys_bitmask_column->view();
auto [row_bitmask, null_count] =
cudf::detail::bitmask_and(_keys, stream, rmm::mr::get_current_device_resource());
auto const zero = numeric_scalar<int8_t>(0);
// Create a temporary variable and only set _keys_bitmask_column right before the return.
// This way, a 2nd (parallel) call to this will not be given a partially created object.
auto keys_bitmask_column = cudf::detail::sequence(
_keys.num_rows(), zero, zero, stream, rmm::mr::get_current_device_resource());
keys_bitmask_column->set_null_mask(std::move(row_bitmask), null_count);
_keys_bitmask_column = std::move(keys_bitmask_column);
return _keys_bitmask_column->view();
}
sort_groupby_helper::column_ptr sort_groupby_helper::sorted_values(
column_view const& values, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr)
{
column_ptr values_sort_order =
cudf::detail::stable_sorted_order(table_view({unsorted_keys_labels(stream), values}),
{},
std::vector<null_order>(2, null_order::AFTER),
stream,
mr);
// Zero-copy slice this sort order so that its new size is num_keys()
column_view gather_map =
cudf::detail::slice(values_sort_order->view(), 0, num_keys(stream), stream);
auto sorted_values_table = cudf::detail::gather(table_view({values}),
gather_map,
cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
return std::move(sorted_values_table->release()[0]);
}
sort_groupby_helper::column_ptr sort_groupby_helper::grouped_values(
column_view const& values, rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr)
{
auto gather_map = key_sort_order(stream);
auto grouped_values_table = cudf::detail::gather(table_view({values}),
gather_map,
cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
return std::move(grouped_values_table->release()[0]);
}
std::unique_ptr<table> sort_groupby_helper::unique_keys(rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto idx_data = key_sort_order(stream).data<size_type>();
auto gather_map_it = thrust::make_transform_iterator(
group_offsets(stream).begin(), [idx_data] __device__(size_type i) { return idx_data[i]; });
return cudf::detail::gather(_keys,
gather_map_it,
gather_map_it + num_groups(stream),
out_of_bounds_policy::DONT_CHECK,
stream,
mr);
}
std::unique_ptr<table> sort_groupby_helper::sorted_keys(rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return cudf::detail::gather(_keys,
key_sort_order(stream),
cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
}
} // namespace sort
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_merge_lists.cu
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_factories.hpp>
#include <cudf/lists/lists_column_view.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/gather.h>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_merge_lists(column_view const& values,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(values.type().id() == type_id::LIST,
"Input to `group_merge_lists` must be a lists column.");
CUDF_EXPECTS(!values.nullable(),
"Input to `group_merge_lists` must be a non-nullable lists column.");
auto offsets_column = make_numeric_column(
data_type(type_to_id<size_type>()), num_groups + 1, mask_state::UNALLOCATED, stream, mr);
// Generate offsets of the output lists column by gathering from the provided group offsets and
// the input list offsets.
//
// For example:
// values = [[2, 1], [], [4, -1, -2], [], [<NA>, 4, <NA>]]
// list_offsets = [0, 2, 2, 5, 5 8]
// group_offsets = [0, 3, 5]
//
// then, the output offsets_column is [0, 5, 8].
//
thrust::gather(rmm::exec_policy(stream),
group_offsets.begin(),
group_offsets.end(),
lists_column_view(values).offsets_begin(),
offsets_column->mutable_view().template begin<size_type>());
// The child column of the output lists column is just copied from the input column.
auto child_column =
std::make_unique<column>(lists_column_view(values).get_sliced_child(stream), stream, mr);
return make_lists_column(num_groups,
std::move(offsets_column),
std::move(child_column),
0,
rmm::device_buffer{},
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_collect.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/copy_if.cuh>
#include <cudf/strings/detail/strings_children.cuh>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/copy.h>
#include <thrust/count.h>
#include <thrust/execution_policy.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/transform.h>
#include <memory>
namespace cudf {
namespace groupby {
namespace detail {
/**
* @brief Purge null entries in grouped values, and adjust group offsets.
*
* @param values Grouped values to be purged
* @param offsets Offsets of groups' starting points
* @param num_groups Number of groups
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
* @return Pair of null-eliminated grouped values and corresponding offsets
*/
std::pair<std::unique_ptr<column>, std::unique_ptr<column>> purge_null_entries(
column_view const& values,
column_view const& offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_device_view = column_device_view::create(values, stream);
auto not_null_pred = [d_value = *values_device_view] __device__(auto i) {
return d_value.is_valid_nocheck(i);
};
// Purge null entries in grouped values.
auto null_purged_entries =
cudf::detail::copy_if(table_view{{values}}, not_null_pred, stream, mr)->release();
auto null_purged_values = std::move(null_purged_entries.front());
null_purged_values->set_null_mask(rmm::device_buffer{0, stream, mr}, 0);
// Recalculate offsets after null entries are purged.
rmm::device_uvector<size_type> null_purged_sizes(num_groups, stream);
thrust::transform(
rmm::exec_policy(stream),
thrust::make_counting_iterator<size_type>(0),
thrust::make_counting_iterator<size_type>(num_groups),
null_purged_sizes.begin(),
[d_offsets = offsets.template begin<size_type>(), not_null_pred] __device__(auto i) {
return thrust::count_if(thrust::seq,
thrust::make_counting_iterator<size_type>(d_offsets[i]),
thrust::make_counting_iterator<size_type>(d_offsets[i + 1]),
not_null_pred);
});
auto null_purged_offsets = std::get<0>(cudf::detail::make_offsets_child_column(
null_purged_sizes.cbegin(), null_purged_sizes.cend(), stream, mr));
return std::pair(std::move(null_purged_values), std::move(null_purged_offsets));
}
std::unique_ptr<column> group_collect(column_view const& values,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
null_policy null_handling,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto [child_column,
offsets_column] = [null_handling, num_groups, &values, &group_offsets, stream, mr] {
auto offsets_column = make_numeric_column(
data_type(type_to_id<size_type>()), num_groups + 1, mask_state::UNALLOCATED, stream, mr);
thrust::copy(rmm::exec_policy(stream),
group_offsets.begin(),
group_offsets.end(),
offsets_column->mutable_view().template begin<size_type>());
// If column of grouped values contains null elements, and null_policy == EXCLUDE,
// those elements must be filtered out, and offsets recomputed.
if (null_handling == null_policy::EXCLUDE && values.has_nulls()) {
return cudf::groupby::detail::purge_null_entries(
values, offsets_column->view(), num_groups, stream, mr);
} else {
return std::pair(std::make_unique<cudf::column>(values, stream, mr),
std::move(offsets_column));
}
}();
return make_lists_column(num_groups,
std::move(offsets_column),
std::move(child_column),
0,
rmm::device_buffer{0, stream, mr},
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_argmax.cu
|
/*
* Copyright (c) 2020-2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/sort/group_single_pass_reduction_util.cuh>
#include <cudf/detail/gather.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/gather.h>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_argmax(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
column_view const& key_sort_order,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto indices = type_dispatcher(values.type(),
group_reduction_dispatcher<aggregation::ARGMAX>{},
values,
num_groups,
group_labels,
stream,
mr);
// The functor returns the index of maximum in the sorted values.
// We need the index of maximum in the original unsorted values.
// So use indices to gather the sort order used to sort `values`.
// Gather map cannot be null so we make a view with the mask removed.
// The values in data buffer of indices corresponding to null values was
// initialized to ARGMAX_SENTINEL. Using gather_if.
// This can't use gather because nulls in gathered column will not store ARGMAX_SENTINEL.
auto indices_view = indices->mutable_view();
thrust::gather_if(rmm::exec_policy(stream),
indices_view.begin<size_type>(), // map first
indices_view.end<size_type>(), // map last
indices_view.begin<size_type>(), // stencil
key_sort_order.begin<size_type>(), // input
indices_view.begin<size_type>(), // result
[] __device__(auto i) { return (i != cudf::detail::ARGMAX_SENTINEL); });
return indices;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_min_scan.cu
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/sort/group_scan_util.cuh>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> min_scan(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return type_dispatcher(values.type(),
group_scan_dispatcher<aggregation::MIN>{},
values,
num_groups,
group_labels,
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_nunique.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/aggregation.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/reduce.h>
namespace cudf {
namespace groupby {
namespace detail {
namespace {
template <bool has_nested_columns, typename Nullate>
struct is_unique_iterator_fn {
using comparator_type =
typename cudf::experimental::row::equality::device_row_comparator<has_nested_columns, Nullate>;
Nullate nulls;
column_device_view const v;
comparator_type equal;
null_policy null_handling;
size_type const* group_offsets;
size_type const* group_labels;
is_unique_iterator_fn(Nullate nulls,
column_device_view const& v,
comparator_type const& equal,
null_policy null_handling,
size_type const* group_offsets,
size_type const* group_labels)
: nulls{nulls},
v{v},
equal{equal},
null_handling{null_handling},
group_offsets{group_offsets},
group_labels{group_labels}
{
}
__device__ size_type operator()(size_type i) const
{
auto const is_input_countable =
!nulls || (null_handling == null_policy::INCLUDE || v.is_valid_nocheck(i));
auto const is_unique =
is_input_countable && (group_offsets[group_labels[i]] == i || // first element or
(not equal(i, i - 1))); // new unique value in sorted
return static_cast<size_type>(is_unique);
}
};
} // namespace
std::unique_ptr<column> group_nunique(column_view const& values,
cudf::device_span<size_type const> group_labels,
size_type const num_groups,
cudf::device_span<size_type const> group_offsets,
null_policy null_handling,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(num_groups >= 0, "number of groups cannot be negative");
CUDF_EXPECTS(static_cast<size_t>(values.size()) == group_labels.size(),
"Size of values column should be same as that of group labels");
auto result = make_numeric_column(
data_type(type_to_id<size_type>()), num_groups, mask_state::UNALLOCATED, stream, mr);
if (num_groups == 0) { return result; }
auto const values_view = table_view{{values}};
auto const comparator = cudf::experimental::row::equality::self_comparator{values_view, stream};
auto const d_values_view = column_device_view::create(values, stream);
auto d_result = rmm::device_uvector<size_type>(group_labels.size(), stream);
auto const comparator_helper = [&](auto const d_equal) {
auto fn = is_unique_iterator_fn{nullate::DYNAMIC{values.has_nulls()},
*d_values_view,
d_equal,
null_handling,
group_offsets.data(),
group_labels.data()};
thrust::transform(rmm::exec_policy(stream),
thrust::make_counting_iterator<size_type>(0),
thrust::make_counting_iterator<size_type>(values.size()),
d_result.begin(),
fn);
};
if (cudf::detail::has_nested_columns(values_view)) {
auto const d_equal = comparator.equal_to<true>(
cudf::nullate::DYNAMIC{cudf::has_nested_nulls(values_view)}, null_equality::EQUAL);
comparator_helper(d_equal);
} else {
auto const d_equal = comparator.equal_to<false>(
cudf::nullate::DYNAMIC{cudf::has_nested_nulls(values_view)}, null_equality::EQUAL);
comparator_helper(d_equal);
}
// calling this with a vector instead of a transform iterator is 10x faster to compile;
// it also helps that we are only calling it once for both conditions
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
d_result.begin(),
thrust::make_discard_iterator(),
result->mutable_view().begin<size_type>());
return result;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_reductions.hpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/aggregation.hpp>
#include <cudf/column/column.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <memory>
/** @internal @file Internal API in this file are mostly segmented reduction operations on column,
* which are used in sort-based groupby aggregations.
*
*/
namespace cudf {
namespace groupby {
namespace detail {
/**
* @brief Internal API to calculate groupwise sum
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* num_groups = 4
*
* group_sum = [7, -3, 4, <NA>]
* @endcode
*
* @param values Grouped values to get sum of
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_sum(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise product
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* num_groups = 4
*
* group_product = [6, 2, 4, <NA>]
* @endcode
*
* @param values Grouped values to get product of
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_product(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise minimum value
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* num_groups = 4
*
* group_min = [1, -2, 4, <NA>]
* @endcode
*
* @param values Grouped values to get minimum from
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_min(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise maximum value
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* num_groups = 4
*
* group_max = [4, -1, 4, <NA>]
* @endcode
*
* @param values Grouped values to get maximum from
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_max(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate group-wise indices of maximum values.
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* num_groups = 4
*
* group_max = [2, 0, 0, <NA>]
* @endcode
*
* @param values Grouped values to get maximum value's index from
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param key_sort_order Indices indicating sort order of groupby keys
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_argmax(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
column_view const& key_sort_order,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate group-wise indices of minimum values.
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* num_groups = 4
*
* group_max = [1, 1, 0, <NA>]
* @endcode
*
* @param values Grouped values to get minimum value's index from
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param key_sort_order Indices indicating sort order of groupby keys
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_argmin(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
column_view const& key_sort_order,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate number of non-null values in each group of
* @p values
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* num_groups = 4
*
* group_count_valid = [3, 2, 1, 0]
* @endcode
*
* @param values Grouped values to get valid count of
* @param group_labels ID of group that the corresponding value belongs to
* @param num_groups Number of groups ( unique values in @p group_labels )
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_count_valid(column_view const& values,
cudf::device_span<size_type const> group_labels,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate number of values in each group of @p values
*
* @code{.pseudo}
* group_offsets = [0, 3, 5, 7, 8]
* num_groups = 4
*
* group_count_all = [3, 2, 2, 1]
* @endcode
*
* @param group_offsets Offsets of groups' starting points within @p values
* @param num_groups Number of groups ( unique values in @p group_labels )
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_count_all(cudf::device_span<size_type const> group_offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to compute histogram for each group in @p values.
*
* The returned column is a lists column, each list corresponds to one input group and stores the
* histogram of the distinct elements in that group in the form of `STRUCT<value, count>`.
*
* Note that the order of distinct elements in each output list is not specified.
*
* @code{.pseudo}
* values = [2, 1, 1, 3, 5, 2, 2, 3, 1, 4]
* group_labels = [0, 0, 0, 1, 1, 1, 1, 1, 2, 2]
* num_groups = 3
*
* output = [[<1, 2>, <2, 1>], [<2, 2>, <3, 2>, <5, 1>], [<1, 1>, <4, 1>]]
* @endcode
*
* @param values Grouped values to compute histogram
* @param group_labels ID of group that the corresponding value belongs to
* @param num_groups Number of groups
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_histogram(column_view const& values,
cudf::device_span<size_type const> group_labels,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate sum of squares of differences from means.
*
* If there are only nulls in the group, the output value of that group will be null.
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* group_means = [2.333333, -1.5, 4.0, <NA>]
* group_m2(...) = [4.666666, 1.0, 0.0, <NA>]
* @endcode
*
* @param values Grouped values to compute M2 values
* @param group_means Pre-computed groupwise MEAN
* @param group_labels ID of group corresponding value in @p values belongs to
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_m2(column_view const& values,
column_view const& group_means,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise variance
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* group_means = [2.333333, -1.5, 4.0, <NA>]
* group_sizes = [3, 2, 2, 1]
* ddof = 1
*
* group_var = [2.333333, 0.5, <NA>, <NA>]
* @endcode
*
* @param values Grouped values to get variance of
* @param group_means Pre-calculated groupwise MEAN
* @param group_sizes Number of valid elements per group
* @param group_labels ID of group corresponding value in @p values belongs to
* @param ddof Delta degrees of freedom. The divisor used in calculation of
* `var` is `N - ddof`, where `N` is the group size.
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_var(column_view const& values,
column_view const& group_means,
column_view const& group_sizes,
cudf::device_span<size_type const> group_labels,
size_type ddof,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise quantiles
*
* @code{.pseudo}
* values = [1, 2, 4, -2, -1, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* group_sizes = [3, 2, 2, 1]
* num_groups = 4
* quantiles = [0.25, 0.5]
*
* group_quantiles = [1.5, 2, -1.75, -1.5, 4, 4, <NA>, <NA>]
* @endcode
*
* @param values Grouped and sorted (within group) values to get quantiles from
* @param group_sizes Number of valid elements per group
* @param group_offsets Offsets of groups' starting points within @p values
* @param quantiles List of quantiles q where q lies in [0,1]
* @param interp Method to use when desired value lies between data points
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_quantiles(column_view const& values,
column_view const& group_sizes,
cudf::device_span<size_type const> group_offsets,
size_type const num_groups,
std::vector<double> const& quantiles,
interpolation interp,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate number of unique values in each group of
* @p values
*
* @code{.pseudo}
* values = [2, 4, 4, -1, -2, <NA>, 4, <NA>]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* group_offsets = [0, 3, 5, 7, 8]
* num_groups = 4
*
* group_nunique(null_policy::EXCLUDE) = [2, 2, 1, 0]
* group_nunique(null_policy::INCLUDE) = [2, 2, 2, 1]
* @endcode
*
* @param values Grouped and sorted (within group) values to get unique count of
* @param group_labels ID of group that the corresponding value belongs to
* @param num_groups Number of groups ( unique values in @p group_labels )
* @param group_offsets Offsets of groups' starting points within @p values
* @param null_handling Exclude nulls while counting if null_policy::EXCLUDE,
* Include nulls if null_policy::INCLUDE.
* Nulls are treated equal.
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_nunique(column_view const& values,
cudf::device_span<size_type const> group_labels,
size_type const num_groups,
cudf::device_span<size_type const> group_offsets,
null_policy null_handling,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate nth values in each group of @p values
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_sizes = [3, 2, 2, 1]
* group_labels = [0, 0, 0, 1, 1, 2, 2, 3]
* group_offsets = [0, 3, 5, 7, 8]
* num_groups = 4
*
* group_nth_element(n=0, null_policy::EXCLUDE) = [2, -1, 4, <NA>]
* group_nth_element(n=0, null_policy::INCLUDE) = [2, -1, <NA>, <NA>]
* @endcode
*
* @param values Grouped values to get nth value of
* @param group_sizes Number of elements per group
* @param group_labels ID of group that the corresponding value belongs to
* @param group_offsets Offsets of groups' starting points within @p values
* @param num_groups Number of groups ( unique values in @p group_labels )
* @param n nth element to choose from each group of @p values
* @param null_handling Exclude nulls while counting if null_policy::EXCLUDE,
* Include nulls if null_policy::INCLUDE.
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_nth_element(column_view const& values,
column_view const& group_sizes,
cudf::device_span<size_type const> group_labels,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
size_type n,
null_policy null_handling,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to collect grouped values into a lists column
*
* @code{.pseudo}
* values = [2, 1, 4, -1, -2, <NA>, 4, <NA>]
* group_offsets = [0, 3, 5, 7, 8]
* num_groups = 4
*
* group_collect(...) = [[2, 1, 4], [-1, -2], [<NA>, 4], [<NA>]]
* @endcode
*
* @param values Grouped values to collect.
* @param group_offsets Offsets of groups' starting points within @p values.
* @param num_groups Number of groups.
* @param null_handling Exclude nulls while counting if null_policy::EXCLUDE,
* include nulls if null_policy::INCLUDE.
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory.
*/
std::unique_ptr<column> group_collect(column_view const& values,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
null_policy null_handling,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to merge grouped lists into one list.
*
* @code{.pseudo}
* values = [[2, 1], [], [4, -1, -2], [], [<NA>, 4, <NA>]]
* group_offsets = [0, 3, 5]
* num_groups = 2
*
* group_merge_lists(...) = [[2, 1, 4, -1, -2], [<NA>, 4, <NA>]]
* @endcode
*
* @param values Grouped values (lists column) to collect.
* @param group_offsets Offsets of groups' starting points within @p values.
* @param num_groups Number of groups.
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory.
*/
std::unique_ptr<column> group_merge_lists(column_view const& values,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to merge grouped M2 values corresponding to the same key.
*
* The values of M2 are merged following the parallel algorithm described here:
* `https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm`
*
* Merging M2 values require accessing to partial M2 values, means, and valid counts. Thus, the
* input to this aggregation need to be a structs column containing tuples of 3 values
* `(valid_count, mean, M2)`.
*
* This aggregation not only merges the partial results of `M2` but also merged all the partial
* results of input aggregations (`COUNT_VALID`, `MEAN`, and `M2`). As such, the output will be a
* structs column containing children columns of merged `COUNT_VALID`, `MEAN`, and `M2` values.
*
* @param values Grouped values (tuples of values `(valid_count, mean, M2)`) to merge.
* @param group_offsets Offsets of groups' starting points within @p values.
* @param num_groups Number of groups.
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_merge_m2(column_view const& values,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to merge multiple output of HISTOGRAM aggregation.
*
* The input values column should be given as a lists column in the form of
* `LIST<STRUCT<value, count>>`.
* After merging, the order of distinct elements in each output list is not specified.
*
* @code{.pseudo}
* values = [ [<1, 2>, <2, 1>], [<2, 2>], [<3, 2>, <2, 1>], [<1, 1>, <2, 1>] ]
* group_offsets = [ 0, 2, 4]
* num_groups = 2
*
* output = [[<1, 2>, <2, 3>], [<1, 1>, <2, 2>, <3, 2>]]]
* @endcode
*
* @param values Grouped values to get valid count of
* @param group_offsets Offsets of groups' starting points within @p values
* @param num_groups Number of groups
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_merge_histogram(column_view const& values,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to find covariance of child columns of a non-nullable struct column.
*
* @param values_0 The first grouped values column to compute covariance
* @param values_1 The second grouped values column to compute covariance
* @param group_labels ID of group that the corresponding value belongs to
* @param num_groups Number of groups.
* @param count The count of valid rows of the grouped values of both columns
* @param mean_0 The mean of the first grouped values column
* @param mean_1 The mean of the second grouped values column
* @param min_periods The minimum number of non-null rows required to consider the covariance
* @param ddof The delta degrees of freedom used in the calculation of the variance
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_covariance(column_view const& values_0,
column_view const& values_1,
cudf::device_span<size_type const> group_labels,
size_type num_groups,
column_view const& count,
column_view const& mean_0,
column_view const& mean_1,
size_type min_periods,
size_type ddof,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to find correlation from covariance and standard deviation.
*
* @param covariance The covariance of two grouped values columns
* @param stddev_0 The standard deviation of the first grouped values column
* @param stddev_1 The standard deviation of the second grouped values column
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> group_correlation(column_view const& covariance,
column_view const& stddev_0,
column_view const& stddev_1,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/functors.hpp
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/aggregation/result_cache.hpp>
#include <cudf/detail/groupby/sort_helper.hpp>
#include <cudf/types.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <memory>
namespace cudf {
namespace groupby {
namespace detail {
/**
* @brief Functor to dispatch aggregation with
*
* This functor is to be used with `aggregation_dispatcher` to compute the
* appropriate aggregation. If the values on which to run the aggregation are
* unchanged, then this functor should be re-used. This is because it stores
* memoised sorted and/or grouped values and re-using will save on computation
* of these values.
*/
struct store_result_functor {
store_result_functor(column_view const& values,
sort::sort_groupby_helper& helper,
cudf::detail::result_cache& cache,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr,
sorted keys_are_sorted = sorted::NO)
: helper(helper),
cache(cache),
values(values),
stream(stream),
mr(mr),
keys_are_sorted(keys_are_sorted)
{
}
protected:
/**
* @brief Check if the groupby keys are presorted
*/
[[nodiscard]] bool is_presorted() const { return keys_are_sorted == sorted::YES; }
/**
* @brief Get the grouped values
*
* Computes the grouped values from @p values on first invocation and returns
* the stored result on subsequent invocation
*/
column_view get_grouped_values()
{
if (is_presorted()) { return values; }
// TODO (dm): After implementing single pass multi-agg, explore making a
// cache of all grouped value columns rather than one at a time
if (grouped_values)
return grouped_values->view();
else if (sorted_values)
// In scan, it wouldn't be ok to return sorted values when asked for grouped values.
// It's overridden in scan implementation.
return sorted_values->view();
else
return (grouped_values = helper.grouped_values(values, stream, mr))->view();
};
/**
* @brief Get the grouped and sorted values
*
* Computes the grouped and sorted (within each group) values from @p values
* on first invocation and returns the stored result on subsequent invocation
*/
column_view get_sorted_values()
{
return sorted_values ? sorted_values->view()
: (sorted_values = helper.sorted_values(values, stream, mr))->view();
};
protected:
sort::sort_groupby_helper& helper; ///< Sort helper
cudf::detail::result_cache& cache; ///< cache of results to store into
column_view const& values; ///< Column of values to group and aggregate
rmm::cuda_stream_view stream; ///< CUDA stream on which to execute kernels
rmm::mr::device_memory_resource* mr; ///< Memory resource to allocate space for results
sorted keys_are_sorted; ///< Whether the keys are sorted
std::unique_ptr<column> sorted_values; ///< Memoised grouped and sorted values
std::unique_ptr<column> grouped_values; ///< Memoised grouped values
};
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/common_utils.cuh
|
/*
* Copyright (c) 2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/types.hpp>
namespace cudf::groupby::detail {
/**
* @brief Functor to compare two rows of a table in given permutation order
*
* This is useful to identify unique elements in a sorted order table, when the permutation order is
* the sorted order of the table.
*/
template <typename ComparatorT, typename Iterator>
struct permuted_row_equality_comparator {
/**
* @brief Constructs a permuted comparator object which compares two rows of the table in given
* permutation order
*
* @param comparator Equality comparator
* @param permutation The permutation map that specifies the effective ordering of
* `t`. Must be the same size as `t.num_rows()`
*/
permuted_row_equality_comparator(ComparatorT const& comparator, Iterator const permutation)
: _comparator{comparator}, _permutation{permutation}
{
}
/**
* @brief Returns true if the two rows at the specified indices in the permuted
* order are equivalent.
*
* For example, comparing rows `i` and `j` is equivalent to comparing
* rows `permutation[i]` and `permutation[j]` in the original table.
*
* @param lhs The index of the first row
* @param rhs The index of the second row
* @returns true if the two specified rows in the permuted order are equivalent
*/
__device__ bool operator()(cudf::size_type lhs, cudf::size_type rhs) const
{
return _comparator(_permutation[lhs], _permutation[rhs]);
};
private:
ComparatorT const _comparator;
Iterator const _permutation;
};
} // namespace cudf::groupby::detail
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_merge_m2.cu
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/valid_if.cuh>
#include <cudf/dictionary/detail/iterator.cuh>
#include <cudf/structs/structs_column_view.hpp>
#include <cudf/utilities/span.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/functional.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/reduce.h>
#include <thrust/transform.h>
#include <thrust/tuple.h>
namespace cudf {
namespace groupby {
namespace detail {
namespace {
/**
* @brief Struct to store partial results for merging.
*/
template <class result_type>
struct partial_result {
size_type count;
result_type mean;
result_type M2;
};
/**
* @brief Functor to accumulate (merge) all partial results corresponding to the same key into a
* final result storing in a member variable. It performs merging for the partial results of
* `COUNT_VALID`, `MEAN`, and `M2` at the same time.
*/
template <class result_type>
struct accumulate_fn {
partial_result<result_type> merge_vals;
void __device__ operator()(partial_result<result_type> const& partial_vals) noexcept
{
if (partial_vals.count == 0) { return; }
auto const n_ab = merge_vals.count + partial_vals.count;
auto const delta = partial_vals.mean - merge_vals.mean;
merge_vals.M2 += partial_vals.M2 + (delta * delta) *
static_cast<result_type>(merge_vals.count) *
static_cast<result_type>(partial_vals.count) / n_ab;
merge_vals.mean =
(merge_vals.mean * merge_vals.count + partial_vals.mean * partial_vals.count) / n_ab;
merge_vals.count = n_ab;
}
};
/**
* @brief Functor to merge partial results of `COUNT_VALID`, `MEAN`, and `M2` aggregations
* for a given group (key) index.
*/
template <class result_type>
struct merge_fn {
size_type const* const d_offsets;
size_type const* const d_counts;
result_type const* const d_means;
result_type const* const d_M2s;
auto __device__ operator()(size_type const group_idx) noexcept
{
auto const start_idx = d_offsets[group_idx], end_idx = d_offsets[group_idx + 1];
// This case should never happen, because all groups are non-empty as the results of
// aggregation. Here we just to make sure we cover this case.
if (start_idx == end_idx) {
return thrust::make_tuple(size_type{0}, result_type{0}, result_type{0}, int8_t{0});
}
// If `(n = d_counts[idx]) > 0` then `d_means[idx] != null` and `d_M2s[idx] != null`.
// Otherwise (`n == 0`), these value (mean and M2) will always be nulls.
// In such cases, reading `mean` and `M2` from memory will return garbage values.
// By setting these values to zero when `n == 0`, we can safely merge the all-zero tuple without
// affecting the final result.
auto get_partial_result = [&] __device__(size_type idx) {
{
auto const n = d_counts[idx];
return n > 0 ? partial_result<result_type>{n, d_means[idx], d_M2s[idx]}
: partial_result<result_type>{size_type{0}, result_type{0}, result_type{0}};
};
};
// Firstly, store tuple(count, mean, M2) of the first partial result in an accumulator.
auto accumulator = accumulate_fn<result_type>{get_partial_result(start_idx)};
// Then, accumulate (merge) the remaining partial results into that accumulator.
for (auto idx = start_idx + 1; idx < end_idx; ++idx) {
accumulator(get_partial_result(idx));
}
// Get the final result after merging.
auto const& merge_vals = accumulator.merge_vals;
// If there are all nulls in the partial results (i.e., sum of all valid counts is
// zero), then the output is a null.
auto const is_valid = int8_t{merge_vals.count > 0};
return thrust::make_tuple(merge_vals.count, merge_vals.mean, merge_vals.M2, is_valid);
}
};
} // namespace
std::unique_ptr<column> group_merge_m2(column_view const& values,
cudf::device_span<size_type const> group_offsets,
size_type num_groups,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(values.type().id() == type_id::STRUCT,
"Input to `group_merge_m2` must be a structs column.");
CUDF_EXPECTS(values.num_children() == 3,
"Input to `group_merge_m2` must be a structs column having 3 children columns.");
using result_type = id_to_type<type_id::FLOAT64>;
static_assert(
std::is_same_v<cudf::detail::target_type_t<result_type, aggregation::Kind::M2>, result_type>);
CUDF_EXPECTS(values.child(0).type().id() == type_id::INT32 &&
values.child(1).type().id() == type_to_id<result_type>() &&
values.child(2).type().id() == type_to_id<result_type>(),
"Input to `group_merge_m2` must be a structs column having children columns "
"containing tuples of (M2_value, mean, valid_count).");
auto result_counts = make_numeric_column(
data_type(type_to_id<size_type>()), num_groups, mask_state::UNALLOCATED, stream, mr);
auto result_means = make_numeric_column(
data_type(type_to_id<result_type>()), num_groups, mask_state::UNALLOCATED, stream, mr);
auto result_M2s = make_numeric_column(
data_type(type_to_id<result_type>()), num_groups, mask_state::UNALLOCATED, stream, mr);
auto validities = rmm::device_uvector<int8_t>(num_groups, stream);
// Perform merging for all the aggregations. Their output (and their validity data) are written
// out concurrently through an output zip iterator.
using iterator_tuple = thrust::tuple<size_type*, result_type*, result_type*, int8_t*>;
using output_iterator = thrust::zip_iterator<iterator_tuple>;
auto const out_iter =
output_iterator{thrust::make_tuple(result_counts->mutable_view().template data<size_type>(),
result_means->mutable_view().template data<result_type>(),
result_M2s->mutable_view().template data<result_type>(),
validities.begin())};
auto const count_valid = values.child(0);
auto const mean_values = values.child(1);
auto const M2_values = values.child(2);
auto const iter = thrust::make_counting_iterator<size_type>(0);
auto const fn = merge_fn<result_type>{group_offsets.begin(),
count_valid.template begin<size_type>(),
mean_values.template begin<result_type>(),
M2_values.template begin<result_type>()};
thrust::transform(rmm::exec_policy(stream), iter, iter + num_groups, out_iter, fn);
// Generate bitmask for the output.
// Only mean and M2 values can be nullable. Count column must be non-nullable.
auto [null_mask, null_count] =
cudf::detail::valid_if(validities.begin(), validities.end(), thrust::identity{}, stream, mr);
if (null_count > 0) {
result_means->set_null_mask(null_mask, null_count, stream); // copy null_mask
result_M2s->set_null_mask(std::move(null_mask), null_count); // take over null_mask
}
// Output is a structs column containing the merged values of `COUNT_VALID`, `MEAN`, and `M2`.
std::vector<std::unique_ptr<column>> out_columns;
out_columns.emplace_back(std::move(result_counts));
out_columns.emplace_back(std::move(result_means));
out_columns.emplace_back(std::move(result_M2s));
auto result = cudf::make_structs_column(
num_groups, std::move(out_columns), 0, rmm::device_buffer{0, stream, mr}, stream, mr);
return result;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_std.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "group_reductions.hpp"
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/dictionary/detail/iterator.cuh>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/utilities/span.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_scalar.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/for_each.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/reduce.h>
#include <thrust/transform.h>
namespace cudf {
namespace groupby {
namespace detail {
namespace {
template <typename ResultType, typename Iterator>
struct var_transform {
column_device_view const d_values;
Iterator values_iter;
ResultType const* d_means;
size_type const* d_group_sizes;
size_type const* d_group_labels;
size_type ddof;
__device__ ResultType operator()(size_type i) const
{
if (d_values.is_null(i)) return 0.0;
auto x = static_cast<ResultType>(values_iter[i]);
size_type group_idx = d_group_labels[i];
size_type group_size = d_group_sizes[group_idx];
// prevent divide by zero error
if (group_size == 0 or group_size - ddof <= 0) return 0.0;
ResultType mean = d_means[group_idx];
return (x - mean) * (x - mean) / (group_size - ddof);
}
};
template <typename ResultType, typename Iterator>
void reduce_by_key_fn(column_device_view const& values,
Iterator values_iter,
cudf::device_span<size_type const> group_labels,
ResultType const* d_means,
size_type const* d_group_sizes,
size_type ddof,
ResultType* d_result,
rmm::cuda_stream_view stream)
{
auto var_fn = var_transform<ResultType, decltype(values_iter)>{
values, values_iter, d_means, d_group_sizes, group_labels.data(), ddof};
auto const itr = thrust::make_counting_iterator<size_type>(0);
// Using a temporary buffer for intermediate transform results instead of
// using the transform-iterator directly in thrust::reduce_by_key
// improves compile-time significantly.
auto vars = rmm::device_uvector<ResultType>(values.size(), stream);
thrust::transform(rmm::exec_policy(stream), itr, itr + values.size(), vars.begin(), var_fn);
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
vars.begin(),
thrust::make_discard_iterator(),
d_result);
}
struct var_functor {
template <typename T>
std::enable_if_t<std::is_arithmetic_v<T>, std::unique_ptr<column>> operator()(
column_view const& values,
column_view const& group_means,
column_view const& group_sizes,
cudf::device_span<size_type const> group_labels,
size_type ddof,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using ResultType = cudf::detail::target_type_t<T, aggregation::Kind::VARIANCE>;
std::unique_ptr<column> result = make_numeric_column(data_type(type_to_id<ResultType>()),
group_sizes.size(),
mask_state::UNINITIALIZED,
stream,
mr);
auto values_view = column_device_view::create(values, stream);
auto d_values = *values_view;
auto d_means = group_means.data<ResultType>();
auto d_group_sizes = group_sizes.data<size_type>();
auto d_result = result->mutable_view().data<ResultType>();
if (!cudf::is_dictionary(values.type())) {
auto values_iter = d_values.begin<T>();
reduce_by_key_fn(
d_values, values_iter, group_labels, d_means, d_group_sizes, ddof, d_result, stream);
} else {
auto values_iter = cudf::dictionary::detail::make_dictionary_iterator<T>(*values_view);
reduce_by_key_fn(
d_values, values_iter, group_labels, d_means, d_group_sizes, ddof, d_result, stream);
}
// set nulls
auto result_view = mutable_column_device_view::create(*result, stream);
auto null_count = rmm::device_scalar<cudf::size_type>(0, stream, mr);
auto d_null_count = null_count.data();
thrust::for_each_n(
rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
group_sizes.size(),
[d_result = *result_view, d_group_sizes, ddof, d_null_count] __device__(size_type i) {
size_type group_size = d_group_sizes[i];
if (group_size == 0 or group_size - ddof <= 0) {
d_result.set_null(i);
// Assuming that typical data does not have too many nulls this
// atomic shouldn't serialize the code too much. The alternatives
// would be 1) writing a more complex kernel using cub/shmem to
// increase parallelism, or 2) calling `cudf::count_nulls` after the
// fact. (1) is more work than it's worth without benchmarking, and
// this approach should outperform (2) unless large amounts of the
// data is null.
atomicAdd(d_null_count, 1);
} else {
d_result.set_valid(i);
}
});
result->set_null_count(null_count.value(stream));
return result;
}
template <typename T, typename... Args>
std::enable_if_t<!std::is_arithmetic_v<T>, std::unique_ptr<column>> operator()(Args&&...)
{
CUDF_FAIL("Only numeric types are supported in std/variance");
}
};
} // namespace
std::unique_ptr<column> group_var(column_view const& values,
column_view const& group_means,
column_view const& group_sizes,
cudf::device_span<size_type const> group_labels,
size_type ddof,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
return type_dispatcher(
values_type, var_functor{}, values, group_means, group_sizes, group_labels, ddof, stream, mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_scan.hpp
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/aggregation.hpp>
#include <cudf/column/column.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <memory>
namespace cudf {
namespace groupby {
namespace detail {
/**
* @brief Internal API to calculate groupwise cumulative sum
*
* @param values Grouped values to get sum of
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> sum_scan(column_view const& values,
size_type num_groups,
device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise cumulative minimum value
*
* @param values Grouped values to get minimum from
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> min_scan(column_view const& values,
size_type num_groups,
device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise cumulative maximum value
*
* @param values Grouped values to get maximum from
* @param num_groups Number of groups
* @param group_labels ID of group that the corresponding value belongs to
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
*/
std::unique_ptr<column> max_scan(column_view const& values,
size_type num_groups,
device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate cumulative number of values in each group
*
* @param group_labels ID of group that the corresponding value belongs to
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
* @return Column of type INT32 of count values
*/
std::unique_ptr<column> count_scan(device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise min rank value
*
* @param grouped_values column or struct column that rows within a group are sorted by
* @param value_order column of type INT32 that contains the order of the values in the
* grouped_values column
* @param group_labels ID of group that the corresponding value belongs to
* @param group_offsets group index offsets with group ID indices
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
* @return Column of type size_type of rank values
*/
std::unique_ptr<column> min_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise max rank value
*
* @details @copydetails min_rank_scan(column_view const& grouped_values,
* column_view const& value_order,
* device_span<size_type const> group_labels,
* device_span<size_type const> group_offsets,
* rmm::cuda_stream_view stream,
* rmm::mr::device_memory_resource* mr)
*/
std::unique_ptr<column> max_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise first rank value
*
* @details @copydetails min_rank_scan(column_view const& grouped_values,
* column_view const& value_order,
* device_span<size_type const> group_labels,
* device_span<size_type const> group_offsets,
* rmm::cuda_stream_view stream,
* rmm::mr::device_memory_resource* mr)
*/
std::unique_ptr<column> first_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise average rank value
*
* @details @copydetails min_rank_scan(column_view const& grouped_values,
* column_view const& value_order,
* device_span<size_type const> group_labels,
* device_span<size_type const> group_offsets,
* rmm::cuda_stream_view stream,
* rmm::mr::device_memory_resource* mr)
*/
std::unique_ptr<column> average_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Internal API to calculate groupwise dense rank value
*
* @param grouped_values column or struct column that rows within a group are sorted by
* @param group_labels ID of group that the corresponding value belongs to
* @param group_offsets group index offsets with group ID indices
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
* @return Column of type size_type of dense rank values
*/
std::unique_ptr<column> dense_rank_scan(column_view const& grouped_values,
column_view const& value_order,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Convert groupwise rank to groupwise percentage rank
*
* @param method rank method
* @param percentage enum to denote the type of conversion ranks to percentage in range (0,1]
* @param rank Groupwise rank column
* @param count Groupwise count column
* @param group_labels ID of group that the corresponding value belongs to
* @param group_offsets group index offsets with group ID indices
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned column's device memory
* @return Column of type double of rank values
*/
std::unique_ptr<column> group_rank_to_percentage(rank_method const method,
rank_percentage const percentage,
column_view const& rank,
column_view const& count,
device_span<size_type const> group_labels,
device_span<size_type const> group_offsets,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_correlation.cu
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/sort/group_reductions.hpp>
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/valid_if.cuh>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/utilities/span.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/reduce.h>
#include <thrust/transform.h>
#include <thrust/tuple.h>
#include <type_traits>
namespace cudf {
namespace groupby {
namespace detail {
namespace {
template <typename T>
constexpr bool is_double_convertible()
{
return std::is_convertible_v<T, double> || std::is_constructible_v<double, T>;
}
struct is_double_convertible_impl {
template <typename T>
bool operator()()
{
return is_double_convertible<T>();
}
};
/**
* @brief Typecasts each element of the column to `CastType`
*/
template <typename CastType>
struct type_casted_accessor {
template <typename Element>
__device__ inline CastType operator()(cudf::size_type i, column_device_view const& col) const
{
if constexpr (column_device_view::has_element_accessor<Element>() and
std::is_convertible_v<Element, CastType>)
return static_cast<CastType>(col.element<Element>(i));
(void)i;
(void)col;
return {};
}
};
template <typename ResultType>
struct covariance_transform {
column_device_view const d_values_0, d_values_1;
ResultType const *d_means_0, *d_means_1;
size_type const* d_group_sizes;
size_type const* d_group_labels;
size_type ddof{1}; // TODO update based on bias.
__device__ static ResultType value(column_device_view const& view, size_type i)
{
bool const is_dict = view.type().id() == type_id::DICTIONARY32;
i = is_dict ? static_cast<size_type>(view.element<dictionary32>(i)) : i;
auto values_col = is_dict ? view.child(dictionary_column_view::keys_column_index) : view;
return type_dispatcher(values_col.type(), type_casted_accessor<ResultType>{}, i, values_col);
}
__device__ ResultType operator()(size_type i)
{
if (d_values_0.is_null(i) or d_values_1.is_null(i)) return 0.0;
// This has to be device dispatch because x and y type may differ
auto const x = value(d_values_0, i);
auto const y = value(d_values_1, i);
size_type const group_idx = d_group_labels[i];
size_type const group_size = d_group_sizes[group_idx];
// prevent divide by zero error
if (group_size == 0 or group_size - ddof <= 0) return 0.0;
ResultType const xmean = d_means_0[group_idx];
ResultType const ymean = d_means_1[group_idx];
return (x - xmean) * (y - ymean) / (group_size - ddof);
}
};
} // namespace
std::unique_ptr<column> group_covariance(column_view const& values_0,
column_view const& values_1,
cudf::device_span<size_type const> group_labels,
size_type num_groups,
column_view const& count,
column_view const& mean_0,
column_view const& mean_1,
size_type min_periods,
size_type ddof,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using result_type = id_to_type<type_id::FLOAT64>;
static_assert(
std::is_same_v<cudf::detail::target_type_t<result_type, aggregation::Kind::CORRELATION>,
result_type>);
// check if each child type can be converted to float64.
auto get_base_type = [](auto const& col) {
return (col.type().id() == type_id::DICTIONARY32
? col.child(dictionary_column_view::keys_column_index)
: col)
.type();
};
bool const is_convertible =
type_dispatcher(get_base_type(values_0), is_double_convertible_impl{}) and
type_dispatcher(get_base_type(values_1), is_double_convertible_impl{});
CUDF_EXPECTS(is_convertible,
"Input to `group_correlation` must be columns of type convertible to float64.");
auto mean0_ptr = mean_0.begin<result_type>();
auto mean1_ptr = mean_1.begin<result_type>();
auto d_values_0 = column_device_view::create(values_0, stream);
auto d_values_1 = column_device_view::create(values_1, stream);
covariance_transform<result_type> covariance_transform_op{*d_values_0,
*d_values_1,
mean0_ptr,
mean1_ptr,
count.data<size_type>(),
group_labels.begin(),
ddof};
auto result = make_numeric_column(
data_type(type_to_id<result_type>()), num_groups, mask_state::UNALLOCATED, stream, mr);
auto d_result = result->mutable_view().begin<result_type>();
auto corr_iter =
thrust::make_transform_iterator(thrust::make_counting_iterator(0), covariance_transform_op);
thrust::reduce_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
corr_iter,
thrust::make_discard_iterator(),
d_result);
auto is_null = [ddof, min_periods] __device__(size_type group_size) {
return not(group_size == 0 or group_size - ddof <= 0 or group_size < min_periods);
};
auto [new_nullmask, null_count] =
cudf::detail::valid_if(count.begin<size_type>(), count.end<size_type>(), is_null, stream, mr);
if (null_count != 0) { result->set_null_mask(std::move(new_nullmask), null_count); }
return result;
}
std::unique_ptr<column> group_correlation(column_view const& covariance,
column_view const& stddev_0,
column_view const& stddev_1,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using result_type = id_to_type<type_id::FLOAT64>;
CUDF_EXPECTS(covariance.type().id() == type_id::FLOAT64, "Covariance result must be FLOAT64");
auto stddev0_ptr = stddev_0.begin<result_type>();
auto stddev1_ptr = stddev_1.begin<result_type>();
auto stddev_iter = thrust::make_zip_iterator(thrust::make_tuple(stddev0_ptr, stddev1_ptr));
auto result = make_numeric_column(covariance.type(),
covariance.size(),
cudf::detail::copy_bitmask(covariance, stream, mr),
covariance.null_count(),
stream,
mr);
auto d_result = result->mutable_view().begin<result_type>();
thrust::transform(rmm::exec_policy(stream),
covariance.begin<result_type>(),
covariance.end<result_type>(),
stddev_iter,
d_result,
[] __device__(auto const covariance, auto const stddev) {
return covariance / thrust::get<0>(stddev) / thrust::get<1>(stddev);
});
result->set_null_count(covariance.null_count());
return result;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_max_scan.cu
|
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/sort/group_scan_util.cuh>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> max_scan(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return type_dispatcher(values.type(),
group_scan_dispatcher<aggregation::MAX>{},
values,
num_groups,
group_labels,
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/aggregate.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/common/utils.hpp>
#include <groupby/sort/functors.hpp>
#include <groupby/sort/group_reductions.hpp>
#include <cudf/aggregation.hpp>
#include <cudf/column/column.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/aggregation/result_cache.hpp>
#include <cudf/detail/binaryop.hpp>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/groupby/sort_helper.hpp>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/tdigest/tdigest.hpp>
#include <cudf/detail/unary.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/groupby.hpp>
#include <cudf/lists/detail/stream_compaction.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <memory>
#include <unordered_map>
#include <utility>
namespace cudf {
namespace groupby {
namespace detail {
/**
* @brief Functor to dispatch aggregation with
*
* This functor is to be used with `aggregation_dispatcher` to compute the
* appropriate aggregation. If the values on which to run the aggregation are
* unchanged, then this functor should be re-used. This is because it stores
* memoised sorted and/or grouped values and re-using will save on computation
* of these values.
*/
struct aggregate_result_functor final : store_result_functor {
using store_result_functor::store_result_functor;
template <aggregation::Kind k>
void operator()(aggregation const& agg)
{
CUDF_FAIL("Unsupported aggregation.");
}
};
template <>
void aggregate_result_functor::operator()<aggregation::COUNT_VALID>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(
values,
agg,
get_grouped_values().nullable()
? detail::group_count_valid(
get_grouped_values(), helper.group_labels(stream), helper.num_groups(stream), stream, mr)
: detail::group_count_all(
helper.group_offsets(stream), helper.num_groups(stream), stream, mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::COUNT_ALL>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(
values,
agg,
detail::group_count_all(helper.group_offsets(stream), helper.num_groups(stream), stream, mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::HISTOGRAM>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(
values,
agg,
detail::group_histogram(
get_grouped_values(), helper.group_labels(stream), helper.num_groups(stream), stream, mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::SUM>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(
values,
agg,
detail::group_sum(
get_grouped_values(), helper.num_groups(stream), helper.group_labels(stream), stream, mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::PRODUCT>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(
values,
agg,
detail::group_product(
get_grouped_values(), helper.num_groups(stream), helper.group_labels(stream), stream, mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::ARGMAX>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(values,
agg,
detail::group_argmax(get_grouped_values(),
helper.num_groups(stream),
helper.group_labels(stream),
helper.key_sort_order(stream),
stream,
mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::ARGMIN>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(values,
agg,
detail::group_argmin(get_grouped_values(),
helper.num_groups(stream),
helper.group_labels(stream),
helper.key_sort_order(stream),
stream,
mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::MIN>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto result = [&]() {
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
if (cudf::is_fixed_width(values_type)) {
return detail::group_min(
get_grouped_values(), helper.num_groups(stream), helper.group_labels(stream), stream, mr);
} else {
auto argmin_agg = make_argmin_aggregation();
operator()<aggregation::ARGMIN>(*argmin_agg);
column_view argmin_result = cache.get_result(values, *argmin_agg);
// We make a view of ARGMIN result without a null mask and gather using
// this mask. The values in data buffer of ARGMIN result corresponding
// to null values was initialized to ARGMIN_SENTINEL which is an out of
// bounds index value and causes the gathered value to be null.
column_view null_removed_map(
data_type(type_to_id<size_type>()),
argmin_result.size(),
static_cast<void const*>(argmin_result.template data<size_type>()),
nullptr,
0);
auto transformed_result =
cudf::detail::gather(table_view({values}),
null_removed_map,
argmin_result.nullable() ? cudf::out_of_bounds_policy::NULLIFY
: cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
return std::move(transformed_result->release()[0]);
}
}();
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::MAX>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto result = [&]() {
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
if (cudf::is_fixed_width(values_type)) {
return detail::group_max(
get_grouped_values(), helper.num_groups(stream), helper.group_labels(stream), stream, mr);
} else {
auto argmax_agg = make_argmax_aggregation();
operator()<aggregation::ARGMAX>(*argmax_agg);
column_view argmax_result = cache.get_result(values, *argmax_agg);
// We make a view of ARGMAX result without a null mask and gather using
// this mask. The values in data buffer of ARGMAX result corresponding
// to null values was initialized to ARGMAX_SENTINEL which is an out of
// bounds index value and causes the gathered value to be null.
column_view null_removed_map(
data_type(type_to_id<size_type>()),
argmax_result.size(),
static_cast<void const*>(argmax_result.template data<size_type>()),
nullptr,
0);
auto transformed_result =
cudf::detail::gather(table_view({values}),
null_removed_map,
argmax_result.nullable() ? cudf::out_of_bounds_policy::NULLIFY
: cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
return std::move(transformed_result->release()[0]);
}
}();
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::MEAN>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto sum_agg = make_sum_aggregation();
auto count_agg = make_count_aggregation();
operator()<aggregation::SUM>(*sum_agg);
operator()<aggregation::COUNT_VALID>(*count_agg);
column_view sum_result = cache.get_result(values, *sum_agg);
column_view count_result = cache.get_result(values, *count_agg);
// TODO (dm): Special case for timestamp. Add target_type_impl for it.
// Blocked until we support operator+ on timestamps
auto col_type = cudf::is_dictionary(values.type())
? cudf::dictionary_column_view(values).keys().type()
: values.type();
auto result =
cudf::detail::binary_operation(sum_result,
count_result,
binary_operator::DIV,
cudf::detail::target_type(col_type, aggregation::MEAN),
stream,
mr);
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::M2>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto const mean_agg = make_mean_aggregation();
operator()<aggregation::MEAN>(*mean_agg);
auto const mean_result = cache.get_result(values, *mean_agg);
cache.add_result(
values,
agg,
detail::group_m2(get_grouped_values(), mean_result, helper.group_labels(stream), stream, mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::VARIANCE>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto& var_agg = dynamic_cast<cudf::detail::var_aggregation const&>(agg);
auto mean_agg = make_mean_aggregation();
auto count_agg = make_count_aggregation();
operator()<aggregation::MEAN>(*mean_agg);
operator()<aggregation::COUNT_VALID>(*count_agg);
column_view mean_result = cache.get_result(values, *mean_agg);
column_view group_sizes = cache.get_result(values, *count_agg);
auto result = detail::group_var(get_grouped_values(),
mean_result,
group_sizes,
helper.group_labels(stream),
var_agg._ddof,
stream,
mr);
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::STD>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto& std_agg = dynamic_cast<cudf::detail::std_aggregation const&>(agg);
auto var_agg = make_variance_aggregation(std_agg._ddof);
operator()<aggregation::VARIANCE>(*var_agg);
column_view var_result = cache.get_result(values, *var_agg);
auto result = cudf::detail::unary_operation(var_result, unary_operator::SQRT, stream, mr);
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::QUANTILE>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto count_agg = make_count_aggregation();
operator()<aggregation::COUNT_VALID>(*count_agg);
column_view group_sizes = cache.get_result(values, *count_agg);
auto& quantile_agg = dynamic_cast<cudf::detail::quantile_aggregation const&>(agg);
auto result = detail::group_quantiles(get_sorted_values(),
group_sizes,
helper.group_offsets(stream),
helper.num_groups(stream),
quantile_agg._quantiles,
quantile_agg._interpolation,
stream,
mr);
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::MEDIAN>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto count_agg = make_count_aggregation();
operator()<aggregation::COUNT_VALID>(*count_agg);
column_view group_sizes = cache.get_result(values, *count_agg);
auto result = detail::group_quantiles(get_sorted_values(),
group_sizes,
helper.group_offsets(stream),
helper.num_groups(stream),
{0.5},
interpolation::LINEAR,
stream,
mr);
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::NUNIQUE>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto& nunique_agg = dynamic_cast<cudf::detail::nunique_aggregation const&>(agg);
auto result = detail::group_nunique(get_sorted_values(),
helper.group_labels(stream),
helper.num_groups(stream),
helper.group_offsets(stream),
nunique_agg._null_handling,
stream,
mr);
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::NTH_ELEMENT>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
auto& nth_element_agg = dynamic_cast<cudf::detail::nth_element_aggregation const&>(agg);
auto count_agg = make_count_aggregation(nth_element_agg._null_handling);
if (count_agg->kind == aggregation::COUNT_VALID) {
operator()<aggregation::COUNT_VALID>(*count_agg);
} else if (count_agg->kind == aggregation::COUNT_ALL) {
operator()<aggregation::COUNT_ALL>(*count_agg);
} else {
CUDF_FAIL("Wrong count aggregation kind");
}
column_view group_sizes = cache.get_result(values, *count_agg);
cache.add_result(values,
agg,
detail::group_nth_element(get_grouped_values(),
group_sizes,
helper.group_labels(stream),
helper.group_offsets(stream),
helper.num_groups(stream),
nth_element_agg._n,
nth_element_agg._null_handling,
stream,
mr));
}
template <>
void aggregate_result_functor::operator()<aggregation::COLLECT_LIST>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
auto const null_handling =
dynamic_cast<cudf::detail::collect_list_aggregation const&>(agg)._null_handling;
auto result = detail::group_collect(get_grouped_values(),
helper.group_offsets(stream),
helper.num_groups(stream),
null_handling,
stream,
mr);
cache.add_result(values, agg, std::move(result));
}
template <>
void aggregate_result_functor::operator()<aggregation::COLLECT_SET>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
auto const null_handling =
dynamic_cast<cudf::detail::collect_set_aggregation const&>(agg)._null_handling;
auto const collect_result = detail::group_collect(get_grouped_values(),
helper.group_offsets(stream),
helper.num_groups(stream),
null_handling,
stream,
rmm::mr::get_current_device_resource());
auto const nulls_equal =
dynamic_cast<cudf::detail::collect_set_aggregation const&>(agg)._nulls_equal;
auto const nans_equal =
dynamic_cast<cudf::detail::collect_set_aggregation const&>(agg)._nans_equal;
cache.add_result(
values,
agg,
lists::detail::distinct(
lists_column_view{collect_result->view()}, nulls_equal, nans_equal, stream, mr));
}
/**
* @brief Perform merging for the lists that correspond to the same key value.
*
* This aggregation is similar to `COLLECT_LIST` with the following differences:
* - It requires the input values to be a non-nullable lists column, and
* - The values (lists) corresponding to the same key will not result in a list of lists as output
* from `COLLECT_LIST`. Instead, those lists will result in a list generated by merging them
* together.
*
* In practice, this aggregation is used to merge the partial results of multiple (distributed)
* groupby `COLLECT_LIST` aggregations into a final `COLLECT_LIST` result. Those distributed
* aggregations were executed on different values columns partitioned from the original values
* column, then their results were (vertically) concatenated before given as the values column for
* this aggregation.
*/
template <>
void aggregate_result_functor::operator()<aggregation::MERGE_LISTS>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
cache.add_result(
values,
agg,
detail::group_merge_lists(
get_grouped_values(), helper.group_offsets(stream), helper.num_groups(stream), stream, mr));
}
/**
* @brief Perform merging for the lists corresponding to the same key value, then dropping duplicate
* list entries.
*
* This aggregation is similar to `COLLECT_SET` with the following differences:
* - It requires the input values to be a non-nullable lists column, and
* - The values (lists) corresponding to the same key will result in a list generated by merging
* them together then dropping duplicate entries.
*
* In practice, this aggregation is used to merge the partial results of multiple (distributed)
* groupby `COLLECT_LIST` or `COLLECT_SET` aggregations into a final `COLLECT_SET` result. Those
* distributed aggregations were executed on different values columns partitioned from the original
* values column, then their results were (vertically) concatenated before given as the values
* column for this aggregation.
*
* Firstly, this aggregation performs `MERGE_LISTS` to concatenate the input lists (corresponding to
* the same key) into intermediate lists, then it calls `lists::distinct` on them to
* remove duplicate list entries. As such, the input (partial results) to this aggregation should be
* generated by (distributed) `COLLECT_LIST` aggregations, not `COLLECT_SET`, to avoid unnecessarily
* removing duplicate entries for the partial results.
*
* Since duplicate list entries will be removed, the parameters `null_equality` and `nan_equality`
* are needed for calling `lists::distinct`.
*/
template <>
void aggregate_result_functor::operator()<aggregation::MERGE_SETS>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
auto const merged_result = detail::group_merge_lists(get_grouped_values(),
helper.group_offsets(stream),
helper.num_groups(stream),
stream,
rmm::mr::get_current_device_resource());
auto const& merge_sets_agg = dynamic_cast<cudf::detail::merge_sets_aggregation const&>(agg);
cache.add_result(values,
agg,
lists::detail::distinct(lists_column_view{merged_result->view()},
merge_sets_agg._nulls_equal,
merge_sets_agg._nans_equal,
stream,
mr));
}
/**
* @brief Perform merging for the M2 values that correspond to the same key value.
*
* The partial results input to this aggregation is a structs column with children are columns
* generated by three other groupby aggregations: `COUNT_VALID`, `MEAN`, and `M2` that were
* performed on partitioned datasets. After distributedly computed, the results output from these
* aggregations are (vertically) concatenated before assembling into a structs column given as the
* values column for this aggregation.
*
* For recursive merging of `M2` values, the aggregations values of all input (`COUNT_VALID`,
* `MEAN`, and `M2`) are all merged and stored in the output of this aggregation. As such, the
* output will be a structs column containing children columns of merged `COUNT_VALID`, `MEAN`, and
* `M2` values.
*
* The values of M2 are merged following the parallel algorithm described here:
* https://www.wikiwand.com/en/Algorithms_for_calculating_variance#/Parallel_algorithm
*/
template <>
void aggregate_result_functor::operator()<aggregation::MERGE_M2>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
cache.add_result(
values,
agg,
detail::group_merge_m2(
get_grouped_values(), helper.group_offsets(stream), helper.num_groups(stream), stream, mr));
}
/**
* @brief Perform merging for multiple histograms that correspond to the same key value.
*
* The partial results input to this aggregation is a structs column that is concatenated from
* multiple outputs of HISTOGRAM aggregations.
*/
template <>
void aggregate_result_functor::operator()<aggregation::MERGE_HISTOGRAM>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
cache.add_result(
values,
agg,
detail::group_merge_histogram(
get_grouped_values(), helper.group_offsets(stream), helper.num_groups(stream), stream, mr));
}
/**
* @brief Creates column views with only valid elements in both input column views
*
* @param column_0 The first column
* @param column_1 The second column
* @return tuple with new null mask (if null masks of input differ) and new column views
*/
auto column_view_with_common_nulls(column_view const& column_0, column_view const& column_1)
{
auto [new_nullmask, null_count] = cudf::bitmask_and(table_view{{column_0, column_1}});
if (null_count == 0) { return std::make_tuple(std::move(new_nullmask), column_0, column_1); }
auto column_view_with_new_nullmask = [](auto const& col, void* nullmask, auto null_count) {
return column_view(col.type(),
col.size(),
col.head(),
static_cast<cudf::bitmask_type const*>(nullmask),
null_count,
col.offset(),
std::vector(col.child_begin(), col.child_end()));
};
auto new_column_0 = null_count == column_0.null_count()
? column_0
: column_view_with_new_nullmask(column_0, new_nullmask.data(), null_count);
auto new_column_1 = null_count == column_1.null_count()
? column_1
: column_view_with_new_nullmask(column_1, new_nullmask.data(), null_count);
return std::make_tuple(std::move(new_nullmask), new_column_0, new_column_1);
}
/**
* @brief Perform covariance between two child columns of non-nullable struct column.
*
*/
template <>
void aggregate_result_functor::operator()<aggregation::COVARIANCE>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
CUDF_EXPECTS(values.type().id() == type_id::STRUCT,
"Input to `groupby covariance` must be a structs column.");
CUDF_EXPECTS(values.num_children() == 2,
"Input to `groupby covariance` must be a structs column having 2 children columns.");
auto const& cov_agg = dynamic_cast<cudf::detail::covariance_aggregation const&>(agg);
// Covariance only for valid values in both columns.
// in non-identical null mask cases, this prevents caching of the results - STD, MEAN, COUNT.
auto [_, values_child0, values_child1] =
column_view_with_common_nulls(values.child(0), values.child(1));
auto mean_agg = make_mean_aggregation();
aggregate_result_functor(values_child0, helper, cache, stream, mr).operator()<aggregation::MEAN>(*mean_agg);
aggregate_result_functor(values_child1, helper, cache, stream, mr).operator()<aggregation::MEAN>(*mean_agg);
auto const mean0 = cache.get_result(values_child0, *mean_agg);
auto const mean1 = cache.get_result(values_child1, *mean_agg);
auto count_agg = make_count_aggregation();
auto const count = cache.get_result(values_child0, *count_agg);
cache.add_result(values,
agg,
detail::group_covariance(get_grouped_values().child(0),
get_grouped_values().child(1),
helper.group_labels(stream),
helper.num_groups(stream),
count,
mean0,
mean1,
cov_agg._min_periods,
cov_agg._ddof,
stream,
mr));
}
/**
* @brief Perform correlation between two child columns of non-nullable struct column.
*
*/
template <>
void aggregate_result_functor::operator()<aggregation::CORRELATION>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
CUDF_EXPECTS(values.type().id() == type_id::STRUCT,
"Input to `groupby correlation` must be a structs column.");
CUDF_EXPECTS(
values.num_children() == 2,
"Input to `groupby correlation` must be a structs column having 2 children columns.");
CUDF_EXPECTS(not values.nullable(),
"Input to `groupby correlation` must be a non-nullable structs column.");
auto const& corr_agg = dynamic_cast<cudf::detail::correlation_aggregation const&>(agg);
CUDF_EXPECTS(corr_agg._type == correlation_type::PEARSON,
"Only Pearson correlation is supported.");
// Correlation only for valid values in both columns.
// in non-identical null mask cases, this prevents caching of the results - STD, MEAN, COUNT
auto [_, values_child0, values_child1] =
column_view_with_common_nulls(values.child(0), values.child(1));
auto std_agg = make_std_aggregation();
aggregate_result_functor(values_child0, helper, cache, stream, mr).operator()<aggregation::STD>(*std_agg);
aggregate_result_functor(values_child1, helper, cache, stream, mr).operator()<aggregation::STD>(*std_agg);
// Compute covariance here to avoid repeated computation of mean & count
auto cov_agg = make_covariance_aggregation(corr_agg._min_periods);
if (not cache.has_result(values, *cov_agg)) {
auto mean_agg = make_mean_aggregation();
auto const mean0 = cache.get_result(values_child0, *mean_agg);
auto const mean1 = cache.get_result(values_child1, *mean_agg);
auto count_agg = make_count_aggregation();
auto const count = cache.get_result(values_child0, *count_agg);
auto const& cov_agg_obj = dynamic_cast<cudf::detail::covariance_aggregation const&>(*cov_agg);
cache.add_result(values,
*cov_agg,
detail::group_covariance(get_grouped_values().child(0),
get_grouped_values().child(1),
helper.group_labels(stream),
helper.num_groups(stream),
count,
mean0,
mean1,
cov_agg_obj._min_periods,
cov_agg_obj._ddof,
stream,
mr));
}
auto const stddev0 = cache.get_result(values_child0, *std_agg);
auto const stddev1 = cache.get_result(values_child1, *std_agg);
auto const covariance = cache.get_result(values, *cov_agg);
cache.add_result(
values, agg, detail::group_correlation(covariance, stddev0, stddev1, stream, mr));
}
/**
* @brief Generate a tdigest column from a grouped set of numeric input values.
*
* The tdigest column produced is of the following structure:
*
* struct {
* // centroids for the digest
* list {
* struct {
* double // mean
* double // weight
* },
* ...
* }
* // these are from the input stream, not the centroids. they are used
* // during the percentile_approx computation near the beginning or
* // end of the quantiles
* double // min
* double // max
* }
*
* Each output row is a single tdigest. The length of the row is the "size" of the
* tdigest, each element of which represents a weighted centroid (mean, weight).
*/
template <>
void aggregate_result_functor::operator()<aggregation::TDIGEST>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
auto const max_centroids =
dynamic_cast<cudf::detail::tdigest_aggregation const&>(agg).max_centroids;
auto count_agg = make_count_aggregation();
operator()<aggregation::COUNT_VALID>(*count_agg);
column_view valid_counts = cache.get_result(values, *count_agg);
cache.add_result(values,
agg,
cudf::tdigest::detail::group_tdigest(
get_sorted_values(),
helper.group_offsets(stream),
helper.group_labels(stream),
{valid_counts.begin<size_type>(), static_cast<size_t>(valid_counts.size())},
helper.num_groups(stream),
max_centroids,
stream,
mr));
}
/**
* @brief Generate a merged tdigest column from a grouped set of input tdigest columns.
*
* The tdigest column produced is of the following structure:
*
* struct {
* // centroids for the digest
* list {
* struct {
* double // mean
* double // weight
* },
* ...
* }
* // these are from the input stream, not the centroids. they are used
* // during the percentile_approx computation near the beginning or
* // end of the quantiles
* double // min
* double // max
* }
*
* Each output row is a single tdigest. The length of the row is the "size" of the
* tdigest, each element of which represents a weighted centroid (mean, weight).
*/
template <>
void aggregate_result_functor::operator()<aggregation::MERGE_TDIGEST>(aggregation const& agg)
{
if (cache.has_result(values, agg)) { return; }
auto const max_centroids =
dynamic_cast<cudf::detail::merge_tdigest_aggregation const&>(agg).max_centroids;
cache.add_result(values,
agg,
cudf::tdigest::detail::group_merge_tdigest(get_grouped_values(),
helper.group_offsets(stream),
helper.group_labels(stream),
helper.num_groups(stream),
max_centroids,
stream,
mr));
}
} // namespace detail
// Sort-based groupby
std::pair<std::unique_ptr<table>, std::vector<aggregation_result>> groupby::sort_aggregate(
host_span<aggregation_request const> requests,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// We're going to start by creating a cache of results so that aggs that
// depend on other aggs will not have to be recalculated. e.g. mean depends on
// sum and count. std depends on mean and count
cudf::detail::result_cache cache(requests.size());
for (auto const& request : requests) {
auto store_functor =
detail::aggregate_result_functor(request.values, helper(), cache, stream, mr);
for (auto const& agg : request.aggregations) {
// TODO (dm): single pass compute all supported reductions
cudf::detail::aggregation_dispatcher(agg->kind, store_functor, *agg);
}
}
auto results = detail::extract_results(requests, cache, stream, mr);
return std::pair(helper().unique_keys(stream, mr), std::move(results));
}
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_scan_util.cuh
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <reductions/nested_type_minmax_util.cuh>
#include <cudf/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/aggregation/aggregation.cuh>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/structs/utilities.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/functional.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/scan.h>
namespace cudf {
namespace groupby {
namespace detail {
// Error case when no other overload or specialization is available
template <aggregation::Kind K, typename T, typename Enable = void>
struct group_scan_functor {
template <typename... Args>
static std::unique_ptr<column> invoke(Args&&...)
{
CUDF_FAIL("Unsupported groupby scan type-agg combination.");
}
};
template <aggregation::Kind K>
struct group_scan_dispatcher {
template <typename T>
std::unique_ptr<column> operator()(column_view const& values,
size_type num_groups,
cudf::device_span<cudf::size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return group_scan_functor<K, T>::invoke(values, num_groups, group_labels, stream, mr);
}
};
/**
* @brief Check if the given aggregation K with data type T is supported in groupby scan.
*/
template <aggregation::Kind K, typename T>
static constexpr bool is_group_scan_supported()
{
if (K == aggregation::SUM)
return cudf::is_numeric<T>() || cudf::is_duration<T>() || cudf::is_fixed_point<T>();
else if (K == aggregation::MIN or K == aggregation::MAX)
return not cudf::is_dictionary<T>() and
(is_relationally_comparable<T, T>() or std::is_same_v<T, cudf::struct_view>);
else
return false;
}
template <aggregation::Kind K, typename T>
struct group_scan_functor<K, T, std::enable_if_t<is_group_scan_supported<K, T>()>> {
static std::unique_ptr<column> invoke(column_view const& values,
size_type num_groups,
cudf::device_span<cudf::size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using DeviceType = device_storage_type_t<T>;
using OpType = cudf::detail::corresponding_operator_t<K>;
using ResultType = cudf::detail::target_type_t<T, K>;
using ResultDeviceType = device_storage_type_t<ResultType>;
auto result_type = is_fixed_point<T>()
? data_type{type_to_id<ResultType>(), values.type().scale()}
: data_type{type_to_id<ResultType>()};
std::unique_ptr<column> result =
make_fixed_width_column(result_type, values.size(), mask_state::UNALLOCATED, stream, mr);
if (values.is_empty()) { return result; }
auto result_table = mutable_table_view({*result});
cudf::detail::initialize_with_identity(result_table, {K}, stream);
auto result_view = mutable_column_device_view::create(result->mutable_view(), stream);
auto values_view = column_device_view::create(values, stream);
// Perform segmented scan.
auto const do_scan = [&](auto const& inp_iter, auto const& out_iter, auto const& binop) {
thrust::inclusive_scan_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
inp_iter,
out_iter,
thrust::equal_to{},
binop);
};
if (values.has_nulls()) {
auto input = thrust::make_transform_iterator(
make_null_replacement_iterator(*values_view, OpType::template identity<DeviceType>()),
thrust::identity<ResultDeviceType>{});
do_scan(input, result_view->begin<ResultDeviceType>(), OpType{});
result->set_null_mask(cudf::detail::copy_bitmask(values, stream, mr), values.null_count());
} else {
auto input = thrust::make_transform_iterator(values_view->begin<DeviceType>(),
thrust::identity<ResultDeviceType>{});
do_scan(input, result_view->begin<ResultDeviceType>(), OpType{});
}
return result;
}
};
template <aggregation::Kind K>
struct group_scan_functor<K,
cudf::string_view,
std::enable_if_t<is_group_scan_supported<K, cudf::string_view>()>> {
static std::unique_ptr<column> invoke(column_view const& values,
size_type num_groups,
cudf::device_span<cudf::size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using OpType = cudf::detail::corresponding_operator_t<K>;
if (values.is_empty()) { return cudf::make_empty_column(cudf::type_id::STRING); }
// create an empty output vector we can fill with string_view instances
auto results_vector = rmm::device_uvector<string_view>(values.size(), stream);
auto values_view = column_device_view::create(values, stream);
// Perform segmented scan.
auto const do_scan = [&](auto const& inp_iter, auto const& out_iter, auto const& binop) {
thrust::inclusive_scan_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
inp_iter,
out_iter,
thrust::equal_to{},
binop);
};
if (values.has_nulls()) {
auto input = make_null_replacement_iterator(
*values_view, OpType::template identity<string_view>(), values.has_nulls());
do_scan(input, results_vector.begin(), OpType{});
} else {
do_scan(values_view->begin<string_view>(), results_vector.begin(), OpType{});
}
// turn the string_view vector into a strings column
auto results = make_strings_column(results_vector, string_view{}, stream, mr);
if (values.has_nulls())
results->set_null_mask(cudf::detail::copy_bitmask(values, stream, mr), values.null_count());
return results;
}
};
template <aggregation::Kind K>
struct group_scan_functor<K,
cudf::struct_view,
std::enable_if_t<is_group_scan_supported<K, cudf::struct_view>()>> {
static std::unique_ptr<column> invoke(column_view const& values,
size_type num_groups,
cudf::device_span<cudf::size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
if (values.is_empty()) { return cudf::empty_like(values); }
// Create a gather map containing indices of the prefix min/max elements within each group.
auto gather_map = rmm::device_uvector<size_type>(values.size(), stream);
auto const binop_generator =
cudf::reduction::detail::comparison_binop_generator::create<K>(values, stream);
thrust::inclusive_scan_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.end(),
thrust::make_counting_iterator<size_type>(0),
gather_map.begin(),
thrust::equal_to{},
binop_generator.binop());
//
// Gather the children elements of the prefix min/max struct elements first.
//
// Typically, we should use `get_sliced_child` for each child column to properly handle the
// input if it is a sliced view. However, since the input to this function is just generated
// from groupby internal APIs which is never a sliced view, we just use `child_begin` and
// `child_end` iterators for simplicity.
auto scanned_children =
cudf::detail::gather(
table_view(std::vector<column_view>{values.child_begin(), values.child_end()}),
gather_map,
cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr)
->release();
// After gathering the children elements, we need to push down nulls from the root structs
// column to them.
if (values.has_nulls()) {
for (std::unique_ptr<column>& child : scanned_children) {
child = structs::detail::superimpose_nulls(
values.null_mask(), values.null_count(), std::move(child), stream, mr);
}
}
return make_structs_column(values.size(),
std::move(scanned_children),
values.null_count(),
cudf::detail::copy_bitmask(values, stream, mr),
stream,
mr);
}
};
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_argmin.cu
|
/*
* Copyright (c) 2020-2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/sort/group_single_pass_reduction_util.cuh>
#include <cudf/detail/gather.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/gather.h>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_argmin(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
column_view const& key_sort_order,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto indices = type_dispatcher(values.type(),
group_reduction_dispatcher<aggregation::ARGMIN>{},
values,
num_groups,
group_labels,
stream,
mr);
// The functor returns the index of minimum in the sorted values.
// We need the index of minimum in the original unsorted values.
// So use indices to gather the sort order used to sort `values`.
// The values in data buffer of indices corresponding to null values was
// initialized to ARGMIN_SENTINEL. Using gather_if.
// This can't use gather because nulls in gathered column will not store ARGMIN_SENTINEL.
auto indices_view = indices->mutable_view();
thrust::gather_if(rmm::exec_policy(stream),
indices_view.begin<size_type>(), // map first
indices_view.end<size_type>(), // map last
indices_view.begin<size_type>(), // stencil
key_sort_order.begin<size_type>(), // input
indices_view.begin<size_type>(), // result
[] __device__(auto i) { return (i != cudf::detail::ARGMIN_SENTINEL); });
return indices;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_sum.cu
|
/*
* Copyright (c) 2019-2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/utilities/span.hpp>
#include <groupby/sort/group_single_pass_reduction_util.cuh>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_sum(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
return type_dispatcher(values_type,
group_reduction_dispatcher<aggregation::SUM>{},
values,
num_groups,
group_labels,
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/scan.cpp
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/common/utils.hpp>
#include <groupby/sort/functors.hpp>
#include <groupby/sort/group_reductions.hpp>
#include <groupby/sort/group_scan.hpp>
#include <cudf/aggregation.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/detail/aggregation/result_cache.hpp>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/scatter.hpp>
#include <cudf/detail/sequence.hpp>
#include <cudf/detail/sorting.hpp>
#include <cudf/detail/structs/utilities.hpp>
#include <cudf/groupby.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/table/table.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/error.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <memory>
namespace cudf {
namespace groupby {
namespace detail {
/**
* @brief Functor to dispatch aggregation with
*
* This functor is to be used with `aggregation_dispatcher` to compute the
* appropriate aggregation. If the values on which to run the aggregation are
* unchanged, then this functor should be re-used. This is because it stores
* memoised sorted and/or grouped values and re-using will save on computation
* of these values.
*/
struct scan_result_functor final : store_result_functor {
using store_result_functor::store_result_functor;
template <aggregation::Kind k>
void operator()(aggregation const& agg)
{
CUDF_FAIL("Unsupported groupby scan aggregation");
}
private:
column_view get_grouped_values()
{
// early exit if presorted
if (is_presorted()) { return values; }
// TODO (dm): After implementing single pass multi-agg, explore making a
// cache of all grouped value columns rather than one at a time
if (grouped_values)
return grouped_values->view();
else
return (grouped_values = helper.grouped_values(values, stream, mr))->view();
};
};
template <>
void scan_result_functor::operator()<aggregation::SUM>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(
values,
agg,
detail::sum_scan(
get_grouped_values(), helper.num_groups(stream), helper.group_labels(stream), stream, mr));
}
template <>
void scan_result_functor::operator()<aggregation::MIN>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(
values,
agg,
detail::min_scan(
get_grouped_values(), helper.num_groups(stream), helper.group_labels(stream), stream, mr));
}
template <>
void scan_result_functor::operator()<aggregation::MAX>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(
values,
agg,
detail::max_scan(
get_grouped_values(), helper.num_groups(stream), helper.group_labels(stream), stream, mr));
}
template <>
void scan_result_functor::operator()<aggregation::COUNT_ALL>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
cache.add_result(values, agg, detail::count_scan(helper.group_labels(stream), stream, mr));
}
template <>
void scan_result_functor::operator()<aggregation::RANK>(aggregation const& agg)
{
if (cache.has_result(values, agg)) return;
CUDF_EXPECTS(!cudf::structs::detail::is_or_has_nested_lists(values),
"Unsupported list type in grouped rank scan.");
auto const& rank_agg = dynamic_cast<cudf::detail::rank_aggregation const&>(agg);
auto const& group_labels = helper.group_labels(stream);
auto const group_labels_view = column_view(cudf::device_span<size_type const>(group_labels));
auto const gather_map = [&]() {
if (is_presorted()) { // assumes both keys and values are sorted, Spark does this.
return cudf::detail::sequence(group_labels.size(),
*cudf::make_fixed_width_scalar(size_type{0}, stream),
stream,
rmm::mr::get_current_device_resource());
} else {
auto sort_order = (rank_agg._method == rank_method::FIRST ? cudf::detail::stable_sorted_order
: cudf::detail::sorted_order);
return sort_order(table_view({group_labels_view, get_grouped_values()}),
{order::ASCENDING, rank_agg._column_order},
{null_order::AFTER, rank_agg._null_precedence},
stream,
rmm::mr::get_current_device_resource());
}
}();
auto rank_scan = [&]() {
switch (rank_agg._method) {
case rank_method::FIRST: return detail::first_rank_scan;
case rank_method::AVERAGE: return detail::average_rank_scan;
case rank_method::DENSE: return detail::dense_rank_scan;
case rank_method::MIN: return detail::min_rank_scan;
case rank_method::MAX: return detail::max_rank_scan;
default: CUDF_FAIL("Unsupported rank method in groupby scan");
}
}();
auto result = rank_scan(get_grouped_values(),
*gather_map,
helper.group_labels(stream),
helper.group_offsets(stream),
stream,
rmm::mr::get_current_device_resource());
if (rank_agg._percentage != rank_percentage::NONE) {
auto count = get_grouped_values().nullable() and rank_agg._null_handling == null_policy::EXCLUDE
? detail::group_count_valid(get_grouped_values(),
helper.group_labels(stream),
helper.num_groups(stream),
stream,
rmm::mr::get_current_device_resource())
: detail::group_count_all(helper.group_offsets(stream),
helper.num_groups(stream),
stream,
rmm::mr::get_current_device_resource());
result = detail::group_rank_to_percentage(rank_agg._method,
rank_agg._percentage,
*result,
*count,
helper.group_labels(stream),
helper.group_offsets(stream),
stream,
mr);
}
result = std::move(
cudf::detail::scatter(table_view{{*result}}, *gather_map, table_view{{*result}}, stream, mr)
->release()[0]);
if (rank_agg._null_handling == null_policy::EXCLUDE) {
auto const values = get_grouped_values();
result->set_null_mask(cudf::detail::copy_bitmask(values, stream, mr), values.null_count());
}
cache.add_result(values, agg, std::move(result));
}
} // namespace detail
// Sort-based groupby
std::pair<std::unique_ptr<table>, std::vector<aggregation_result>> groupby::sort_scan(
host_span<scan_request const> requests,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// We're going to start by creating a cache of results so that aggs that
// depend on other aggs will not have to be recalculated. e.g. mean depends on
// sum and count. std depends on mean and count
cudf::detail::result_cache cache(requests.size());
for (auto const& request : requests) {
auto store_functor =
detail::scan_result_functor(request.values, helper(), cache, stream, mr, _keys_are_sorted);
for (auto const& aggregation : request.aggregations) {
// TODO (dm): single pass compute all supported reductions
cudf::detail::aggregation_dispatcher(aggregation->kind, store_functor, *aggregation);
}
}
auto results = detail::extract_results(requests, cache, stream, mr);
return std::pair(helper().sorted_keys(stream, mr), std::move(results));
}
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_min.cu
|
/*
* Copyright (c) 2019-2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/sort/group_single_pass_reduction_util.cuh>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_min(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
return type_dispatcher(values_type,
group_reduction_dispatcher<aggregation::MIN>{},
values,
num_groups,
group_labels,
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_replace_nulls.cu
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/groupby/group_replace_nulls.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/replace/nulls.cuh>
#include <cudf/replace.hpp>
#include <rmm/device_uvector.hpp>
#include <thrust/functional.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/reverse_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/scan.h>
#include <thrust/tuple.h>
#include <utility>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_replace_nulls(cudf::column_view const& grouped_value,
device_span<size_type const> group_labels,
cudf::replace_policy replace_policy,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
cudf::size_type size = grouped_value.size();
auto device_in = cudf::column_device_view::create(grouped_value, stream);
auto index = thrust::make_counting_iterator<cudf::size_type>(0);
auto valid_it = cudf::detail::make_validity_iterator(*device_in);
auto in_begin = thrust::make_zip_iterator(thrust::make_tuple(index, valid_it));
rmm::device_uvector<cudf::size_type> gather_map(size, stream);
auto gm_begin = thrust::make_zip_iterator(
thrust::make_tuple(gather_map.begin(), thrust::make_discard_iterator()));
auto func = cudf::detail::replace_policy_functor();
thrust::equal_to<cudf::size_type> eq;
if (replace_policy == cudf::replace_policy::PRECEDING) {
thrust::inclusive_scan_by_key(rmm::exec_policy(stream),
group_labels.begin(),
group_labels.begin() + size,
in_begin,
gm_begin,
eq,
func);
} else {
auto gl_rbegin = thrust::make_reverse_iterator(group_labels.begin() + size);
auto in_rbegin = thrust::make_reverse_iterator(in_begin + size);
auto gm_rbegin = thrust::make_reverse_iterator(gm_begin + size);
thrust::inclusive_scan_by_key(
rmm::exec_policy(stream), gl_rbegin, gl_rbegin + size, in_rbegin, gm_rbegin, eq, func);
}
auto output = cudf::detail::gather(cudf::table_view({grouped_value}),
gather_map,
cudf::out_of_bounds_policy::DONT_CHECK,
cudf::detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
return std::move(output->release()[0]);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/sort/group_max.cu
|
/*
* Copyright (c) 2019-2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <groupby/sort/group_single_pass_reduction_util.cuh>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace groupby {
namespace detail {
std::unique_ptr<column> group_max(column_view const& values,
size_type num_groups,
cudf::device_span<size_type const> group_labels,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_type = cudf::is_dictionary(values.type())
? dictionary_column_view(values).keys().type()
: values.type();
return type_dispatcher(values_type,
group_reduction_dispatcher<aggregation::MAX>{},
values,
num_groups,
group_labels,
stream,
mr);
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src/groupby
|
rapidsai_public_repos/cudf/cpp/src/groupby/common/utils.hpp
|
/*
* Copyright (c) 2019-2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/detail/aggregation/result_cache.hpp>
#include <cudf/detail/groupby.hpp>
#include <cudf/utilities/span.hpp>
#include <memory>
#include <vector>
namespace cudf {
namespace groupby {
namespace detail {
template <typename RequestType>
inline std::vector<aggregation_result> extract_results(host_span<RequestType const> requests,
cudf::detail::result_cache& cache,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
std::vector<aggregation_result> results(requests.size());
std::unordered_map<std::pair<column_view, std::reference_wrapper<aggregation const>>,
column_view,
cudf::detail::pair_column_aggregation_hash,
cudf::detail::pair_column_aggregation_equal_to>
repeated_result;
for (size_t i = 0; i < requests.size(); i++) {
for (auto&& agg : requests[i].aggregations) {
if (cache.has_result(requests[i].values, *agg)) {
results[i].results.emplace_back(cache.release_result(requests[i].values, *agg));
repeated_result[{requests[i].values, *agg}] = results[i].results.back()->view();
} else {
auto it = repeated_result.find({requests[i].values, *agg});
if (it != repeated_result.end()) {
results[i].results.emplace_back(std::make_unique<column>(it->second, stream, mr));
} else {
CUDF_FAIL("Cannot extract result from the cache");
}
}
}
}
return results;
}
} // namespace detail
} // namespace groupby
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_semi.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "join_common_utils.cuh"
#include "join_common_utils.hpp"
#include "mixed_join_kernels_semi.cuh"
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/ast/expressions.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/join.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/fill.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/scan.h>
#include <optional>
#include <utility>
namespace cudf {
namespace detail {
namespace {
/**
* @brief Device functor to create a pair of hash value and index for a given row.
*/
struct make_pair_function_semi {
__device__ __forceinline__ cudf::detail::pair_type operator()(size_type i) const noexcept
{
// The value is irrelevant since we only ever use the hash map to check for
// membership of a particular row index.
return cuco::make_pair(static_cast<hash_value_type>(i), 0);
}
};
/**
* @brief Equality comparator that composes two row_equality comparators.
*/
class double_row_equality {
public:
double_row_equality(row_equality equality_comparator, row_equality conditional_comparator)
: _equality_comparator{equality_comparator}, _conditional_comparator{conditional_comparator}
{
}
__device__ bool operator()(size_type lhs_row_index, size_type rhs_row_index) const noexcept
{
using experimental::row::lhs_index_type;
using experimental::row::rhs_index_type;
return _equality_comparator(lhs_index_type{lhs_row_index}, rhs_index_type{rhs_row_index}) &&
_conditional_comparator(lhs_index_type{lhs_row_index}, rhs_index_type{rhs_row_index});
}
private:
row_equality _equality_comparator;
row_equality _conditional_comparator;
};
} // namespace
std::unique_ptr<rmm::device_uvector<size_type>> mixed_join_semi(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
join_kind join_type,
std::optional<std::pair<std::size_t, device_span<size_type const>>> output_size_data,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS((join_type != join_kind::INNER_JOIN) && (join_type != join_kind::LEFT_JOIN) &&
(join_type != join_kind::FULL_JOIN),
"Inner, left, and full joins should use mixed_join.");
CUDF_EXPECTS(left_conditional.num_rows() == left_equality.num_rows(),
"The left conditional and equality tables must have the same number of rows.");
CUDF_EXPECTS(right_conditional.num_rows() == right_equality.num_rows(),
"The right conditional and equality tables must have the same number of rows.");
auto const right_num_rows{right_conditional.num_rows()};
auto const left_num_rows{left_conditional.num_rows()};
auto const swap_tables = (join_type == join_kind::INNER_JOIN) && (right_num_rows > left_num_rows);
// The "outer" table is the larger of the two tables. The kernels are
// launched with one thread per row of the outer table, which also means that
// it is the probe table for the hash
auto const outer_num_rows{swap_tables ? right_num_rows : left_num_rows};
// We can immediately filter out cases where the right table is empty. In
// some cases, we return all the rows of the left table with a corresponding
// null index for the right table; in others, we return an empty output.
if (right_num_rows == 0) {
switch (join_type) {
// Anti and semi return all the row indices from left
// with a corresponding NULL from the right.
case join_kind::LEFT_ANTI_JOIN:
return get_trivial_left_join_indices(
left_conditional, stream, rmm::mr::get_current_device_resource())
.first;
// Inner and left semi joins return empty output because no matches can exist.
case join_kind::LEFT_SEMI_JOIN:
return std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr);
default: CUDF_FAIL("Invalid join kind."); break;
}
} else if (left_num_rows == 0) {
switch (join_type) {
// Anti and semi joins both return empty sets.
case join_kind::LEFT_ANTI_JOIN:
case join_kind::LEFT_SEMI_JOIN:
return std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr);
default: CUDF_FAIL("Invalid join kind."); break;
}
}
// If evaluating the expression may produce null outputs we create a nullable
// output column and follow the null-supporting expression evaluation code
// path.
auto const has_nulls = cudf::nullate::DYNAMIC{
cudf::has_nulls(left_equality) || cudf::has_nulls(right_equality) ||
binary_predicate.may_evaluate_null(left_conditional, right_conditional, stream)};
auto const parser = ast::detail::expression_parser{
binary_predicate, left_conditional, right_conditional, has_nulls, stream, mr};
CUDF_EXPECTS(parser.output_type().id() == type_id::BOOL8,
"The expression must produce a boolean output.");
// TODO: The non-conditional join impls start with a dictionary matching,
// figure out what that is and what it's needed for (and if conditional joins
// need to do the same).
auto& probe = swap_tables ? right_equality : left_equality;
auto& build = swap_tables ? left_equality : right_equality;
auto probe_view = table_device_view::create(probe, stream);
auto build_view = table_device_view::create(build, stream);
auto left_conditional_view = table_device_view::create(left_conditional, stream);
auto right_conditional_view = table_device_view::create(right_conditional, stream);
auto const preprocessed_build =
experimental::row::equality::preprocessed_table::create(build, stream);
auto const preprocessed_probe =
experimental::row::equality::preprocessed_table::create(probe, stream);
auto const row_comparator =
cudf::experimental::row::equality::two_table_comparator{preprocessed_probe, preprocessed_build};
auto const equality_probe = row_comparator.equal_to<false>(has_nulls, compare_nulls);
semi_map_type hash_table{compute_hash_table_size(build.num_rows()),
cuco::empty_key{std::numeric_limits<hash_value_type>::max()},
cuco::empty_value{cudf::detail::JoinNoneValue},
detail::hash_table_allocator_type{default_allocator<char>{}, stream},
stream.value()};
// Create hash table containing all keys found in right table
// TODO: To add support for nested columns we will need to flatten in many
// places. However, this probably isn't worth adding any time soon since we
// won't be able to support AST conditions for those types anyway.
auto const build_nulls = cudf::nullate::DYNAMIC{cudf::has_nulls(build)};
auto const row_hash_build = cudf::experimental::row::hash::row_hasher{preprocessed_build};
auto const hash_build = row_hash_build.device_hasher(build_nulls);
// Since we may see multiple rows that are identical in the equality tables
// but differ in the conditional tables, the equality comparator used for
// insertion must account for both sets of tables. An alternative solution
// would be to use a multimap, but that solution would store duplicates where
// equality and conditional rows are equal, so this approach is preferable.
// One way to make this solution even more efficient would be to only include
// the columns of the conditional table that are used by the expression, but
// that requires additional plumbing through the AST machinery and is out of
// scope for now.
auto const row_comparator_build =
cudf::experimental::row::equality::two_table_comparator{preprocessed_build, preprocessed_build};
auto const equality_build_equality =
row_comparator_build.equal_to<false>(build_nulls, compare_nulls);
auto const preprocessed_build_condtional =
experimental::row::equality::preprocessed_table::create(
swap_tables ? left_conditional : right_conditional, stream);
auto const row_comparator_conditional_build =
cudf::experimental::row::equality::two_table_comparator{preprocessed_build_condtional,
preprocessed_build_condtional};
auto const equality_build_conditional =
row_comparator_conditional_build.equal_to<false>(build_nulls, compare_nulls);
double_row_equality equality_build{equality_build_equality, equality_build_conditional};
make_pair_function_semi pair_func_build{};
auto iter = cudf::detail::make_counting_transform_iterator(0, pair_func_build);
// skip rows that are null here.
if ((compare_nulls == null_equality::EQUAL) or (not nullable(build))) {
hash_table.insert(iter, iter + right_num_rows, hash_build, equality_build, stream.value());
} else {
thrust::counting_iterator<cudf::size_type> stencil(0);
auto const [row_bitmask, _] =
cudf::detail::bitmask_and(build, stream, rmm::mr::get_current_device_resource());
row_is_valid pred{static_cast<bitmask_type const*>(row_bitmask.data())};
// insert valid rows
hash_table.insert_if(
iter, iter + right_num_rows, stencil, pred, hash_build, equality_build, stream.value());
}
auto hash_table_view = hash_table.get_device_view();
// For inner joins we support optimizing the join by launching one thread for
// whichever table is larger rather than always using the left table.
detail::grid_1d const config(outer_num_rows, DEFAULT_JOIN_BLOCK_SIZE);
auto const shmem_size_per_block = parser.shmem_per_thread * config.num_threads_per_block;
join_kind const kernel_join_type =
join_type == join_kind::FULL_JOIN ? join_kind::LEFT_JOIN : join_type;
// If the join size data was not provided as an input, compute it here.
std::size_t join_size;
// Using an optional because we only need to allocate a new vector if one was
// not passed as input, and rmm::device_uvector is not default constructible
std::optional<rmm::device_uvector<size_type>> matches_per_row{};
device_span<size_type const> matches_per_row_span{};
auto const row_hash = cudf::experimental::row::hash::row_hasher{preprocessed_probe};
auto const hash_probe = row_hash.device_hasher(has_nulls);
if (output_size_data.has_value()) {
join_size = output_size_data->first;
matches_per_row_span = output_size_data->second;
} else {
// Allocate storage for the counter used to get the size of the join output
rmm::device_scalar<std::size_t> size(0, stream, mr);
matches_per_row =
rmm::device_uvector<size_type>{static_cast<std::size_t>(outer_num_rows), stream, mr};
// Note that the view goes out of scope after this else statement, but the
// data owned by matches_per_row stays alive so the data pointer is valid.
auto mutable_matches_per_row_span = cudf::device_span<size_type>{
matches_per_row->begin(), static_cast<std::size_t>(outer_num_rows)};
matches_per_row_span = cudf::device_span<size_type const>{
matches_per_row->begin(), static_cast<std::size_t>(outer_num_rows)};
if (has_nulls) {
compute_mixed_join_output_size_semi<DEFAULT_JOIN_BLOCK_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
kernel_join_type,
hash_table_view,
parser.device_expression_data,
swap_tables,
size.data(),
mutable_matches_per_row_span);
} else {
compute_mixed_join_output_size_semi<DEFAULT_JOIN_BLOCK_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
kernel_join_type,
hash_table_view,
parser.device_expression_data,
swap_tables,
size.data(),
mutable_matches_per_row_span);
}
join_size = size.value(stream);
}
if (join_size == 0) { return std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr); }
// Given the number of matches per row, we need to compute the offsets for insertion.
auto join_result_offsets =
rmm::device_uvector<size_type>{static_cast<std::size_t>(outer_num_rows), stream, mr};
thrust::exclusive_scan(rmm::exec_policy{stream},
matches_per_row_span.begin(),
matches_per_row_span.end(),
join_result_offsets.begin());
auto left_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto const& join_output_l = left_indices->data();
if (has_nulls) {
mixed_join_semi<DEFAULT_JOIN_BLOCK_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
kernel_join_type,
hash_table_view,
join_output_l,
parser.device_expression_data,
join_result_offsets.data(),
swap_tables);
} else {
mixed_join_semi<DEFAULT_JOIN_BLOCK_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
kernel_join_type,
hash_table_view,
join_output_l,
parser.device_expression_data,
join_result_offsets.data(),
swap_tables);
}
return left_indices;
}
std::pair<std::size_t, std::unique_ptr<rmm::device_uvector<size_type>>>
compute_mixed_join_output_size_semi(table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
join_kind join_type,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(
(join_type != join_kind::INNER_JOIN) && (join_type != join_kind::LEFT_JOIN) &&
(join_type != join_kind::FULL_JOIN),
"Inner, left, and full join size estimation should use compute_mixed_join_output_size.");
CUDF_EXPECTS(left_conditional.num_rows() == left_equality.num_rows(),
"The left conditional and equality tables must have the same number of rows.");
CUDF_EXPECTS(right_conditional.num_rows() == right_equality.num_rows(),
"The right conditional and equality tables must have the same number of rows.");
auto const right_num_rows{right_conditional.num_rows()};
auto const left_num_rows{left_conditional.num_rows()};
auto const swap_tables = (join_type == join_kind::INNER_JOIN) && (right_num_rows > left_num_rows);
// The "outer" table is the larger of the two tables. The kernels are
// launched with one thread per row of the outer table, which also means that
// it is the probe table for the hash
auto const outer_num_rows{swap_tables ? right_num_rows : left_num_rows};
auto matches_per_row = std::make_unique<rmm::device_uvector<size_type>>(
static_cast<std::size_t>(outer_num_rows), stream, mr);
auto matches_per_row_span = cudf::device_span<size_type>{
matches_per_row->begin(), static_cast<std::size_t>(outer_num_rows)};
// We can immediately filter out cases where one table is empty. In
// some cases, we return all the rows of the other table with a corresponding
// null index for the empty table; in others, we return an empty output.
if (right_num_rows == 0) {
switch (join_type) {
// Left, left anti, and full all return all the row indices from left
// with a corresponding NULL from the right.
case join_kind::LEFT_ANTI_JOIN: {
thrust::fill(matches_per_row->begin(), matches_per_row->end(), 1);
return {left_num_rows, std::move(matches_per_row)};
}
// Inner and left semi joins return empty output because no matches can exist.
case join_kind::LEFT_SEMI_JOIN: return {0, std::move(matches_per_row)};
default: CUDF_FAIL("Invalid join kind."); break;
}
} else if (left_num_rows == 0) {
switch (join_type) {
// Left, left anti, left semi, and inner joins all return empty sets.
case join_kind::LEFT_ANTI_JOIN:
case join_kind::LEFT_SEMI_JOIN: {
thrust::fill(matches_per_row->begin(), matches_per_row->end(), 0);
return {0, std::move(matches_per_row)};
}
default: CUDF_FAIL("Invalid join kind."); break;
}
}
// If evaluating the expression may produce null outputs we create a nullable
// output column and follow the null-supporting expression evaluation code
// path.
auto const has_nulls = cudf::nullate::DYNAMIC{
cudf::has_nulls(left_equality) || cudf::has_nulls(right_equality) ||
binary_predicate.may_evaluate_null(left_conditional, right_conditional, stream)};
auto const parser = ast::detail::expression_parser{
binary_predicate, left_conditional, right_conditional, has_nulls, stream, mr};
CUDF_EXPECTS(parser.output_type().id() == type_id::BOOL8,
"The expression must produce a boolean output.");
// TODO: The non-conditional join impls start with a dictionary matching,
// figure out what that is and what it's needed for (and if conditional joins
// need to do the same).
auto& probe = swap_tables ? right_equality : left_equality;
auto& build = swap_tables ? left_equality : right_equality;
auto probe_view = table_device_view::create(probe, stream);
auto build_view = table_device_view::create(build, stream);
auto left_conditional_view = table_device_view::create(left_conditional, stream);
auto right_conditional_view = table_device_view::create(right_conditional, stream);
auto const preprocessed_build =
experimental::row::equality::preprocessed_table::create(build, stream);
auto const preprocessed_probe =
experimental::row::equality::preprocessed_table::create(probe, stream);
auto const row_comparator =
cudf::experimental::row::equality::two_table_comparator{preprocessed_probe, preprocessed_build};
auto const equality_probe = row_comparator.equal_to<false>(has_nulls, compare_nulls);
semi_map_type hash_table{compute_hash_table_size(build.num_rows()),
cuco::empty_key{std::numeric_limits<hash_value_type>::max()},
cuco::empty_value{cudf::detail::JoinNoneValue},
detail::hash_table_allocator_type{default_allocator<char>{}, stream},
stream.value()};
// Create hash table containing all keys found in right table
// TODO: To add support for nested columns we will need to flatten in many
// places. However, this probably isn't worth adding any time soon since we
// won't be able to support AST conditions for those types anyway.
auto const build_nulls = cudf::nullate::DYNAMIC{cudf::has_nulls(build)};
auto const row_hash_build = cudf::experimental::row::hash::row_hasher{preprocessed_build};
auto const hash_build = row_hash_build.device_hasher(build_nulls);
// Since we may see multiple rows that are identical in the equality tables
// but differ in the conditional tables, the equality comparator used for
// insertion must account for both sets of tables. An alternative solution
// would be to use a multimap, but that solution would store duplicates where
// equality and conditional rows are equal, so this approach is preferable.
// One way to make this solution even more efficient would be to only include
// the columns of the conditional table that are used by the expression, but
// that requires additional plumbing through the AST machinery and is out of
// scope for now.
auto const row_comparator_build =
cudf::experimental::row::equality::two_table_comparator{preprocessed_build, preprocessed_build};
auto const equality_build_equality =
row_comparator_build.equal_to<false>(build_nulls, compare_nulls);
auto const preprocessed_build_condtional =
experimental::row::equality::preprocessed_table::create(
swap_tables ? left_conditional : right_conditional, stream);
auto const row_comparator_conditional_build =
cudf::experimental::row::equality::two_table_comparator{preprocessed_build_condtional,
preprocessed_build_condtional};
auto const equality_build_conditional =
row_comparator_conditional_build.equal_to<false>(build_nulls, compare_nulls);
double_row_equality equality_build{equality_build_equality, equality_build_conditional};
make_pair_function_semi pair_func_build{};
auto iter = cudf::detail::make_counting_transform_iterator(0, pair_func_build);
// skip rows that are null here.
if ((compare_nulls == null_equality::EQUAL) or (not nullable(build))) {
hash_table.insert(iter, iter + right_num_rows, hash_build, equality_build, stream.value());
} else {
thrust::counting_iterator<cudf::size_type> stencil(0);
auto const [row_bitmask, _] =
cudf::detail::bitmask_and(build, stream, rmm::mr::get_current_device_resource());
row_is_valid pred{static_cast<bitmask_type const*>(row_bitmask.data())};
// insert valid rows
hash_table.insert_if(
iter, iter + right_num_rows, stencil, pred, hash_build, equality_build, stream.value());
}
auto hash_table_view = hash_table.get_device_view();
// For inner joins we support optimizing the join by launching one thread for
// whichever table is larger rather than always using the left table.
detail::grid_1d const config(outer_num_rows, DEFAULT_JOIN_BLOCK_SIZE);
auto const shmem_size_per_block = parser.shmem_per_thread * config.num_threads_per_block;
// Allocate storage for the counter used to get the size of the join output
rmm::device_scalar<std::size_t> size(0, stream, mr);
auto const row_hash = cudf::experimental::row::hash::row_hasher{preprocessed_probe};
auto const hash_probe = row_hash.device_hasher(has_nulls);
// Determine number of output rows without actually building the output to simply
// find what the size of the output will be.
if (has_nulls) {
compute_mixed_join_output_size_semi<DEFAULT_JOIN_BLOCK_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
join_type,
hash_table_view,
parser.device_expression_data,
swap_tables,
size.data(),
matches_per_row_span);
} else {
compute_mixed_join_output_size_semi<DEFAULT_JOIN_BLOCK_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
join_type,
hash_table_view,
parser.device_expression_data,
swap_tables,
size.data(),
matches_per_row_span);
}
return {size.value(stream), std::move(matches_per_row)};
}
} // namespace detail
std::pair<std::size_t, std::unique_ptr<rmm::device_uvector<size_type>>> mixed_left_semi_join_size(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::compute_mixed_join_output_size_semi(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::LEFT_SEMI_JOIN,
cudf::get_default_stream(),
mr);
}
std::unique_ptr<rmm::device_uvector<size_type>> mixed_left_semi_join(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
std::optional<std::pair<std::size_t, device_span<size_type const>>> output_size_data,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::mixed_join_semi(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::LEFT_SEMI_JOIN,
output_size_data,
cudf::get_default_stream(),
mr);
}
std::pair<std::size_t, std::unique_ptr<rmm::device_uvector<size_type>>> mixed_left_anti_join_size(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::compute_mixed_join_output_size_semi(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::LEFT_ANTI_JOIN,
cudf::get_default_stream(),
mr);
}
std::unique_ptr<rmm::device_uvector<size_type>> mixed_left_anti_join(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
std::optional<std::pair<std::size_t, device_span<size_type const>>> output_size_data,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::mixed_join_semi(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::LEFT_ANTI_JOIN,
output_size_data,
cudf::get_default_stream(),
mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/join.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "join_common_utils.hpp"
#include <cudf/detail/gather.cuh>
#include <cudf/dictionary/detail/update_keys.hpp>
#include <cudf/join.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace detail {
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
inner_join(table_view const& left_input,
table_view const& right_input,
null_equality compare_nulls,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Make sure any dictionary columns have matched key sets.
// This will return any new dictionary columns created as well as updated table_views.
auto matched = cudf::dictionary::detail::match_dictionaries(
{left_input, right_input},
stream,
rmm::mr::get_current_device_resource()); // temporary objects returned
// now rebuild the table views with the updated ones
auto const left = matched.second.front();
auto const right = matched.second.back();
auto const has_nulls = cudf::has_nested_nulls(left) || cudf::has_nested_nulls(right)
? cudf::nullable_join::YES
: cudf::nullable_join::NO;
// For `inner_join`, we can freely choose either the `left` or `right` table to use for
// building/probing the hash map. Because building is typically more expensive than probing, we
// build the hash map from the smaller table.
if (right.num_rows() > left.num_rows()) {
cudf::hash_join hj_obj(left, has_nulls, compare_nulls, stream);
auto [right_result, left_result] = hj_obj.inner_join(right, std::nullopt, stream, mr);
return std::pair(std::move(left_result), std::move(right_result));
} else {
cudf::hash_join hj_obj(right, has_nulls, compare_nulls, stream);
return hj_obj.inner_join(left, std::nullopt, stream, mr);
}
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
left_join(table_view const& left_input,
table_view const& right_input,
null_equality compare_nulls,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Make sure any dictionary columns have matched key sets.
// This will return any new dictionary columns created as well as updated table_views.
auto matched = cudf::dictionary::detail::match_dictionaries(
{left_input, right_input}, // these should match
stream,
rmm::mr::get_current_device_resource()); // temporary objects returned
// now rebuild the table views with the updated ones
table_view const left = matched.second.front();
table_view const right = matched.second.back();
auto const has_nulls = cudf::has_nested_nulls(left) || cudf::has_nested_nulls(right)
? cudf::nullable_join::YES
: cudf::nullable_join::NO;
cudf::hash_join hj_obj(right, has_nulls, compare_nulls, stream);
return hj_obj.left_join(left, std::nullopt, stream, mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
full_join(table_view const& left_input,
table_view const& right_input,
null_equality compare_nulls,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Make sure any dictionary columns have matched key sets.
// This will return any new dictionary columns created as well as updated table_views.
auto matched = cudf::dictionary::detail::match_dictionaries(
{left_input, right_input}, // these should match
stream,
rmm::mr::get_current_device_resource()); // temporary objects returned
// now rebuild the table views with the updated ones
table_view const left = matched.second.front();
table_view const right = matched.second.back();
auto const has_nulls = cudf::has_nested_nulls(left) || cudf::has_nested_nulls(right)
? cudf::nullable_join::YES
: cudf::nullable_join::NO;
cudf::hash_join hj_obj(right, has_nulls, compare_nulls, stream);
return hj_obj.full_join(left, std::nullopt, stream, mr);
}
} // namespace detail
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
inner_join(table_view const& left,
table_view const& right,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::inner_join(left, right, compare_nulls, cudf::get_default_stream(), mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
left_join(table_view const& left,
table_view const& right,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::left_join(left, right, compare_nulls, cudf::get_default_stream(), mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
full_join(table_view const& left,
table_view const& right,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::full_join(left, right, compare_nulls, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_size_kernel.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mixed_join_size_kernel.cuh"
namespace cudf {
namespace detail {
template __global__ void compute_mixed_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, false>(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::mixed_multimap_type::device_view hash_table_view,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size,
cudf::device_span<cudf::size_type> matches_per_row);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_size_kernel.cuh
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "join_common_utils.cuh"
#include "join_common_utils.hpp"
#include "mixed_join_common_utils.cuh"
#include <cudf/ast/detail/expression_evaluator.cuh>
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/span.hpp>
#include <cooperative_groups.h>
#include <cub/cub.cuh>
#include <thrust/iterator/discard_iterator.h>
namespace cudf {
namespace detail {
namespace cg = cooperative_groups;
template <int block_size, bool has_nulls>
__launch_bounds__(block_size) __global__ void compute_mixed_join_output_size(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::mixed_multimap_type::device_view hash_table_view,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size,
cudf::device_span<cudf::size_type> matches_per_row)
{
// The (required) extern storage of the shared memory array leads to
// conflicting declarations between different templates. The easiest
// workaround is to declare an arbitrary (here char) array type then cast it
// after the fact to the appropriate type.
extern __shared__ char raw_intermediate_storage[];
cudf::ast::detail::IntermediateDataType<has_nulls>* intermediate_storage =
reinterpret_cast<cudf::ast::detail::IntermediateDataType<has_nulls>*>(raw_intermediate_storage);
auto thread_intermediate_storage =
intermediate_storage + (threadIdx.x * device_expression_data.num_intermediates);
std::size_t thread_counter{0};
cudf::size_type const start_idx = threadIdx.x + blockIdx.x * block_size;
cudf::size_type const stride = block_size * gridDim.x;
cudf::size_type const left_num_rows = left_table.num_rows();
cudf::size_type const right_num_rows = right_table.num_rows();
auto const outer_num_rows = (swap_tables ? right_num_rows : left_num_rows);
auto evaluator = cudf::ast::detail::expression_evaluator<has_nulls>(
left_table, right_table, device_expression_data);
auto const empty_key_sentinel = hash_table_view.get_empty_key_sentinel();
make_pair_function pair_func{hash_probe, empty_key_sentinel};
// Figure out the number of elements for this key.
cg::thread_block_tile<1> this_thread = cg::this_thread();
// TODO: Address asymmetry in operator.
auto count_equality = pair_expression_equality<has_nulls>{
evaluator, thread_intermediate_storage, swap_tables, equality_probe};
for (cudf::size_type outer_row_index = start_idx; outer_row_index < outer_num_rows;
outer_row_index += stride) {
auto query_pair = pair_func(outer_row_index);
if (join_type == join_kind::LEFT_JOIN || join_type == join_kind::FULL_JOIN) {
matches_per_row[outer_row_index] =
hash_table_view.pair_count_outer(this_thread, query_pair, count_equality);
} else {
matches_per_row[outer_row_index] =
hash_table_view.pair_count(this_thread, query_pair, count_equality);
}
thread_counter += matches_per_row[outer_row_index];
}
using BlockReduce = cub::BlockReduce<cudf::size_type, block_size>;
__shared__ typename BlockReduce::TempStorage temp_storage;
std::size_t block_counter = BlockReduce(temp_storage).Sum(thread_counter);
// Add block counter to global counter
if (threadIdx.x == 0) {
cuda::atomic_ref<std::size_t, cuda::thread_scope_device> ref{*output_size};
ref.fetch_add(block_counter, cuda::std::memory_order_relaxed);
}
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/join_common_utils.cuh
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "join_common_utils.hpp"
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/table/experimental/row_operators.cuh>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <cub/cub.cuh>
#include <thrust/iterator/counting_iterator.h>
namespace cudf {
namespace detail {
/**
* @brief Remaps a hash value to a new value if it is equal to the specified sentinel value.
*
* @param hash The hash value to potentially remap
* @param sentinel The reserved value
*/
template <typename H, typename S>
constexpr auto remap_sentinel_hash(H hash, S sentinel)
{
// Arbitrarily choose hash - 1
return (hash == sentinel) ? (hash - 1) : hash;
}
/**
* @brief Device functor to create a pair of {hash_value, row_index} for a given row.
*
* @tparam T Type of row index, must be convertible to `size_type`.
* @tparam Hasher The type of internal hasher to compute row hash.
*/
template <typename Hasher, typename T = size_type>
class make_pair_function {
public:
CUDF_HOST_DEVICE make_pair_function(Hasher const& hash, hash_value_type const empty_key_sentinel)
: _hash{hash}, _empty_key_sentinel{empty_key_sentinel}
{
}
__device__ __forceinline__ auto operator()(size_type i) const noexcept
{
// Compute the hash value of row `i`
auto row_hash_value = remap_sentinel_hash(_hash(i), _empty_key_sentinel);
return cuco::make_pair(row_hash_value, T{i});
}
private:
Hasher _hash;
hash_value_type const _empty_key_sentinel;
};
/**
* @brief Device functor to determine if a row is valid.
*/
class row_is_valid {
public:
row_is_valid(bitmask_type const* row_bitmask) : _row_bitmask{row_bitmask} {}
__device__ __inline__ bool operator()(size_type const& i) const noexcept
{
return cudf::bit_is_set(_row_bitmask, i);
}
private:
bitmask_type const* _row_bitmask;
};
/**
* @brief Device functor to determine if two pairs are identical.
*
* This equality comparator is designed for use with cuco::static_multimap's
* pair* APIs, which will compare equality based on comparing (key, value)
* pairs. In the context of joins, these pairs are of the form
* (row_hash, row_id). A hash probe hit indicates that hash of a probe row's hash is
* equal to the hash of the hash of some row in the multimap, at which point we need an
* equality comparator that will check whether the contents of the rows are
* identical. This comparator does so by verifying key equality (i.e. that
* probe_row_hash == build_row_hash) and then using a row_equality_comparator
* to compare the contents of the row indices that are stored as the payload in
* the hash map.
*
* @tparam Comparator The row comparator type to perform row equality comparison from row indices.
*/
template <typename DeviceComparator>
class pair_equality {
public:
pair_equality(DeviceComparator check_row_equality)
: _check_row_equality{std::move(check_row_equality)}
{
}
// The parameters are build/probe rather than left/right because the operator
// is called by cuco's kernels with parameters in this order (note that this
// is an implementation detail that we should eventually stop relying on by
// defining operators with suitable heterogeneous typing). Rather than
// converting to left/right semantics, we can operate directly on build/probe
template <typename LhsPair, typename RhsPair>
__device__ __forceinline__ bool operator()(LhsPair const& lhs, RhsPair const& rhs) const noexcept
{
using experimental::row::lhs_index_type;
using experimental::row::rhs_index_type;
return lhs.first == rhs.first and
_check_row_equality(lhs_index_type{rhs.second}, rhs_index_type{lhs.second});
}
private:
DeviceComparator _check_row_equality;
};
/**
* @brief Computes the trivial left join operation for the case when the
* right table is empty.
*
* In this case all the valid indices of the left table
* are returned with their corresponding right indices being set to
* JoinNoneValue, i.e. -1.
*
* @param left Table of left columns to join
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the result
*
* @return Join output indices vector pair
*/
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
get_trivial_left_join_indices(table_view const& left,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Builds the hash table based on the given `build_table`.
*
* @tparam MultimapType The type of the hash table
*
* @param build Table of columns used to build join hash.
* @param preprocessed_build shared_ptr to cudf::experimental::row::equality::preprocessed_table for
* build
* @param hash_table Build hash table.
* @param has_nulls Flag to denote if build or probe tables have nested nulls
* @param nulls_equal Flag to denote nulls are equal or not.
* @param bitmask Bitmask to denote whether a row is valid.
* @param stream CUDA stream used for device memory operations and kernel launches.
*
*/
template <typename MultimapType>
void build_join_hash_table(
cudf::table_view const& build,
std::shared_ptr<experimental::row::equality::preprocessed_table> const& preprocessed_build,
MultimapType& hash_table,
bool has_nulls,
null_equality nulls_equal,
[[maybe_unused]] bitmask_type const* bitmask,
rmm::cuda_stream_view stream)
{
CUDF_EXPECTS(0 != build.num_columns(), "Selected build dataset is empty");
CUDF_EXPECTS(0 != build.num_rows(), "Build side table has no rows");
auto const row_hash = experimental::row::hash::row_hasher{preprocessed_build};
auto const hash_build = row_hash.device_hasher(nullate::DYNAMIC{has_nulls});
auto const empty_key_sentinel = hash_table.get_empty_key_sentinel();
make_pair_function pair_func{hash_build, empty_key_sentinel};
auto const iter = cudf::detail::make_counting_transform_iterator(0, pair_func);
size_type const build_table_num_rows{build.num_rows()};
if (nulls_equal == cudf::null_equality::EQUAL or (not nullable(build))) {
hash_table.insert(iter, iter + build_table_num_rows, stream.value());
} else {
thrust::counting_iterator<size_type> stencil(0);
row_is_valid pred{bitmask};
// insert valid rows
hash_table.insert_if(iter, iter + build_table_num_rows, stencil, pred, stream.value());
}
}
// Convenient alias for a pair of unique pointers to device uvectors.
using VectorPair = std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>;
/**
* @brief Takes two pairs of vectors and returns a single pair where the first
* element is a vector made from concatenating the first elements of both input
* pairs and the second element is a vector made from concatenating the second
* elements of both input pairs.
*
* This function's primary use is for computing the indices of a full join by
* first performing a left join, then separately getting the complementary
* right join indices, then finally calling this function to concatenate the
* results. In this case, each input VectorPair contains the left and right
* indices from a join.
*
* Note that this is a destructive operation, in that at least one of a or b
* will be invalidated (by a move) by this operation. Calling code should
* assume that neither input VectorPair is valid after this function executes.
*
* @param a The first pair of vectors.
* @param b The second pair of vectors.
* @param stream CUDA stream used for device memory operations and kernel launches
*
* @return A pair of vectors containing the concatenated output.
*/
VectorPair concatenate_vector_pairs(VectorPair& a, VectorPair& b, rmm::cuda_stream_view stream);
/**
* @brief Creates a table containing the complement of left join indices.
*
* This table has two columns. The first one is filled with JoinNoneValue(-1)
* and the second one contains values from 0 to right_table_row_count - 1
* excluding those found in the right_indices column.
*
* @param right_indices Vector of indices
* @param left_table_row_count Number of rows of left table
* @param right_table_row_count Number of rows of right table
* @param stream CUDA stream used for device memory operations and kernel launches.
* @param mr Device memory resource used to allocate the returned vectors.
*
* @return Pair of vectors containing the left join indices complement
*/
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
get_left_join_indices_complement(std::unique_ptr<rmm::device_uvector<size_type>>& right_indices,
size_type left_table_row_count,
size_type right_table_row_count,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Device functor to determine if an index is contained in a range.
*/
template <typename T>
struct valid_range {
T start, stop;
__host__ __device__ valid_range(T const begin, T const end) : start(begin), stop(end) {}
__host__ __device__ __forceinline__ bool operator()(T const index)
{
return ((index >= start) && (index < stop));
}
};
/**
* @brief Adds a pair of indices to the shared memory cache
*
* @param[in] first The first index in the pair
* @param[in] second The second index in the pair
* @param[in,out] current_idx_shared Pointer to shared index that determines
* where in the shared memory cache the pair will be written
* @param[in] warp_id The ID of the warp of the calling the thread
* @param[out] joined_shared_l Pointer to the shared memory cache for left indices
* @param[out] joined_shared_r Pointer to the shared memory cache for right indices
*/
__inline__ __device__ void add_pair_to_cache(size_type const first,
size_type const second,
size_type* current_idx_shared,
int const warp_id,
size_type* joined_shared_l,
size_type* joined_shared_r)
{
size_type my_current_idx{atomicAdd(current_idx_shared + warp_id, size_type(1))};
// its guaranteed to fit into the shared cache
joined_shared_l[my_current_idx] = first;
joined_shared_r[my_current_idx] = second;
}
template <int num_warps, cudf::size_type output_cache_size>
__device__ void flush_output_cache(unsigned int const activemask,
cudf::size_type const max_size,
int const warp_id,
int const lane_id,
cudf::size_type* current_idx,
cudf::size_type current_idx_shared[num_warps],
size_type join_shared_l[num_warps][output_cache_size],
size_type join_shared_r[num_warps][output_cache_size],
size_type* join_output_l,
size_type* join_output_r)
{
// count how many active threads participating here which could be less than warp_size
int num_threads = __popc(activemask);
cudf::size_type output_offset = 0;
if (0 == lane_id) { output_offset = atomicAdd(current_idx, current_idx_shared[warp_id]); }
// No warp sync is necessary here because we are assuming that ShuffleIndex
// is internally using post-CUDA 9.0 synchronization-safe primitives
// (__shfl_sync instead of __shfl). __shfl is technically not guaranteed to
// be safe by the compiler because it is not required by the standard to
// converge divergent branches before executing.
output_offset = cub::ShuffleIndex<detail::warp_size>(output_offset, 0, activemask);
for (int shared_out_idx = lane_id; shared_out_idx < current_idx_shared[warp_id];
shared_out_idx += num_threads) {
cudf::size_type thread_offset = output_offset + shared_out_idx;
if (thread_offset < max_size) {
join_output_l[thread_offset] = join_shared_l[warp_id][shared_out_idx];
join_output_r[thread_offset] = join_shared_r[warp_id][shared_out_idx];
}
}
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_kernel.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mixed_join_kernel.cuh"
namespace cudf {
namespace detail {
template __global__ void mixed_join<DEFAULT_JOIN_BLOCK_SIZE, false>(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::mixed_multimap_type::device_view hash_table_view,
size_type* join_output_l,
size_type* join_output_r,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const* join_result_offsets,
bool const swap_tables);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_size_kernel_nulls.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mixed_join_size_kernel.cuh"
namespace cudf {
namespace detail {
template __global__ void compute_mixed_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, true>(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::mixed_multimap_type::device_view hash_table_view,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size,
cudf::device_span<cudf::size_type> matches_per_row);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/join_common_utils.hpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/detail/join.hpp>
#include <cudf/hashing/detail/default_hash.cuh>
#include <cudf/hashing/detail/hash_allocator.cuh>
#include <cudf/hashing/detail/helper_functions.cuh>
#include <cudf/join.hpp>
#include <cudf/table/row_operators.cuh>
#include <cudf/table/table_view.hpp>
#include <rmm/mr/device/polymorphic_allocator.hpp>
#include <cuco/static_map.cuh>
#include <cuco/static_multimap.cuh>
#include <cuda/atomic>
#include <limits>
namespace cudf {
namespace detail {
constexpr int DEFAULT_JOIN_BLOCK_SIZE = 128;
constexpr int DEFAULT_JOIN_CACHE_SIZE = 128;
constexpr size_type JoinNoneValue = std::numeric_limits<size_type>::min();
using pair_type = cuco::pair<hash_value_type, size_type>;
using hash_type = cuco::murmurhash3_32<hash_value_type>;
using hash_table_allocator_type = rmm::mr::stream_allocator_adaptor<default_allocator<char>>;
using multimap_type = cudf::hash_join::impl_type::map_type;
// Multimap type used for mixed joins. TODO: This is a temporary alias used
// until the mixed joins are converted to using CGs properly. Right now it's
// using a cooperative group of size 1.
using mixed_multimap_type = cuco::static_multimap<hash_value_type,
size_type,
cuda::thread_scope_device,
hash_table_allocator_type,
cuco::double_hashing<1, hash_type, hash_type>>;
using semi_map_type = cuco::
static_map<hash_value_type, size_type, cuda::thread_scope_device, hash_table_allocator_type>;
using row_hash_legacy =
cudf::row_hasher<cudf::hashing::detail::default_hash, cudf::nullate::DYNAMIC>;
using row_equality_legacy = cudf::row_equality_comparator<cudf::nullate::DYNAMIC>;
bool is_trivial_join(table_view const& left, table_view const& right, join_kind join_type);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "join_common_utils.cuh"
#include "join_common_utils.hpp"
#include "mixed_join_kernels.cuh"
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/ast/expressions.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/join.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/span.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/fill.h>
#include <thrust/scan.h>
#include <optional>
#include <utility>
namespace cudf {
namespace detail {
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
mixed_join(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
join_kind join_type,
std::optional<std::pair<std::size_t, device_span<size_type const>>> const& output_size_data,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(left_conditional.num_rows() == left_equality.num_rows(),
"The left conditional and equality tables must have the same number of rows.");
CUDF_EXPECTS(right_conditional.num_rows() == right_equality.num_rows(),
"The right conditional and equality tables must have the same number of rows.");
CUDF_EXPECTS((join_type != join_kind::LEFT_SEMI_JOIN) && (join_type != join_kind::LEFT_ANTI_JOIN),
"Left semi and anti joins should use mixed_join_semi.");
auto const right_num_rows{right_conditional.num_rows()};
auto const left_num_rows{left_conditional.num_rows()};
auto const swap_tables = (join_type == join_kind::INNER_JOIN) && (right_num_rows > left_num_rows);
// The "outer" table is the larger of the two tables. The kernels are
// launched with one thread per row of the outer table, which also means that
// it is the probe table for the hash
auto const outer_num_rows{swap_tables ? right_num_rows : left_num_rows};
// We can immediately filter out cases where the right table is empty. In
// some cases, we return all the rows of the left table with a corresponding
// null index for the right table; in others, we return an empty output.
if (right_num_rows == 0) {
switch (join_type) {
// Left and full joins all return all the row indices from
// left with a corresponding NULL from the right.
case join_kind::LEFT_JOIN:
case join_kind::FULL_JOIN:
return get_trivial_left_join_indices(
left_conditional, stream, rmm::mr::get_current_device_resource());
// Inner joins return empty output because no matches can exist.
case join_kind::INNER_JOIN:
return std::pair(std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr),
std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr));
default: CUDF_FAIL("Invalid join kind."); break;
}
} else if (left_num_rows == 0) {
switch (join_type) {
// Left and inner joins all return empty sets.
case join_kind::LEFT_JOIN:
case join_kind::INNER_JOIN:
return std::pair(std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr),
std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr));
// Full joins need to return the trivial complement.
case join_kind::FULL_JOIN: {
auto ret_flipped = get_trivial_left_join_indices(
right_conditional, stream, rmm::mr::get_current_device_resource());
return std::pair(std::move(ret_flipped.second), std::move(ret_flipped.first));
}
default: CUDF_FAIL("Invalid join kind."); break;
}
}
// If evaluating the expression may produce null outputs we create a nullable
// output column and follow the null-supporting expression evaluation code
// path.
auto const has_nulls = cudf::nullate::DYNAMIC{
cudf::has_nulls(left_equality) || cudf::has_nulls(right_equality) ||
binary_predicate.may_evaluate_null(left_conditional, right_conditional, stream)};
auto const parser = ast::detail::expression_parser{
binary_predicate, left_conditional, right_conditional, has_nulls, stream, mr};
CUDF_EXPECTS(parser.output_type().id() == type_id::BOOL8,
"The expression must produce a boolean output.");
// TODO: The non-conditional join impls start with a dictionary matching,
// figure out what that is and what it's needed for (and if conditional joins
// need to do the same).
auto& probe = swap_tables ? right_equality : left_equality;
auto& build = swap_tables ? left_equality : right_equality;
auto probe_view = table_device_view::create(probe, stream);
auto build_view = table_device_view::create(build, stream);
// Don't use multimap_type because we want a CG size of 1.
mixed_multimap_type hash_table{
compute_hash_table_size(build.num_rows()),
cuco::empty_key{std::numeric_limits<hash_value_type>::max()},
cuco::empty_value{cudf::detail::JoinNoneValue},
stream.value(),
detail::hash_table_allocator_type{default_allocator<char>{}, stream}};
// TODO: To add support for nested columns we will need to flatten in many
// places. However, this probably isn't worth adding any time soon since we
// won't be able to support AST conditions for those types anyway.
auto const row_bitmask =
cudf::detail::bitmask_and(build, stream, rmm::mr::get_current_device_resource()).first;
auto const preprocessed_build =
experimental::row::equality::preprocessed_table::create(build, stream);
build_join_hash_table(build,
preprocessed_build,
hash_table,
has_nulls,
compare_nulls,
static_cast<bitmask_type const*>(row_bitmask.data()),
stream);
auto hash_table_view = hash_table.get_device_view();
auto left_conditional_view = table_device_view::create(left_conditional, stream);
auto right_conditional_view = table_device_view::create(right_conditional, stream);
// For inner joins we support optimizing the join by launching one thread for
// whichever table is larger rather than always using the left table.
detail::grid_1d const config(outer_num_rows, DEFAULT_JOIN_BLOCK_SIZE);
auto const shmem_size_per_block = parser.shmem_per_thread * config.num_threads_per_block;
join_kind const kernel_join_type =
join_type == join_kind::FULL_JOIN ? join_kind::LEFT_JOIN : join_type;
// If the join size data was not provided as an input, compute it here.
std::size_t join_size;
// Using an optional because we only need to allocate a new vector if one was
// not passed as input, and rmm::device_uvector is not default constructible
std::optional<rmm::device_uvector<size_type>> matches_per_row{};
device_span<size_type const> matches_per_row_span{};
auto const preprocessed_probe =
experimental::row::equality::preprocessed_table::create(probe, stream);
auto const row_hash = cudf::experimental::row::hash::row_hasher{preprocessed_probe};
auto const hash_probe = row_hash.device_hasher(has_nulls);
auto const row_comparator =
cudf::experimental::row::equality::two_table_comparator{preprocessed_probe, preprocessed_build};
auto const equality_probe = row_comparator.equal_to<false>(has_nulls, compare_nulls);
if (output_size_data.has_value()) {
join_size = output_size_data->first;
matches_per_row_span = output_size_data->second;
} else {
// Allocate storage for the counter used to get the size of the join output
rmm::device_scalar<std::size_t> size(0, stream, mr);
matches_per_row =
rmm::device_uvector<size_type>{static_cast<std::size_t>(outer_num_rows), stream, mr};
// Note that the view goes out of scope after this else statement, but the
// data owned by matches_per_row stays alive so the data pointer is valid.
auto mutable_matches_per_row_span = cudf::device_span<size_type>{
matches_per_row->begin(), static_cast<std::size_t>(outer_num_rows)};
matches_per_row_span = cudf::device_span<size_type const>{
matches_per_row->begin(), static_cast<std::size_t>(outer_num_rows)};
if (has_nulls) {
compute_mixed_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
kernel_join_type,
hash_table_view,
parser.device_expression_data,
swap_tables,
size.data(),
mutable_matches_per_row_span);
} else {
compute_mixed_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
kernel_join_type,
hash_table_view,
parser.device_expression_data,
swap_tables,
size.data(),
mutable_matches_per_row_span);
}
join_size = size.value(stream);
}
// The initial early exit clauses guarantee that we will not reach this point
// unless both the left and right tables are non-empty. Under that
// constraint, neither left nor full joins can return an empty result since
// at minimum we are guaranteed null matches for all non-matching rows. In
// all other cases (inner, left semi, and left anti joins) if we reach this
// point we can safely return an empty result.
if (join_size == 0) {
return std::pair(std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr),
std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr));
}
// Given the number of matches per row, we need to compute the offsets for insertion.
auto join_result_offsets =
rmm::device_uvector<size_type>{static_cast<std::size_t>(outer_num_rows), stream, mr};
thrust::exclusive_scan(rmm::exec_policy{stream},
matches_per_row_span.begin(),
matches_per_row_span.end(),
join_result_offsets.begin());
auto left_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto right_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto const& join_output_l = left_indices->data();
auto const& join_output_r = right_indices->data();
if (has_nulls) {
mixed_join<DEFAULT_JOIN_BLOCK_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
kernel_join_type,
hash_table_view,
join_output_l,
join_output_r,
parser.device_expression_data,
join_result_offsets.data(),
swap_tables);
} else {
mixed_join<DEFAULT_JOIN_BLOCK_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
kernel_join_type,
hash_table_view,
join_output_l,
join_output_r,
parser.device_expression_data,
join_result_offsets.data(),
swap_tables);
}
auto join_indices = std::pair(std::move(left_indices), std::move(right_indices));
// For full joins, get the indices in the right table that were not joined to
// by any row in the left table.
if (join_type == join_kind::FULL_JOIN) {
auto complement_indices = detail::get_left_join_indices_complement(
join_indices.second, left_num_rows, right_num_rows, stream, mr);
join_indices = detail::concatenate_vector_pairs(join_indices, complement_indices, stream);
}
return join_indices;
}
std::pair<std::size_t, std::unique_ptr<rmm::device_uvector<size_type>>>
compute_mixed_join_output_size(table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
join_kind join_type,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Until we add logic to handle the number of non-matches in the right table,
// full joins are not supported in this function. Note that this does not
// prevent actually performing full joins since we do that by calculating the
// left join and then concatenating the complementary right indices.
CUDF_EXPECTS(join_type != join_kind::FULL_JOIN,
"Size estimation is not available for full joins.");
CUDF_EXPECTS(
(join_type != join_kind::LEFT_SEMI_JOIN) && (join_type != join_kind::LEFT_ANTI_JOIN),
"Left semi and anti join size estimation should use compute_mixed_join_output_size_semi.");
CUDF_EXPECTS(left_conditional.num_rows() == left_equality.num_rows(),
"The left conditional and equality tables must have the same number of rows.");
CUDF_EXPECTS(right_conditional.num_rows() == right_equality.num_rows(),
"The right conditional and equality tables must have the same number of rows.");
auto const right_num_rows{right_conditional.num_rows()};
auto const left_num_rows{left_conditional.num_rows()};
auto const swap_tables = (join_type == join_kind::INNER_JOIN) && (right_num_rows > left_num_rows);
// The "outer" table is the larger of the two tables. The kernels are
// launched with one thread per row of the outer table, which also means that
// it is the probe table for the hash
auto const outer_num_rows{swap_tables ? right_num_rows : left_num_rows};
auto matches_per_row = std::make_unique<rmm::device_uvector<size_type>>(
static_cast<std::size_t>(outer_num_rows), stream, mr);
auto matches_per_row_span = cudf::device_span<size_type>{
matches_per_row->begin(), static_cast<std::size_t>(outer_num_rows)};
// We can immediately filter out cases where one table is empty. In
// some cases, we return all the rows of the other table with a corresponding
// null index for the empty table; in others, we return an empty output.
if (right_num_rows == 0) {
switch (join_type) {
// Left, left anti, and full all return all the row indices from left
// with a corresponding NULL from the right.
case join_kind::LEFT_JOIN:
case join_kind::FULL_JOIN: {
thrust::fill(matches_per_row->begin(), matches_per_row->end(), 1);
return {left_num_rows, std::move(matches_per_row)};
}
// Inner and left semi joins return empty output because no matches can exist.
case join_kind::INNER_JOIN: {
thrust::fill(matches_per_row->begin(), matches_per_row->end(), 0);
return {0, std::move(matches_per_row)};
}
default: CUDF_FAIL("Invalid join kind."); break;
}
} else if (left_num_rows == 0) {
switch (join_type) {
// Left, left anti, left semi, and inner joins all return empty sets.
case join_kind::LEFT_JOIN:
case join_kind::INNER_JOIN: {
thrust::fill(matches_per_row->begin(), matches_per_row->end(), 0);
return {0, std::move(matches_per_row)};
}
// Full joins need to return the trivial complement.
case join_kind::FULL_JOIN: {
thrust::fill(matches_per_row->begin(), matches_per_row->end(), 1);
return {right_num_rows, std::move(matches_per_row)};
}
default: CUDF_FAIL("Invalid join kind."); break;
}
}
// If evaluating the expression may produce null outputs we create a nullable
// output column and follow the null-supporting expression evaluation code
// path.
auto const has_nulls = cudf::nullate::DYNAMIC{
cudf::has_nulls(left_equality) || cudf::has_nulls(right_equality) ||
binary_predicate.may_evaluate_null(left_conditional, right_conditional, stream)};
auto const parser = ast::detail::expression_parser{
binary_predicate, left_conditional, right_conditional, has_nulls, stream, mr};
CUDF_EXPECTS(parser.output_type().id() == type_id::BOOL8,
"The expression must produce a boolean output.");
// TODO: The non-conditional join impls start with a dictionary matching,
// figure out what that is and what it's needed for (and if conditional joins
// need to do the same).
auto& probe = swap_tables ? right_equality : left_equality;
auto& build = swap_tables ? left_equality : right_equality;
auto probe_view = table_device_view::create(probe, stream);
auto build_view = table_device_view::create(build, stream);
// Don't use multimap_type because we want a CG size of 1.
mixed_multimap_type hash_table{
compute_hash_table_size(build.num_rows()),
cuco::empty_key{std::numeric_limits<hash_value_type>::max()},
cuco::empty_value{cudf::detail::JoinNoneValue},
stream.value(),
detail::hash_table_allocator_type{default_allocator<char>{}, stream}};
// TODO: To add support for nested columns we will need to flatten in many
// places. However, this probably isn't worth adding any time soon since we
// won't be able to support AST conditions for those types anyway.
auto const row_bitmask =
cudf::detail::bitmask_and(build, stream, rmm::mr::get_current_device_resource()).first;
auto const preprocessed_build =
experimental::row::equality::preprocessed_table::create(build, stream);
build_join_hash_table(build,
preprocessed_build,
hash_table,
has_nulls,
compare_nulls,
static_cast<bitmask_type const*>(row_bitmask.data()),
stream);
auto hash_table_view = hash_table.get_device_view();
auto left_conditional_view = table_device_view::create(left_conditional, stream);
auto right_conditional_view = table_device_view::create(right_conditional, stream);
// For inner joins we support optimizing the join by launching one thread for
// whichever table is larger rather than always using the left table.
detail::grid_1d const config(outer_num_rows, DEFAULT_JOIN_BLOCK_SIZE);
auto const shmem_size_per_block = parser.shmem_per_thread * config.num_threads_per_block;
// Allocate storage for the counter used to get the size of the join output
rmm::device_scalar<std::size_t> size(0, stream, mr);
auto const preprocessed_probe =
experimental::row::equality::preprocessed_table::create(probe, stream);
auto const row_hash = cudf::experimental::row::hash::row_hasher{preprocessed_probe};
auto const hash_probe = row_hash.device_hasher(has_nulls);
auto const row_comparator =
cudf::experimental::row::equality::two_table_comparator{preprocessed_probe, preprocessed_build};
auto const equality_probe = row_comparator.equal_to<false>(has_nulls, compare_nulls);
// Determine number of output rows without actually building the output to simply
// find what the size of the output will be.
if (has_nulls) {
compute_mixed_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
join_type,
hash_table_view,
parser.device_expression_data,
swap_tables,
size.data(),
matches_per_row_span);
} else {
compute_mixed_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_conditional_view,
*right_conditional_view,
*probe_view,
*build_view,
hash_probe,
equality_probe,
join_type,
hash_table_view,
parser.device_expression_data,
swap_tables,
size.data(),
matches_per_row_span);
}
return {size.value(stream), std::move(matches_per_row)};
}
} // namespace detail
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
mixed_inner_join(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
std::optional<std::pair<std::size_t, device_span<size_type const>>> const output_size_data,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::mixed_join(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::INNER_JOIN,
output_size_data,
cudf::get_default_stream(),
mr);
}
std::pair<std::size_t, std::unique_ptr<rmm::device_uvector<size_type>>> mixed_inner_join_size(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::compute_mixed_join_output_size(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::INNER_JOIN,
cudf::get_default_stream(),
mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
mixed_left_join(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
std::optional<std::pair<std::size_t, device_span<size_type const>>> const output_size_data,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::mixed_join(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::LEFT_JOIN,
output_size_data,
cudf::get_default_stream(),
mr);
}
std::pair<std::size_t, std::unique_ptr<rmm::device_uvector<size_type>>> mixed_left_join_size(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::compute_mixed_join_output_size(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::LEFT_JOIN,
cudf::get_default_stream(),
mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
mixed_full_join(
table_view const& left_equality,
table_view const& right_equality,
table_view const& left_conditional,
table_view const& right_conditional,
ast::expression const& binary_predicate,
null_equality compare_nulls,
std::optional<std::pair<std::size_t, device_span<size_type const>>> const output_size_data,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::mixed_join(left_equality,
right_equality,
left_conditional,
right_conditional,
binary_predicate,
compare_nulls,
detail::join_kind::FULL_JOIN,
output_size_data,
cudf::get_default_stream(),
mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/hash_join.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "join_common_utils.cuh"
#include <cudf/copying.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/join.hpp>
#include <cudf/detail/structs/utilities.hpp>
#include <cudf/join.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_buffer.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/count.h>
#include <thrust/functional.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/zip_iterator.h>
#include <thrust/scatter.h>
#include <thrust/tuple.h>
#include <thrust/uninitialized_fill.h>
#include <cstddef>
#include <iostream>
#include <numeric>
namespace cudf {
namespace detail {
namespace {
/**
* @brief Calculates the exact size of the join output produced when
* joining two tables together.
*
* @throw cudf::logic_error if join is not INNER_JOIN or LEFT_JOIN
*
* @param build_table The right hand table
* @param probe_table The left hand table
* @param preprocessed_build shared_ptr to cudf::experimental::row::equality::preprocessed_table for
* build_table
* @param preprocessed_probe shared_ptr to cudf::experimental::row::equality::preprocessed_table for
* probe_table
* @param hash_table A hash table built on the build table that maps the index
* of every row to the hash value of that row
* @param join The type of join to be performed
* @param has_nulls Flag to denote if build or probe tables have nested nulls
* @param nulls_equal Flag to denote nulls are equal or not
* @param stream CUDA stream used for device memory operations and kernel launches
*
* @return The exact size of the output of the join operation
*/
std::size_t compute_join_output_size(
table_view const& build_table,
table_view const& probe_table,
std::shared_ptr<cudf::experimental::row::equality::preprocessed_table> const& preprocessed_build,
std::shared_ptr<cudf::experimental::row::equality::preprocessed_table> const& preprocessed_probe,
cudf::detail::multimap_type const& hash_table,
join_kind join,
bool has_nulls,
cudf::null_equality nulls_equal,
rmm::cuda_stream_view stream)
{
size_type const build_table_num_rows{build_table.num_rows()};
size_type const probe_table_num_rows{probe_table.num_rows()};
// If the build table is empty, we know exactly how large the output
// will be for the different types of joins and can return immediately
if (0 == build_table_num_rows) {
switch (join) {
// Inner join with an empty table will have no output
case join_kind::INNER_JOIN: return 0;
// Left join with an empty table will have an output of NULL rows
// equal to the number of rows in the probe table
case join_kind::LEFT_JOIN: return probe_table_num_rows;
default: CUDF_FAIL("Unsupported join type");
}
}
auto const probe_nulls = cudf::nullate::DYNAMIC{has_nulls};
auto const row_hash = cudf::experimental::row::hash::row_hasher{preprocessed_probe};
auto const hash_probe = row_hash.device_hasher(probe_nulls);
auto const empty_key_sentinel = hash_table.get_empty_key_sentinel();
auto const iter = cudf::detail::make_counting_transform_iterator(
0, make_pair_function{hash_probe, empty_key_sentinel});
auto const row_comparator =
cudf::experimental::row::equality::two_table_comparator{preprocessed_probe, preprocessed_build};
auto const comparator_helper = [&](auto device_comparator) {
pair_equality equality{device_comparator};
if (join == join_kind::LEFT_JOIN) {
return hash_table.pair_count_outer(
iter, iter + probe_table_num_rows, equality, stream.value());
} else {
return hash_table.pair_count(iter, iter + probe_table_num_rows, equality, stream.value());
}
};
if (cudf::detail::has_nested_columns(probe_table)) {
auto const device_comparator = row_comparator.equal_to<true>(has_nulls, nulls_equal);
return comparator_helper(device_comparator);
} else {
auto const device_comparator = row_comparator.equal_to<false>(has_nulls, nulls_equal);
return comparator_helper(device_comparator);
}
}
/**
* @brief Probes the `hash_table` built from `build_table` for tuples in `probe_table`,
* and returns the output indices of `build_table` and `probe_table` as a combined table.
* Behavior is undefined if the provided `output_size` is smaller than the actual output size.
*
* @param build_table Table of build side columns to join
* @param probe_table Table of probe side columns to join
* @param preprocessed_build shared_ptr to cudf::experimental::row::equality::preprocessed_table for
* build_table
* @param preprocessed_probe shared_ptr to cudf::experimental::row::equality::preprocessed_table for
* probe_table
* @param hash_table Hash table built from `build_table`
* @param join The type of join to be performed
* @param has_nulls Flag to denote if build or probe tables have nested nulls
* @param compare_nulls Controls whether null join-key values should match or not
* @param output_size Optional value which allows users to specify the exact output size
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned vectors
*
* @return Join output indices vector pair.
*/
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
probe_join_hash_table(
cudf::table_view const& build_table,
cudf::table_view const& probe_table,
std::shared_ptr<cudf::experimental::row::equality::preprocessed_table> const& preprocessed_build,
std::shared_ptr<cudf::experimental::row::equality::preprocessed_table> const& preprocessed_probe,
cudf::detail::multimap_type const& hash_table,
join_kind join,
bool has_nulls,
null_equality compare_nulls,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Use the output size directly if provided. Otherwise, compute the exact output size
auto const probe_join_type =
(join == cudf::detail::join_kind::FULL_JOIN) ? cudf::detail::join_kind::LEFT_JOIN : join;
std::size_t const join_size = output_size ? *output_size
: compute_join_output_size(build_table,
probe_table,
preprocessed_build,
preprocessed_probe,
hash_table,
probe_join_type,
has_nulls,
compare_nulls,
stream);
// If output size is zero, return immediately
if (join_size == 0) {
return std::pair(std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr),
std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr));
}
auto left_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto right_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto const probe_nulls = cudf::nullate::DYNAMIC{has_nulls};
auto const row_hash = cudf::experimental::row::hash::row_hasher{preprocessed_probe};
auto const hash_probe = row_hash.device_hasher(probe_nulls);
auto const empty_key_sentinel = hash_table.get_empty_key_sentinel();
auto const iter = cudf::detail::make_counting_transform_iterator(
0, make_pair_function{hash_probe, empty_key_sentinel});
cudf::size_type const probe_table_num_rows = probe_table.num_rows();
auto const out1_zip_begin = thrust::make_zip_iterator(
thrust::make_tuple(thrust::make_discard_iterator(), left_indices->begin()));
auto const out2_zip_begin = thrust::make_zip_iterator(
thrust::make_tuple(thrust::make_discard_iterator(), right_indices->begin()));
auto const row_comparator =
cudf::experimental::row::equality::two_table_comparator{preprocessed_probe, preprocessed_build};
auto const comparator_helper = [&](auto device_comparator) {
pair_equality equality{device_comparator};
if (join == cudf::detail::join_kind::FULL_JOIN or join == cudf::detail::join_kind::LEFT_JOIN) {
[[maybe_unused]] auto [out1_zip_end, out2_zip_end] =
hash_table.pair_retrieve_outer(iter,
iter + probe_table_num_rows,
out1_zip_begin,
out2_zip_begin,
equality,
stream.value());
if (join == cudf::detail::join_kind::FULL_JOIN) {
auto const actual_size = thrust::distance(out1_zip_begin, out1_zip_end);
left_indices->resize(actual_size, stream);
right_indices->resize(actual_size, stream);
}
} else {
hash_table.pair_retrieve(iter,
iter + probe_table_num_rows,
out1_zip_begin,
out2_zip_begin,
equality,
stream.value());
}
};
if (cudf::detail::has_nested_columns(probe_table)) {
auto const device_comparator = row_comparator.equal_to<true>(probe_nulls, compare_nulls);
comparator_helper(device_comparator);
} else {
auto const device_comparator = row_comparator.equal_to<false>(probe_nulls, compare_nulls);
comparator_helper(device_comparator);
}
return std::pair(std::move(left_indices), std::move(right_indices));
}
/**
* @brief Probes the `hash_table` built from `build_table` for tuples in `probe_table` twice,
* and returns the output size of a full join operation between `build_table` and `probe_table`.
* TODO: this is a temporary solution as part of `full_join_size`. To be refactored during
* cuco integration.
*
* @param build_table Table of build side columns to join
* @param probe_table Table of probe side columns to join
* @param preprocessed_build shared_ptr to cudf::experimental::row::equality::preprocessed_table for
* build_table
* @param preprocessed_probe shared_ptr to cudf::experimental::row::equality::preprocessed_table for
* probe_table
* @param hash_table Hash table built from `build_table`
* @param has_nulls Flag to denote if build or probe tables have nested nulls
* @param compare_nulls Controls whether null join-key values should match or not
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the intermediate vectors
*
* @return Output size of full join.
*/
std::size_t get_full_join_size(
cudf::table_view const& build_table,
cudf::table_view const& probe_table,
std::shared_ptr<cudf::experimental::row::equality::preprocessed_table> const& preprocessed_build,
std::shared_ptr<cudf::experimental::row::equality::preprocessed_table> const& preprocessed_probe,
cudf::detail::multimap_type const& hash_table,
bool has_nulls,
null_equality compare_nulls,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
std::size_t join_size = compute_join_output_size(build_table,
probe_table,
preprocessed_build,
preprocessed_probe,
hash_table,
cudf::detail::join_kind::LEFT_JOIN,
has_nulls,
compare_nulls,
stream);
// If output size is zero, return immediately
if (join_size == 0) { return join_size; }
auto left_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto right_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto const probe_nulls = cudf::nullate::DYNAMIC{has_nulls};
auto const row_hash = cudf::experimental::row::hash::row_hasher{preprocessed_probe};
auto const hash_probe = row_hash.device_hasher(probe_nulls);
auto const empty_key_sentinel = hash_table.get_empty_key_sentinel();
auto const iter = cudf::detail::make_counting_transform_iterator(
0, make_pair_function{hash_probe, empty_key_sentinel});
cudf::size_type const probe_table_num_rows = probe_table.num_rows();
auto const out1_zip_begin = thrust::make_zip_iterator(
thrust::make_tuple(thrust::make_discard_iterator(), left_indices->begin()));
auto const out2_zip_begin = thrust::make_zip_iterator(
thrust::make_tuple(thrust::make_discard_iterator(), right_indices->begin()));
auto const row_comparator =
cudf::experimental::row::equality::two_table_comparator{preprocessed_probe, preprocessed_build};
auto const comparator_helper = [&](auto device_comparator) {
pair_equality equality{device_comparator};
hash_table.pair_retrieve_outer(
iter, iter + probe_table_num_rows, out1_zip_begin, out2_zip_begin, equality, stream.value());
};
if (cudf::detail::has_nested_columns(probe_table)) {
auto const device_comparator = row_comparator.equal_to<true>(probe_nulls, compare_nulls);
comparator_helper(device_comparator);
} else {
auto const device_comparator = row_comparator.equal_to<false>(probe_nulls, compare_nulls);
comparator_helper(device_comparator);
}
// Release intermediate memory allocation
left_indices->resize(0, stream);
auto const left_table_row_count = probe_table.num_rows();
auto const right_table_row_count = build_table.num_rows();
std::size_t left_join_complement_size;
// If left table is empty then all rows of the right table should be represented in the joined
// indices.
if (left_table_row_count == 0) {
left_join_complement_size = right_table_row_count;
} else {
// Assume all the indices in invalid_index_map are invalid
auto invalid_index_map =
std::make_unique<rmm::device_uvector<size_type>>(right_table_row_count, stream);
thrust::uninitialized_fill(
rmm::exec_policy(stream), invalid_index_map->begin(), invalid_index_map->end(), int32_t{1});
// Functor to check for index validity since left joins can create invalid indices
valid_range<size_type> valid(0, right_table_row_count);
// invalid_index_map[index_ptr[i]] = 0 for i = 0 to right_table_row_count
// Thus specifying that those locations are valid
thrust::scatter_if(rmm::exec_policy(stream),
thrust::make_constant_iterator(0),
thrust::make_constant_iterator(0) + right_indices->size(),
right_indices->begin(), // Index locations
right_indices->begin(), // Stencil - Check if index location is valid
invalid_index_map->begin(), // Output indices
valid); // Stencil Predicate
// Create list of indices that have been marked as invalid
left_join_complement_size = thrust::count_if(rmm::exec_policy(stream),
invalid_index_map->begin(),
invalid_index_map->end(),
thrust::identity());
}
return join_size + left_join_complement_size;
}
} // namespace
template <typename Hasher>
hash_join<Hasher>::hash_join(cudf::table_view const& build,
bool has_nulls,
cudf::null_equality compare_nulls,
rmm::cuda_stream_view stream)
: _has_nulls(has_nulls),
_is_empty{build.num_rows() == 0},
_nulls_equal{compare_nulls},
_hash_table{compute_hash_table_size(build.num_rows()),
cuco::empty_key{std::numeric_limits<hash_value_type>::max()},
cuco::empty_value{cudf::detail::JoinNoneValue},
stream.value(),
detail::hash_table_allocator_type{default_allocator<char>{}, stream}},
_build{build},
_preprocessed_build{
cudf::experimental::row::equality::preprocessed_table::create(_build, stream)}
{
CUDF_FUNC_RANGE();
CUDF_EXPECTS(0 != build.num_columns(), "Hash join build table is empty");
if (_is_empty) { return; }
auto const row_bitmask =
cudf::detail::bitmask_and(build, stream, rmm::mr::get_current_device_resource()).first;
cudf::detail::build_join_hash_table(_build,
_preprocessed_build,
_hash_table,
_has_nulls,
_nulls_equal,
reinterpret_cast<bitmask_type const*>(row_bitmask.data()),
stream);
}
template <typename Hasher>
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
hash_join<Hasher>::inner_join(cudf::table_view const& probe,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
CUDF_FUNC_RANGE();
return compute_hash_join(probe, cudf::detail::join_kind::INNER_JOIN, output_size, stream, mr);
}
template <typename Hasher>
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
hash_join<Hasher>::left_join(cudf::table_view const& probe,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
CUDF_FUNC_RANGE();
return compute_hash_join(probe, cudf::detail::join_kind::LEFT_JOIN, output_size, stream, mr);
}
template <typename Hasher>
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
hash_join<Hasher>::full_join(cudf::table_view const& probe,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
CUDF_FUNC_RANGE();
return compute_hash_join(probe, cudf::detail::join_kind::FULL_JOIN, output_size, stream, mr);
}
template <typename Hasher>
std::size_t hash_join<Hasher>::inner_join_size(cudf::table_view const& probe,
rmm::cuda_stream_view stream) const
{
CUDF_FUNC_RANGE();
// Return directly if build table is empty
if (_is_empty) { return 0; }
CUDF_EXPECTS(_has_nulls || !cudf::has_nested_nulls(probe),
"Probe table has nulls while build table was not hashed with null check.");
auto const preprocessed_probe =
cudf::experimental::row::equality::preprocessed_table::create(probe, stream);
return cudf::detail::compute_join_output_size(_build,
probe,
_preprocessed_build,
preprocessed_probe,
_hash_table,
cudf::detail::join_kind::INNER_JOIN,
_has_nulls,
_nulls_equal,
stream);
}
template <typename Hasher>
std::size_t hash_join<Hasher>::left_join_size(cudf::table_view const& probe,
rmm::cuda_stream_view stream) const
{
CUDF_FUNC_RANGE();
// Trivial left join case - exit early
if (_is_empty) { return probe.num_rows(); }
CUDF_EXPECTS(_has_nulls || !cudf::has_nested_nulls(probe),
"Probe table has nulls while build table was not hashed with null check.");
auto const preprocessed_probe =
cudf::experimental::row::equality::preprocessed_table::create(probe, stream);
return cudf::detail::compute_join_output_size(_build,
probe,
_preprocessed_build,
preprocessed_probe,
_hash_table,
cudf::detail::join_kind::LEFT_JOIN,
_has_nulls,
_nulls_equal,
stream);
}
template <typename Hasher>
std::size_t hash_join<Hasher>::full_join_size(cudf::table_view const& probe,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
CUDF_FUNC_RANGE();
// Trivial left join case - exit early
if (_is_empty) { return probe.num_rows(); }
CUDF_EXPECTS(_has_nulls || !cudf::has_nested_nulls(probe),
"Probe table has nulls while build table was not hashed with null check.");
auto const preprocessed_probe =
cudf::experimental::row::equality::preprocessed_table::create(probe, stream);
return cudf::detail::get_full_join_size(_build,
probe,
_preprocessed_build,
preprocessed_probe,
_hash_table,
_has_nulls,
_nulls_equal,
stream,
mr);
}
template <typename Hasher>
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
hash_join<Hasher>::probe_join_indices(cudf::table_view const& probe_table,
cudf::detail::join_kind join,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
// Trivial left join case - exit early
if (_is_empty and join != cudf::detail::join_kind::INNER_JOIN) {
return get_trivial_left_join_indices(probe_table, stream, mr);
}
CUDF_EXPECTS(!_is_empty, "Hash table of hash join is null.");
CUDF_EXPECTS(_has_nulls || !cudf::has_nested_nulls(probe_table),
"Probe table has nulls while build table was not hashed with null check.");
auto const preprocessed_probe =
cudf::experimental::row::equality::preprocessed_table::create(probe_table, stream);
auto join_indices = cudf::detail::probe_join_hash_table(_build,
probe_table,
_preprocessed_build,
preprocessed_probe,
_hash_table,
join,
_has_nulls,
_nulls_equal,
output_size,
stream,
mr);
if (join == cudf::detail::join_kind::FULL_JOIN) {
auto complement_indices = detail::get_left_join_indices_complement(
join_indices.second, probe_table.num_rows(), _build.num_rows(), stream, mr);
join_indices = detail::concatenate_vector_pairs(join_indices, complement_indices, stream);
}
return join_indices;
}
template <typename Hasher>
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
hash_join<Hasher>::compute_hash_join(cudf::table_view const& probe,
cudf::detail::join_kind join,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
CUDF_EXPECTS(0 != probe.num_columns(), "Hash join probe table is empty");
CUDF_EXPECTS(_build.num_columns() == probe.num_columns(),
"Mismatch in number of columns to be joined on");
CUDF_EXPECTS(_has_nulls || !cudf::has_nested_nulls(probe),
"Probe table has nulls while build table was not hashed with null check.");
if (is_trivial_join(probe, _build, join)) {
return std::pair(std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr),
std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr));
}
CUDF_EXPECTS(std::equal(std::cbegin(_build),
std::cend(_build),
std::cbegin(probe),
std::cend(probe),
[](auto const& b, auto const& p) { return b.type() == p.type(); }),
"Mismatch in joining column data types");
return probe_join_indices(probe, join, output_size, stream, mr);
}
} // namespace detail
hash_join::~hash_join() = default;
hash_join::hash_join(cudf::table_view const& build,
null_equality compare_nulls,
rmm::cuda_stream_view stream)
// If we cannot know beforehand about null existence then let's assume that there are nulls.
: hash_join(build, nullable_join::YES, compare_nulls, stream)
{
}
hash_join::hash_join(cudf::table_view const& build,
nullable_join has_nulls,
null_equality compare_nulls,
rmm::cuda_stream_view stream)
: _impl{std::make_unique<impl_type const>(
build, has_nulls == nullable_join::YES, compare_nulls, stream)}
{
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
hash_join::inner_join(cudf::table_view const& probe,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
return _impl->inner_join(probe, output_size, stream, mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
hash_join::left_join(cudf::table_view const& probe,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
return _impl->left_join(probe, output_size, stream, mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
hash_join::full_join(cudf::table_view const& probe,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
return _impl->full_join(probe, output_size, stream, mr);
}
std::size_t hash_join::inner_join_size(cudf::table_view const& probe,
rmm::cuda_stream_view stream) const
{
return _impl->inner_join_size(probe, stream);
}
std::size_t hash_join::left_join_size(cudf::table_view const& probe,
rmm::cuda_stream_view stream) const
{
return _impl->left_join_size(probe, stream);
}
std::size_t hash_join::full_join_size(cudf::table_view const& probe,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
return _impl->full_join_size(probe, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/conditional_join.hpp
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "join_common_utils.hpp"
#include <cudf/ast/expressions.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
#include <optional>
namespace cudf {
namespace detail {
/**
* @brief Computes the join operation between two tables and returns the
* output indices of left and right table as a combined table
*
* @param left Table of left columns to join
* @param right Table of right columns to join
* tables have been flipped, meaning the output indices should also be flipped
* @param JoinKind The type of join to be performed
* @param stream CUDA stream used for device memory operations and kernel launches
*
* @return Join output indices vector pair
*/
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
conditional_join(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
join_kind JoinKind,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
/**
* @brief Computes the size of a join operation between two tables without
* materializing the result and returns the total size value.
*
* @param left Table of left columns to join
* @param right Table of right columns to join
* tables have been flipped, meaning the output indices should also be flipped
* @param JoinKind The type of join to be performed
* @param stream CUDA stream used for device memory operations and kernel launches
*
* @return Join output indices vector pair
*/
std::size_t compute_conditional_join_output_size(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
join_kind JoinKind,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_kernels.cuh
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <join/join_common_utils.hpp>
#include <join/mixed_join_common_utils.cuh>
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/span.hpp>
namespace cudf {
namespace detail {
/**
* @brief Computes the output size of joining the left table to the right table.
*
* This method probes the hash table with each row in the probe table using a
* custom equality comparator that also checks that the conditional expression
* evaluates to true between the left/right tables when a match is found
* between probe and build rows.
*
* @tparam block_size The number of threads per block for this kernel
* @tparam has_nulls Whether or not the inputs may contain nulls.
*
* @param[in] left_table The left table
* @param[in] right_table The right table
* @param[in] probe The table with which to probe the hash table for matches.
* @param[in] build The table with which the hash table was built.
* @param[in] hash_probe The hasher used for the probe table.
* @param[in] equality_probe The equality comparator used when probing the hash table.
* @param[in] join_type The type of join to be performed
* @param[in] hash_table_view The hash table built from `build`.
* @param[in] device_expression_data Container of device data required to evaluate the desired
* expression.
* @param[in] swap_tables If true, the kernel was launched with one thread per right row and
* the kernel needs to internally loop over left rows. Otherwise, loop over right rows.
* @param[out] output_size The resulting output size
* @param[out] matches_per_row The number of matches in one pair of
* equality/conditional tables for each row in the other pair of tables. If
* swap_tables is true, matches_per_row corresponds to the right_table,
* otherwise it corresponds to the left_table. Note that corresponding swap of
* left/right tables to determine which is the build table and which is the
* probe table has already happened on the host.
*/
template <int block_size, bool has_nulls>
__global__ void compute_mixed_join_output_size(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::mixed_multimap_type::device_view hash_table_view,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size,
cudf::device_span<cudf::size_type> matches_per_row);
/**
* @brief Performs a join using the combination of a hash lookup to identify
* equal rows between one pair of tables and the evaluation of an expression
* containing an arbitrary expression.
*
* This method probes the hash table with each row in the probe table using a
* custom equality comparator that also checks that the conditional expression
* evaluates to true between the left/right tables when a match is found
* between probe and build rows.
*
* @tparam block_size The number of threads per block for this kernel
* @tparam has_nulls Whether or not the inputs may contain nulls.
*
* @param[in] left_table The left table
* @param[in] right_table The right table
* @param[in] probe The table with which to probe the hash table for matches.
* @param[in] build The table with which the hash table was built.
* @param[in] hash_probe The hasher used for the probe table.
* @param[in] equality_probe The equality comparator used when probing the hash table.
* @param[in] join_type The type of join to be performed
* @param[in] hash_table_view The hash table built from `build`.
* @param[out] join_output_l The left result of the join operation
* @param[out] join_output_r The right result of the join operation
* @param[in] device_expression_data Container of device data required to evaluate the desired
* expression.
* @param[in] join_result_offsets The starting indices in join_output[l|r]
* where the matches for each row begin. Equivalent to a prefix sum of
* matches_per_row.
* @param[in] swap_tables If true, the kernel was launched with one thread per right row and
* the kernel needs to internally loop over left rows. Otherwise, loop over right rows.
*/
template <cudf::size_type block_size, bool has_nulls>
__global__ void mixed_join(table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::mixed_multimap_type::device_view hash_table_view,
size_type* join_output_l,
size_type* join_output_r,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const* join_result_offsets,
bool const swap_tables);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/conditional_join_kernels.cuh
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <join/join_common_utils.cuh>
#include <join/join_common_utils.hpp>
#include <cudf/ast/detail/expression_evaluator.cuh>
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cub/cub.cuh>
namespace cudf {
namespace detail {
/**
* @brief Computes the output size of joining the left table to the right table.
*
* This method uses a nested loop to iterate over the left and right tables and count the number of
* matches according to a boolean expression.
*
* @tparam block_size The number of threads per block for this kernel
* @tparam has_nulls Whether or not the inputs may contain nulls.
*
* @param[in] left_table The left table
* @param[in] right_table The right table
* @param[in] join_type The type of join to be performed
* @param[in] device_expression_data Container of device data required to evaluate the desired
* expression.
* @param[in] swap_tables If true, the kernel was launched with one thread per right row and
* the kernel needs to internally loop over left rows. Otherwise, loop over right rows.
* @param[out] output_size The resulting output size
*/
template <int block_size, bool has_nulls>
__global__ void compute_conditional_join_output_size(
table_device_view left_table,
table_device_view right_table,
join_kind join_type,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size)
{
// The (required) extern storage of the shared memory array leads to
// conflicting declarations between different templates. The easiest
// workaround is to declare an arbitrary (here char) array type then cast it
// after the fact to the appropriate type.
extern __shared__ char raw_intermediate_storage[];
cudf::ast::detail::IntermediateDataType<has_nulls>* intermediate_storage =
reinterpret_cast<cudf::ast::detail::IntermediateDataType<has_nulls>*>(raw_intermediate_storage);
auto thread_intermediate_storage =
&intermediate_storage[threadIdx.x * device_expression_data.num_intermediates];
std::size_t thread_counter{0};
auto const start_idx = cudf::detail::grid_1d::global_thread_id();
auto const stride = cudf::detail::grid_1d::grid_stride();
cudf::thread_index_type const left_num_rows = left_table.num_rows();
cudf::thread_index_type const right_num_rows = right_table.num_rows();
auto const outer_num_rows = (swap_tables ? right_num_rows : left_num_rows);
auto const inner_num_rows = (swap_tables ? left_num_rows : right_num_rows);
auto evaluator = cudf::ast::detail::expression_evaluator<has_nulls>(
left_table, right_table, device_expression_data);
for (cudf::thread_index_type outer_row_index = start_idx; outer_row_index < outer_num_rows;
outer_row_index += stride) {
bool found_match = false;
for (cudf::thread_index_type inner_row_index = 0; inner_row_index < inner_num_rows;
++inner_row_index) {
auto output_dest = cudf::ast::detail::value_expression_result<bool, has_nulls>();
cudf::size_type const left_row_index = swap_tables ? inner_row_index : outer_row_index;
cudf::size_type const right_row_index = swap_tables ? outer_row_index : inner_row_index;
evaluator.evaluate(
output_dest, left_row_index, right_row_index, 0, thread_intermediate_storage);
if (output_dest.is_valid() && output_dest.value()) {
if ((join_type != join_kind::LEFT_ANTI_JOIN) &&
!(join_type == join_kind::LEFT_SEMI_JOIN && found_match)) {
++thread_counter;
}
found_match = true;
}
}
if ((join_type == join_kind::LEFT_JOIN || join_type == join_kind::LEFT_ANTI_JOIN ||
join_type == join_kind::FULL_JOIN) &&
(!found_match)) {
++thread_counter;
}
}
using BlockReduce = cub::BlockReduce<cudf::size_type, block_size>;
__shared__ typename BlockReduce::TempStorage temp_storage;
std::size_t block_counter = BlockReduce(temp_storage).Sum(thread_counter);
// Add block counter to global counter
if (threadIdx.x == 0) {
cuda::atomic_ref<std::size_t, cuda::thread_scope_device> ref{*output_size};
ref.fetch_add(block_counter, cuda::std::memory_order_relaxed);
}
}
/**
* @brief Performs a join conditioned on a predicate to find all matching rows
* between the left and right tables and generate the output for the desired
* Join operation.
*
* @tparam block_size The number of threads per block for this kernel
* @tparam output_cache_size The side of the shared memory buffer to cache join
* output results
* @tparam has_nulls Whether or not the inputs may contain nulls.
*
* @param[in] left_table The left table
* @param[in] right_table The right table
* @param[in] join_type The type of join to be performed
* @param[out] join_output_l The left result of the join operation
* @param[out] join_output_r The right result of the join operation
* @param[in,out] current_idx A global counter used by threads to coordinate
* writes to the global output
* @param device_expression_data Container of device data required to evaluate the desired
* expression.
* @param[in] max_size The maximum size of the output
* @param[in] swap_tables If true, the kernel was launched with one thread per right row and
* the kernel needs to internally loop over left rows. Otherwise, loop over right rows.
*/
template <cudf::size_type block_size, cudf::size_type output_cache_size, bool has_nulls>
__global__ void conditional_join(table_device_view left_table,
table_device_view right_table,
join_kind join_type,
cudf::size_type* join_output_l,
cudf::size_type* join_output_r,
cudf::size_type* current_idx,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const max_size,
bool const swap_tables)
{
constexpr int num_warps = block_size / detail::warp_size;
__shared__ cudf::size_type current_idx_shared[num_warps];
__shared__ cudf::size_type join_shared_l[num_warps][output_cache_size];
__shared__ cudf::size_type join_shared_r[num_warps][output_cache_size];
// Normally the casting of a shared memory array is used to create multiple
// arrays of different types from the shared memory buffer, but here it is
// used to circumvent conflicts between arrays of different types between
// different template instantiations due to the extern specifier.
extern __shared__ char raw_intermediate_storage[];
cudf::ast::detail::IntermediateDataType<has_nulls>* intermediate_storage =
reinterpret_cast<cudf::ast::detail::IntermediateDataType<has_nulls>*>(raw_intermediate_storage);
auto thread_intermediate_storage =
&intermediate_storage[threadIdx.x * device_expression_data.num_intermediates];
int const warp_id = threadIdx.x / detail::warp_size;
int const lane_id = threadIdx.x % detail::warp_size;
cudf::thread_index_type const left_num_rows = left_table.num_rows();
cudf::thread_index_type const right_num_rows = right_table.num_rows();
cudf::thread_index_type const outer_num_rows = (swap_tables ? right_num_rows : left_num_rows);
cudf::thread_index_type const inner_num_rows = (swap_tables ? left_num_rows : right_num_rows);
if (0 == lane_id) { current_idx_shared[warp_id] = 0; }
__syncwarp();
auto outer_row_index = cudf::detail::grid_1d::global_thread_id();
unsigned int const activemask = __ballot_sync(0xffff'ffffu, outer_row_index < outer_num_rows);
auto evaluator = cudf::ast::detail::expression_evaluator<has_nulls>(
left_table, right_table, device_expression_data);
if (outer_row_index < outer_num_rows) {
bool found_match = false;
for (thread_index_type inner_row_index(0); inner_row_index < inner_num_rows;
++inner_row_index) {
auto output_dest = cudf::ast::detail::value_expression_result<bool, has_nulls>();
auto const left_row_index = swap_tables ? inner_row_index : outer_row_index;
auto const right_row_index = swap_tables ? outer_row_index : inner_row_index;
evaluator.evaluate(
output_dest, left_row_index, right_row_index, 0, thread_intermediate_storage);
if (output_dest.is_valid() && output_dest.value()) {
// If the rows are equal, then we have found a true match
// In the case of left anti joins we only add indices from left after
// the loop if we have found _no_ matches from the right.
// In the case of left semi joins we only add the first match (note
// that the current logic relies on the fact that we process all right
// table rows for a single left table row on a single thread so that no
// synchronization of found_match is required).
if ((join_type != join_kind::LEFT_ANTI_JOIN) &&
!(join_type == join_kind::LEFT_SEMI_JOIN && found_match)) {
add_pair_to_cache(left_row_index,
right_row_index,
current_idx_shared,
warp_id,
join_shared_l[warp_id],
join_shared_r[warp_id]);
}
found_match = true;
}
__syncwarp(activemask);
// flush output cache if next iteration does not fit
auto const do_flush = current_idx_shared[warp_id] + detail::warp_size >= output_cache_size;
auto const flush_mask = __ballot_sync(activemask, do_flush);
if (do_flush) {
flush_output_cache<num_warps, output_cache_size>(flush_mask,
max_size,
warp_id,
lane_id,
current_idx,
current_idx_shared,
join_shared_l,
join_shared_r,
join_output_l,
join_output_r);
__syncwarp(flush_mask);
if (0 == lane_id) { current_idx_shared[warp_id] = 0; }
}
__syncwarp(activemask);
}
// Left, left anti, and full joins all require saving left columns that
// aren't present in the right.
if ((join_type == join_kind::LEFT_JOIN || join_type == join_kind::LEFT_ANTI_JOIN ||
join_type == join_kind::FULL_JOIN) &&
(!found_match)) {
// TODO: This code assumes that swap_tables is false for all join
// kinds aside from inner joins. Once the code is generalized to handle
// other joins we'll want to switch the variable in the line below back
// to the left_row_index, but for now we can assume that they are
// equivalent inside this conditional.
add_pair_to_cache(outer_row_index,
static_cast<cudf::size_type>(JoinNoneValue),
current_idx_shared,
warp_id,
join_shared_l[warp_id],
join_shared_r[warp_id]);
}
__syncwarp(activemask);
// final flush of output cache
auto const do_flush = current_idx_shared[warp_id] > 0;
auto const flush_mask = __ballot_sync(activemask, do_flush);
if (do_flush) {
flush_output_cache<num_warps, output_cache_size>(flush_mask,
max_size,
warp_id,
lane_id,
current_idx,
current_idx_shared,
join_shared_l,
join_shared_r,
join_output_l,
join_output_r);
}
}
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/cross_join.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/repeat.hpp>
#include <cudf/detail/reshape.hpp>
#include <cudf/filling.hpp>
#include <cudf/join.hpp>
#include <cudf/reshape.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace detail {
/**
* @copydoc cudf::cross_join
*
* @param stream CUDA stream used for device memory operations and kernel launches
*/
std::unique_ptr<cudf::table> cross_join(cudf::table_view const& left,
cudf::table_view const& right,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(0 != left.num_columns(), "Left table is empty");
CUDF_EXPECTS(0 != right.num_columns(), "Right table is empty");
// If left or right table has no rows, return an empty table with all columns
if ((0 == left.num_rows()) || (0 == right.num_rows())) {
auto empty_left_columns = empty_like(left)->release();
auto empty_right_columns = empty_like(right)->release();
std::move(empty_right_columns.begin(),
empty_right_columns.end(),
std::back_inserter(empty_left_columns));
return std::make_unique<table>(std::move(empty_left_columns));
}
// Repeat left table
auto left_repeated = detail::repeat(left, right.num_rows(), stream, mr);
// Tile right table
auto right_tiled = detail::tile(right, left.num_rows(), stream, mr);
// Concatenate all repeated/tiled columns into one table
auto left_repeated_columns = left_repeated->release();
auto right_tiled_columns = right_tiled->release();
std::move(right_tiled_columns.begin(),
right_tiled_columns.end(),
std::back_inserter(left_repeated_columns));
return std::make_unique<table>(std::move(left_repeated_columns));
}
} // namespace detail
std::unique_ptr<cudf::table> cross_join(cudf::table_view const& left,
cudf::table_view const& right,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::cross_join(left, right, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/conditional_join.cu
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/ast/expressions.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/join.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <join/conditional_join.hpp>
#include <join/conditional_join_kernels.cuh>
#include <join/join_common_utils.cuh>
#include <join/join_common_utils.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <optional>
namespace cudf {
namespace detail {
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
conditional_join(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
join_kind join_type,
std::optional<std::size_t> output_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// We can immediately filter out cases where the right table is empty. In
// some cases, we return all the rows of the left table with a corresponding
// null index for the right table; in others, we return an empty output.
auto right_num_rows{right.num_rows()};
auto left_num_rows{left.num_rows()};
if (right_num_rows == 0) {
switch (join_type) {
// Left, left anti, and full all return all the row indices from left
// with a corresponding NULL from the right.
case join_kind::LEFT_JOIN:
case join_kind::LEFT_ANTI_JOIN:
case join_kind::FULL_JOIN:
return get_trivial_left_join_indices(left, stream, rmm::mr::get_current_device_resource());
// Inner and left semi joins return empty output because no matches can exist.
case join_kind::INNER_JOIN:
case join_kind::LEFT_SEMI_JOIN:
return std::pair(std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr),
std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr));
default: CUDF_FAIL("Invalid join kind."); break;
}
} else if (left_num_rows == 0) {
switch (join_type) {
// Left, left anti, left semi, and inner joins all return empty sets.
case join_kind::LEFT_JOIN:
case join_kind::LEFT_ANTI_JOIN:
case join_kind::INNER_JOIN:
case join_kind::LEFT_SEMI_JOIN:
return std::pair(std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr),
std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr));
// Full joins need to return the trivial complement.
case join_kind::FULL_JOIN: {
auto ret_flipped =
get_trivial_left_join_indices(right, stream, rmm::mr::get_current_device_resource());
return std::pair(std::move(ret_flipped.second), std::move(ret_flipped.first));
}
default: CUDF_FAIL("Invalid join kind."); break;
}
}
// If evaluating the expression may produce null outputs we create a nullable
// output column and follow the null-supporting expression evaluation code
// path.
auto const has_nulls = binary_predicate.may_evaluate_null(left, right, stream);
auto const parser =
ast::detail::expression_parser{binary_predicate, left, right, has_nulls, stream, mr};
CUDF_EXPECTS(parser.output_type().id() == type_id::BOOL8,
"The expression must produce a boolean output.");
auto left_table = table_device_view::create(left, stream);
auto right_table = table_device_view::create(right, stream);
// For inner joins we support optimizing the join by launching one thread for
// whichever table is larger rather than always using the left table.
auto swap_tables = (join_type == join_kind::INNER_JOIN) && (right_num_rows > left_num_rows);
detail::grid_1d const config(swap_tables ? right_num_rows : left_num_rows,
DEFAULT_JOIN_BLOCK_SIZE);
auto const shmem_size_per_block = parser.shmem_per_thread * config.num_threads_per_block;
join_kind const kernel_join_type =
join_type == join_kind::FULL_JOIN ? join_kind::LEFT_JOIN : join_type;
// If the join size was not provided as an input, compute it here.
std::size_t join_size;
if (output_size.has_value()) {
join_size = *output_size;
} else {
// Allocate storage for the counter used to get the size of the join output
rmm::device_scalar<std::size_t> size(0, stream, mr);
if (has_nulls) {
compute_conditional_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_table,
*right_table,
kernel_join_type,
parser.device_expression_data,
swap_tables,
size.data());
} else {
compute_conditional_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_table,
*right_table,
kernel_join_type,
parser.device_expression_data,
swap_tables,
size.data());
}
join_size = size.value(stream);
}
// The initial early exit clauses guarantee that we will not reach this point
// unless both the left and right tables are non-empty. Under that
// constraint, neither left nor full joins can return an empty result since
// at minimum we are guaranteed null matches for all non-matching rows. In
// all other cases (inner, left semi, and left anti joins) if we reach this
// point we can safely return an empty result.
if (join_size == 0) {
return std::pair(std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr),
std::make_unique<rmm::device_uvector<size_type>>(0, stream, mr));
}
rmm::device_scalar<size_type> write_index(0, stream);
auto left_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto right_indices = std::make_unique<rmm::device_uvector<size_type>>(join_size, stream, mr);
auto const& join_output_l = left_indices->data();
auto const& join_output_r = right_indices->data();
if (has_nulls) {
conditional_join<DEFAULT_JOIN_BLOCK_SIZE, DEFAULT_JOIN_CACHE_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_table,
*right_table,
kernel_join_type,
join_output_l,
join_output_r,
write_index.data(),
parser.device_expression_data,
join_size,
swap_tables);
} else {
conditional_join<DEFAULT_JOIN_BLOCK_SIZE, DEFAULT_JOIN_CACHE_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_table,
*right_table,
kernel_join_type,
join_output_l,
join_output_r,
write_index.data(),
parser.device_expression_data,
join_size,
swap_tables);
}
auto join_indices = std::pair(std::move(left_indices), std::move(right_indices));
// For full joins, get the indices in the right table that were not joined to
// by any row in the left table.
if (join_type == join_kind::FULL_JOIN) {
auto complement_indices = detail::get_left_join_indices_complement(
join_indices.second, left_num_rows, right_num_rows, stream, mr);
join_indices = detail::concatenate_vector_pairs(join_indices, complement_indices, stream);
}
return join_indices;
}
std::size_t compute_conditional_join_output_size(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
join_kind join_type,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Until we add logic to handle the number of non-matches in the right table,
// full joins are not supported in this function. Note that this does not
// prevent actually performing full joins since we do that by calculating the
// left join and then concatenating the complementary right indices.
CUDF_EXPECTS(join_type != join_kind::FULL_JOIN,
"Size estimation is not available for full joins.");
// We can immediately filter out cases where one table is empty. In
// some cases, we return all the rows of the other table with a corresponding
// null index for the empty table; in others, we return an empty output.
auto right_num_rows{right.num_rows()};
auto left_num_rows{left.num_rows()};
if (right_num_rows == 0) {
switch (join_type) {
// Left, left anti, and full all return all the row indices from left
// with a corresponding NULL from the right.
case join_kind::LEFT_JOIN:
case join_kind::LEFT_ANTI_JOIN:
case join_kind::FULL_JOIN: return left_num_rows;
// Inner and left semi joins return empty output because no matches can exist.
case join_kind::INNER_JOIN:
case join_kind::LEFT_SEMI_JOIN: return 0;
default: CUDF_FAIL("Invalid join kind."); break;
}
} else if (left_num_rows == 0) {
switch (join_type) {
// Left, left anti, left semi, and inner joins all return empty sets.
case join_kind::LEFT_JOIN:
case join_kind::LEFT_ANTI_JOIN:
case join_kind::INNER_JOIN:
case join_kind::LEFT_SEMI_JOIN: return 0;
// Full joins need to return the trivial complement.
case join_kind::FULL_JOIN: return right_num_rows;
default: CUDF_FAIL("Invalid join kind."); break;
}
}
// Prepare output column. Whether or not the output column is nullable is
// determined by whether any of the columns in the input table are nullable.
// If none of the input columns actually contain nulls, we can still use the
// non-nullable version of the expression evaluation code path for
// performance, so we capture that information as well.
auto const has_nulls = binary_predicate.may_evaluate_null(left, right, stream);
auto const parser =
ast::detail::expression_parser{binary_predicate, left, right, has_nulls, stream, mr};
CUDF_EXPECTS(parser.output_type().id() == type_id::BOOL8,
"The expression must produce a boolean output.");
auto left_table = table_device_view::create(left, stream);
auto right_table = table_device_view::create(right, stream);
// For inner joins we support optimizing the join by launching one thread for
// whichever table is larger rather than always using the left table.
auto swap_tables = (join_type == join_kind::INNER_JOIN) && (right_num_rows > left_num_rows);
detail::grid_1d const config(swap_tables ? right_num_rows : left_num_rows,
DEFAULT_JOIN_BLOCK_SIZE);
auto const shmem_size_per_block = parser.shmem_per_thread * config.num_threads_per_block;
// Allocate storage for the counter used to get the size of the join output
rmm::device_scalar<std::size_t> size(0, stream, mr);
// Determine number of output rows without actually building the output to simply
// find what the size of the output will be.
if (has_nulls) {
compute_conditional_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, true>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_table,
*right_table,
join_type,
parser.device_expression_data,
swap_tables,
size.data());
} else {
compute_conditional_join_output_size<DEFAULT_JOIN_BLOCK_SIZE, false>
<<<config.num_blocks, config.num_threads_per_block, shmem_size_per_block, stream.value()>>>(
*left_table,
*right_table,
join_type,
parser.device_expression_data,
swap_tables,
size.data());
}
return size.value(stream);
}
} // namespace detail
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
conditional_inner_join(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
std::optional<std::size_t> output_size,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::conditional_join(left,
right,
binary_predicate,
detail::join_kind::INNER_JOIN,
output_size,
cudf::get_default_stream(),
mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
conditional_left_join(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
std::optional<std::size_t> output_size,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::conditional_join(left,
right,
binary_predicate,
detail::join_kind::LEFT_JOIN,
output_size,
cudf::get_default_stream(),
mr);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
conditional_full_join(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::conditional_join(left,
right,
binary_predicate,
detail::join_kind::FULL_JOIN,
{},
cudf::get_default_stream(),
mr);
}
std::unique_ptr<rmm::device_uvector<size_type>> conditional_left_semi_join(
table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
std::optional<std::size_t> output_size,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return std::move(detail::conditional_join(left,
right,
binary_predicate,
detail::join_kind::LEFT_SEMI_JOIN,
output_size,
cudf::get_default_stream(),
mr)
.first);
}
std::unique_ptr<rmm::device_uvector<size_type>> conditional_left_anti_join(
table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
std::optional<std::size_t> output_size,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return std::move(detail::conditional_join(left,
right,
binary_predicate,
detail::join_kind::LEFT_ANTI_JOIN,
output_size,
cudf::get_default_stream(),
mr)
.first);
}
std::size_t conditional_inner_join_size(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::compute_conditional_join_output_size(
left, right, binary_predicate, detail::join_kind::INNER_JOIN, cudf::get_default_stream(), mr);
}
std::size_t conditional_left_join_size(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::compute_conditional_join_output_size(
left, right, binary_predicate, detail::join_kind::LEFT_JOIN, cudf::get_default_stream(), mr);
}
std::size_t conditional_left_semi_join_size(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return std::move(detail::compute_conditional_join_output_size(left,
right,
binary_predicate,
detail::join_kind::LEFT_SEMI_JOIN,
cudf::get_default_stream(),
mr));
}
std::size_t conditional_left_anti_join_size(table_view const& left,
table_view const& right,
ast::expression const& binary_predicate,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return std::move(detail::compute_conditional_join_output_size(left,
right,
binary_predicate,
detail::join_kind::LEFT_ANTI_JOIN,
cudf::get_default_stream(),
mr));
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_kernels_semi.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <join/join_common_utils.cuh>
#include <join/join_common_utils.hpp>
#include <join/mixed_join_common_utils.cuh>
#include <cudf/ast/detail/expression_evaluator.cuh>
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/span.hpp>
#include <cub/cub.cuh>
namespace cudf {
namespace detail {
namespace cg = cooperative_groups;
template <cudf::size_type block_size, bool has_nulls>
__launch_bounds__(block_size) __global__
void mixed_join_semi(table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::semi_map_type::device_view hash_table_view,
size_type* join_output_l,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const* join_result_offsets,
bool const swap_tables)
{
// Normally the casting of a shared memory array is used to create multiple
// arrays of different types from the shared memory buffer, but here it is
// used to circumvent conflicts between arrays of different types between
// different template instantiations due to the extern specifier.
extern __shared__ char raw_intermediate_storage[];
cudf::ast::detail::IntermediateDataType<has_nulls>* intermediate_storage =
reinterpret_cast<cudf::ast::detail::IntermediateDataType<has_nulls>*>(raw_intermediate_storage);
auto thread_intermediate_storage =
&intermediate_storage[threadIdx.x * device_expression_data.num_intermediates];
cudf::size_type const left_num_rows = left_table.num_rows();
cudf::size_type const right_num_rows = right_table.num_rows();
auto const outer_num_rows = (swap_tables ? right_num_rows : left_num_rows);
cudf::size_type outer_row_index = threadIdx.x + blockIdx.x * block_size;
auto evaluator = cudf::ast::detail::expression_evaluator<has_nulls>(
left_table, right_table, device_expression_data);
if (outer_row_index < outer_num_rows) {
// Figure out the number of elements for this key.
auto equality = single_expression_equality<has_nulls>{
evaluator, thread_intermediate_storage, swap_tables, equality_probe};
if ((join_type == join_kind::LEFT_ANTI_JOIN) !=
(hash_table_view.contains(outer_row_index, hash_probe, equality))) {
*(join_output_l + join_result_offsets[outer_row_index]) = outer_row_index;
}
}
}
template __global__ void mixed_join_semi<DEFAULT_JOIN_BLOCK_SIZE, true>(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::semi_map_type::device_view hash_table_view,
size_type* join_output_l,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const* join_result_offsets,
bool const swap_tables);
template __global__ void mixed_join_semi<DEFAULT_JOIN_BLOCK_SIZE, false>(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::semi_map_type::device_view hash_table_view,
size_type* join_output_l,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const* join_result_offsets,
bool const swap_tables);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/join_utils.cu
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "join_common_utils.cuh"
#include <rmm/exec_policy.hpp>
#include <thrust/copy.h>
#include <thrust/functional.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/scatter.h>
#include <thrust/sequence.h>
#include <thrust/uninitialized_fill.h>
namespace cudf {
namespace detail {
bool is_trivial_join(table_view const& left, table_view const& right, join_kind join_type)
{
// If there is nothing to join, then send empty table with all columns
if (left.is_empty() || right.is_empty()) { return true; }
// If left join and the left table is empty, return immediately
if ((join_kind::LEFT_JOIN == join_type) && (0 == left.num_rows())) { return true; }
// If Inner Join and either table is empty, return immediately
if ((join_kind::INNER_JOIN == join_type) && ((0 == left.num_rows()) || (0 == right.num_rows()))) {
return true;
}
// If left semi join (contains) and right table is empty,
// return immediately
if ((join_kind::LEFT_SEMI_JOIN == join_type) && (0 == right.num_rows())) { return true; }
return false;
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
get_trivial_left_join_indices(table_view const& left,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto left_indices = std::make_unique<rmm::device_uvector<size_type>>(left.num_rows(), stream, mr);
thrust::sequence(rmm::exec_policy(stream), left_indices->begin(), left_indices->end(), 0);
auto right_indices =
std::make_unique<rmm::device_uvector<size_type>>(left.num_rows(), stream, mr);
thrust::uninitialized_fill(
rmm::exec_policy(stream), right_indices->begin(), right_indices->end(), JoinNoneValue);
return std::pair(std::move(left_indices), std::move(right_indices));
}
VectorPair concatenate_vector_pairs(VectorPair& a, VectorPair& b, rmm::cuda_stream_view stream)
{
CUDF_EXPECTS((a.first->size() == a.second->size()),
"Mismatch between sizes of vectors in vector pair");
CUDF_EXPECTS((b.first->size() == b.second->size()),
"Mismatch between sizes of vectors in vector pair");
if (a.first->is_empty()) {
return std::move(b);
} else if (b.first->is_empty()) {
return std::move(a);
}
auto original_size = a.first->size();
a.first->resize(a.first->size() + b.first->size(), stream);
a.second->resize(a.second->size() + b.second->size(), stream);
thrust::copy(
rmm::exec_policy(stream), b.first->begin(), b.first->end(), a.first->begin() + original_size);
thrust::copy(rmm::exec_policy(stream),
b.second->begin(),
b.second->end(),
a.second->begin() + original_size);
return std::move(a);
}
std::pair<std::unique_ptr<rmm::device_uvector<size_type>>,
std::unique_ptr<rmm::device_uvector<size_type>>>
get_left_join_indices_complement(std::unique_ptr<rmm::device_uvector<size_type>>& right_indices,
size_type left_table_row_count,
size_type right_table_row_count,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// Get array of indices that do not appear in right_indices
// Vector allocated for unmatched result
auto right_indices_complement =
std::make_unique<rmm::device_uvector<size_type>>(right_table_row_count, stream);
// If left table is empty in a full join call then all rows of the right table
// should be represented in the joined indices. This is an optimization since
// if left table is empty and full join is called all the elements in
// right_indices will be JoinNoneValue, i.e. -1. This if path should
// produce exactly the same result as the else path but will be faster.
if (left_table_row_count == 0) {
thrust::sequence(rmm::exec_policy(stream),
right_indices_complement->begin(),
right_indices_complement->end(),
0);
} else {
// Assume all the indices in invalid_index_map are invalid
auto invalid_index_map =
std::make_unique<rmm::device_uvector<size_type>>(right_table_row_count, stream);
thrust::uninitialized_fill(
rmm::exec_policy(stream), invalid_index_map->begin(), invalid_index_map->end(), int32_t{1});
// Functor to check for index validity since left joins can create invalid indices
valid_range<size_type> valid(0, right_table_row_count);
// invalid_index_map[index_ptr[i]] = 0 for i = 0 to right_table_row_count
// Thus specifying that those locations are valid
thrust::scatter_if(rmm::exec_policy(stream),
thrust::make_constant_iterator(0),
thrust::make_constant_iterator(0) + right_indices->size(),
right_indices->begin(), // Index locations
right_indices->begin(), // Stencil - Check if index location is valid
invalid_index_map->begin(), // Output indices
valid); // Stencil Predicate
size_type begin_counter = static_cast<size_type>(0);
size_type end_counter = static_cast<size_type>(right_table_row_count);
// Create list of indices that have been marked as invalid
size_type indices_count = thrust::copy_if(rmm::exec_policy(stream),
thrust::make_counting_iterator(begin_counter),
thrust::make_counting_iterator(end_counter),
invalid_index_map->begin(),
right_indices_complement->begin(),
thrust::identity{}) -
right_indices_complement->begin();
right_indices_complement->resize(indices_count, stream);
}
auto left_invalid_indices =
std::make_unique<rmm::device_uvector<size_type>>(right_indices_complement->size(), stream);
thrust::uninitialized_fill(rmm::exec_policy(stream),
left_invalid_indices->begin(),
left_invalid_indices->end(),
JoinNoneValue);
return std::pair(std::move(left_invalid_indices), std::move(right_indices_complement));
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_kernels_semi.cuh
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <join/join_common_utils.hpp>
#include <join/mixed_join_common_utils.cuh>
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/span.hpp>
namespace cudf {
namespace detail {
/**
* @brief Computes the output size of joining the left table to the right table for semi/anti joins.
*
* This method probes the hash table with each row in the probe table using a
* custom equality comparator that also checks that the conditional expression
* evaluates to true between the left/right tables when a match is found
* between probe and build rows.
*
* @tparam block_size The number of threads per block for this kernel
* @tparam has_nulls Whether or not the inputs may contain nulls.
*
* @param[in] left_table The left table
* @param[in] right_table The right table
* @param[in] probe The table with which to probe the hash table for matches.
* @param[in] build The table with which the hash table was built.
* @param[in] hash_probe The hasher used for the probe table.
* @param[in] equality_probe The equality comparator used when probing the hash table.
* @param[in] join_type The type of join to be performed
* @param[in] hash_table_view The hash table built from `build`.
* @param[in] device_expression_data Container of device data required to evaluate the desired
* expression.
* @param[in] swap_tables If true, the kernel was launched with one thread per right row and
* the kernel needs to internally loop over left rows. Otherwise, loop over right rows.
* @param[out] output_size The resulting output size
* @param[out] matches_per_row The number of matches in one pair of
* equality/conditional tables for each row in the other pair of tables. If
* swap_tables is true, matches_per_row corresponds to the right_table,
* otherwise it corresponds to the left_table. Note that corresponding swap of
* left/right tables to determine which is the build table and which is the
* probe table has already happened on the host.
*/
template <int block_size, bool has_nulls>
__global__ void compute_mixed_join_output_size_semi(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::semi_map_type::device_view hash_table_view,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size,
cudf::device_span<cudf::size_type> matches_per_row);
/**
* @brief Performs a semi/anti join using the combination of a hash lookup to
* identify equal rows between one pair of tables and the evaluation of an
* expression containing an arbitrary expression.
*
* This method probes the hash table with each row in the probe table using a
* custom equality comparator that also checks that the conditional expression
* evaluates to true between the left/right tables when a match is found
* between probe and build rows.
*
* @tparam block_size The number of threads per block for this kernel
* @tparam has_nulls Whether or not the inputs may contain nulls.
*
* @param[in] left_table The left table
* @param[in] right_table The right table
* @param[in] probe The table with which to probe the hash table for matches.
* @param[in] build The table with which the hash table was built.
* @param[in] hash_probe The hasher used for the probe table.
* @param[in] equality_probe The equality comparator used when probing the hash table.
* @param[in] join_type The type of join to be performed
* @param[in] hash_table_view The hash table built from `build`.
* @param[out] join_output_l The left result of the join operation
* @param[in] device_expression_data Container of device data required to evaluate the desired
* expression.
* @param[in] join_result_offsets The starting indices in join_output[l|r]
* where the matches for each row begin. Equivalent to a prefix sum of
* matches_per_row.
* @param[in] swap_tables If true, the kernel was launched with one thread per right row and
* the kernel needs to internally loop over left rows. Otherwise, loop over right rows.
*/
template <cudf::size_type block_size, bool has_nulls>
__global__ void mixed_join_semi(table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::semi_map_type::device_view hash_table_view,
size_type* join_output_l,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const* join_result_offsets,
bool const swap_tables);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_common_utils.cuh
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <join/join_common_utils.hpp>
#include <cudf/ast/detail/expression_evaluator.cuh>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/table/experimental/row_operators.cuh>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <cub/cub.cuh>
namespace cudf {
namespace detail {
using row_hash =
cudf::experimental::row::hash::device_row_hasher<cudf::hashing::detail::default_hash,
cudf::nullate::DYNAMIC>;
// // This alias is used by mixed_joins, which support only non-nested types
using row_equality = cudf::experimental::row::equality::strong_index_comparator_adapter<
cudf::experimental::row::equality::device_row_comparator<false, cudf::nullate::DYNAMIC>>;
/**
* @brief Equality comparator for use with cuco map methods that require expression evaluation.
*
* This class just defines the construction of the class and the necessary
* attributes, specifically the equality operator for the non-conditional parts
* of the operator and the evaluator used for the conditional.
*/
template <bool has_nulls>
struct expression_equality {
__device__ expression_equality(
cudf::ast::detail::expression_evaluator<has_nulls> const& evaluator,
cudf::ast::detail::IntermediateDataType<has_nulls>* thread_intermediate_storage,
bool const swap_tables,
row_equality const& equality_probe)
: evaluator{evaluator},
thread_intermediate_storage{thread_intermediate_storage},
swap_tables{swap_tables},
equality_probe{equality_probe}
{
}
cudf::ast::detail::IntermediateDataType<has_nulls>* thread_intermediate_storage;
cudf::ast::detail::expression_evaluator<has_nulls> const& evaluator;
bool const swap_tables;
row_equality const& equality_probe;
};
/**
* @brief Equality comparator for cuco::static_map queries.
*
* This equality comparator is designed for use with cuco::static_map's APIs. A
* probe hit indicates that the hashes of the keys are equal, at which point
* this comparator checks whether the keys themselves are equal (using the
* provided equality_probe) and then evaluates the conditional expression
*/
template <bool has_nulls>
struct single_expression_equality : expression_equality<has_nulls> {
using expression_equality<has_nulls>::expression_equality;
// The parameters are build/probe rather than left/right because the operator
// is called by cuco's kernels with parameters in this order (note that this
// is an implementation detail that we should eventually stop relying on by
// defining operators with suitable heterogeneous typing). Rather than
// converting to left/right semantics, we can operate directly on build/probe
// until we get to the expression evaluator, which needs to convert back to
// left/right semantics because the conditional expression need not be
// commutative.
// TODO: The input types should really be size_type.
__device__ __forceinline__ bool operator()(hash_value_type const build_row_index,
hash_value_type const probe_row_index) const noexcept
{
using cudf::experimental::row::lhs_index_type;
using cudf::experimental::row::rhs_index_type;
auto output_dest = cudf::ast::detail::value_expression_result<bool, has_nulls>();
// Two levels of checks:
// 1. The contents of the columns involved in the equality condition are equal.
// 2. The predicate evaluated on the relevant columns (already encoded in the evaluator)
// evaluates to true.
if (this->equality_probe(lhs_index_type{probe_row_index}, rhs_index_type{build_row_index})) {
auto const lrow_idx = this->swap_tables ? build_row_index : probe_row_index;
auto const rrow_idx = this->swap_tables ? probe_row_index : build_row_index;
this->evaluator.evaluate(output_dest,
static_cast<size_type>(lrow_idx),
static_cast<size_type>(rrow_idx),
0,
this->thread_intermediate_storage);
return (output_dest.is_valid() && output_dest.value());
}
return false;
}
};
/**
* @brief Equality comparator for cuco::static_multimap queries.
*
* This equality comparator is designed for use with cuco::static_multimap's
* pair* APIs, which will compare equality based on comparing (key, value)
* pairs. In the context of joins, these pairs are of the form
* (row_hash, row_id). A hash probe hit indicates that hash of a probe row's hash is
* equal to the hash of the hash of some row in the multimap, at which point we need an
* equality comparator that will check whether the contents of the rows are
* identical. This comparator does so by verifying key equality (i.e. that
* probe_row_hash == build_row_hash) and then using a row_equality_comparator
* to compare the contents of the row indices that are stored as the payload in
* the hash map.
*/
template <bool has_nulls>
struct pair_expression_equality : public expression_equality<has_nulls> {
using expression_equality<has_nulls>::expression_equality;
// The parameters are build/probe rather than left/right because the operator
// is called by cuco's kernels with parameters in this order (note that this
// is an implementation detail that we should eventually stop relying on by
// defining operators with suitable heterogeneous typing). Rather than
// converting to left/right semantics, we can operate directly on build/probe
// until we get to the expression evaluator, which needs to convert back to
// left/right semantics because the conditional expression need not be
// commutative.
__device__ __forceinline__ bool operator()(pair_type const& build_row,
pair_type const& probe_row) const noexcept
{
using cudf::experimental::row::lhs_index_type;
using cudf::experimental::row::rhs_index_type;
auto output_dest = cudf::ast::detail::value_expression_result<bool, has_nulls>();
// Three levels of checks:
// 1. Row hashes of the columns involved in the equality condition are equal.
// 2. The contents of the columns involved in the equality condition are equal.
// 3. The predicate evaluated on the relevant columns (already encoded in the evaluator)
// evaluates to true.
if ((probe_row.first == build_row.first) &&
this->equality_probe(lhs_index_type{probe_row.second}, rhs_index_type{build_row.second})) {
auto const lrow_idx = this->swap_tables ? build_row.second : probe_row.second;
auto const rrow_idx = this->swap_tables ? probe_row.second : build_row.second;
this->evaluator.evaluate(
output_dest, lrow_idx, rrow_idx, 0, this->thread_intermediate_storage);
return (output_dest.is_valid() && output_dest.value());
}
return false;
}
};
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_kernel_nulls.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mixed_join_kernel.cuh"
namespace cudf {
namespace detail {
template __global__ void mixed_join<DEFAULT_JOIN_BLOCK_SIZE, true>(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::mixed_multimap_type::device_view hash_table_view,
size_type* join_output_l,
size_type* join_output_r,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const* join_result_offsets,
bool const swap_tables);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/semi_join.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <join/join_common_utils.hpp>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/search.hpp>
#include <cudf/dictionary/detail/update_keys.hpp>
#include <cudf/join.hpp>
#include <cudf/table/table.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/copy.h>
#include <thrust/distance.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/sequence.h>
#include <thrust/transform.h>
namespace cudf {
namespace detail {
std::unique_ptr<rmm::device_uvector<cudf::size_type>> left_semi_anti_join(
join_kind const kind,
cudf::table_view const& left_keys,
cudf::table_view const& right_keys,
null_equality compare_nulls,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(0 != left_keys.num_columns(), "Left table is empty");
CUDF_EXPECTS(0 != right_keys.num_columns(), "Right table is empty");
if (is_trivial_join(left_keys, right_keys, kind)) {
return std::make_unique<rmm::device_uvector<cudf::size_type>>(0, stream, mr);
}
if ((join_kind::LEFT_ANTI_JOIN == kind) && (0 == right_keys.num_rows())) {
auto result =
std::make_unique<rmm::device_uvector<cudf::size_type>>(left_keys.num_rows(), stream, mr);
thrust::sequence(rmm::exec_policy(stream), result->begin(), result->end());
return result;
}
// Materialize a `flagged` boolean array to generate a gather map.
// Previously, the gather map was generated directly without this array but by calling to
// `map.contains` inside the `thrust::copy_if` kernel. However, that led to increasing register
// usage and reducing performance, as reported here: https://github.com/rapidsai/cudf/pull/10511.
auto const flagged = cudf::detail::contains(right_keys,
left_keys,
compare_nulls,
nan_equality::ALL_EQUAL,
stream,
rmm::mr::get_current_device_resource());
auto const left_num_rows = left_keys.num_rows();
auto gather_map =
std::make_unique<rmm::device_uvector<cudf::size_type>>(left_num_rows, stream, mr);
// gather_map_end will be the end of valid data in gather_map
auto gather_map_end =
thrust::copy_if(rmm::exec_policy(stream),
thrust::counting_iterator<size_type>(0),
thrust::counting_iterator<size_type>(left_num_rows),
gather_map->begin(),
[kind, d_flagged = flagged.begin()] __device__(size_type const idx) {
return *(d_flagged + idx) == (kind == join_kind::LEFT_SEMI_JOIN);
});
gather_map->resize(thrust::distance(gather_map->begin(), gather_map_end), stream);
return gather_map;
}
} // namespace detail
std::unique_ptr<rmm::device_uvector<cudf::size_type>> left_semi_join(
cudf::table_view const& left,
cudf::table_view const& right,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::left_semi_anti_join(
detail::join_kind::LEFT_SEMI_JOIN, left, right, compare_nulls, cudf::get_default_stream(), mr);
}
std::unique_ptr<rmm::device_uvector<cudf::size_type>> left_anti_join(
cudf::table_view const& left,
cudf::table_view const& right,
null_equality compare_nulls,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::left_semi_anti_join(
detail::join_kind::LEFT_ANTI_JOIN, left, right, compare_nulls, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_size_kernels_semi.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <join/join_common_utils.cuh>
#include <join/join_common_utils.hpp>
#include <join/mixed_join_common_utils.cuh>
#include <cudf/ast/detail/expression_evaluator.cuh>
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/span.hpp>
#include <cub/cub.cuh>
namespace cudf {
namespace detail {
namespace cg = cooperative_groups;
template <int block_size, bool has_nulls>
__launch_bounds__(block_size) __global__ void compute_mixed_join_output_size_semi(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::semi_map_type::device_view hash_table_view,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size,
cudf::device_span<cudf::size_type> matches_per_row)
{
// The (required) extern storage of the shared memory array leads to
// conflicting declarations between different templates. The easiest
// workaround is to declare an arbitrary (here char) array type then cast it
// after the fact to the appropriate type.
extern __shared__ char raw_intermediate_storage[];
cudf::ast::detail::IntermediateDataType<has_nulls>* intermediate_storage =
reinterpret_cast<cudf::ast::detail::IntermediateDataType<has_nulls>*>(raw_intermediate_storage);
auto thread_intermediate_storage =
intermediate_storage + (threadIdx.x * device_expression_data.num_intermediates);
std::size_t thread_counter{0};
cudf::size_type const start_idx = threadIdx.x + blockIdx.x * block_size;
cudf::size_type const stride = block_size * gridDim.x;
cudf::size_type const left_num_rows = left_table.num_rows();
cudf::size_type const right_num_rows = right_table.num_rows();
auto const outer_num_rows = (swap_tables ? right_num_rows : left_num_rows);
auto evaluator = cudf::ast::detail::expression_evaluator<has_nulls>(
left_table, right_table, device_expression_data);
// TODO: Address asymmetry in operator.
auto equality = single_expression_equality<has_nulls>{
evaluator, thread_intermediate_storage, swap_tables, equality_probe};
for (cudf::size_type outer_row_index = start_idx; outer_row_index < outer_num_rows;
outer_row_index += stride) {
matches_per_row[outer_row_index] =
((join_type == join_kind::LEFT_ANTI_JOIN) !=
(hash_table_view.contains(outer_row_index, hash_probe, equality)));
thread_counter += matches_per_row[outer_row_index];
}
using BlockReduce = cub::BlockReduce<cudf::size_type, block_size>;
__shared__ typename BlockReduce::TempStorage temp_storage;
std::size_t block_counter = BlockReduce(temp_storage).Sum(thread_counter);
// Add block counter to global counter
if (threadIdx.x == 0) {
cuda::atomic_ref<std::size_t, cuda::thread_scope_device> ref{*output_size};
ref.fetch_add(block_counter, cuda::std::memory_order_relaxed);
}
}
template __global__ void compute_mixed_join_output_size_semi<DEFAULT_JOIN_BLOCK_SIZE, true>(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::semi_map_type::device_view hash_table_view,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size,
cudf::device_span<cudf::size_type> matches_per_row);
template __global__ void compute_mixed_join_output_size_semi<DEFAULT_JOIN_BLOCK_SIZE, false>(
table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::semi_map_type::device_view hash_table_view,
ast::detail::expression_device_view device_expression_data,
bool const swap_tables,
std::size_t* output_size,
cudf::device_span<cudf::size_type> matches_per_row);
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/join/mixed_join_kernel.cuh
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "join_common_utils.cuh"
#include "join_common_utils.hpp"
#include "mixed_join_common_utils.cuh"
#include <cudf/ast/detail/expression_evaluator.cuh>
#include <cudf/ast/detail/expression_parser.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/span.hpp>
#include <cooperative_groups.h>
#include <cub/cub.cuh>
#include <thrust/iterator/discard_iterator.h>
namespace cudf {
namespace detail {
namespace cg = cooperative_groups;
template <cudf::size_type block_size, bool has_nulls>
__launch_bounds__(block_size) __global__
void mixed_join(table_device_view left_table,
table_device_view right_table,
table_device_view probe,
table_device_view build,
row_hash const hash_probe,
row_equality const equality_probe,
join_kind const join_type,
cudf::detail::mixed_multimap_type::device_view hash_table_view,
size_type* join_output_l,
size_type* join_output_r,
cudf::ast::detail::expression_device_view device_expression_data,
cudf::size_type const* join_result_offsets,
bool const swap_tables)
{
// Normally the casting of a shared memory array is used to create multiple
// arrays of different types from the shared memory buffer, but here it is
// used to circumvent conflicts between arrays of different types between
// different template instantiations due to the extern specifier.
extern __shared__ char raw_intermediate_storage[];
cudf::ast::detail::IntermediateDataType<has_nulls>* intermediate_storage =
reinterpret_cast<cudf::ast::detail::IntermediateDataType<has_nulls>*>(raw_intermediate_storage);
auto thread_intermediate_storage =
&intermediate_storage[threadIdx.x * device_expression_data.num_intermediates];
cudf::size_type const left_num_rows = left_table.num_rows();
cudf::size_type const right_num_rows = right_table.num_rows();
auto const outer_num_rows = (swap_tables ? right_num_rows : left_num_rows);
cudf::size_type outer_row_index = threadIdx.x + blockIdx.x * block_size;
auto evaluator = cudf::ast::detail::expression_evaluator<has_nulls>(
left_table, right_table, device_expression_data);
auto const empty_key_sentinel = hash_table_view.get_empty_key_sentinel();
make_pair_function pair_func{hash_probe, empty_key_sentinel};
if (outer_row_index < outer_num_rows) {
// Figure out the number of elements for this key.
cg::thread_block_tile<1> this_thread = cg::this_thread();
// Figure out the number of elements for this key.
auto query_pair = pair_func(outer_row_index);
auto equality = pair_expression_equality<has_nulls>{
evaluator, thread_intermediate_storage, swap_tables, equality_probe};
auto probe_key_begin = thrust::make_discard_iterator();
auto probe_value_begin = swap_tables ? join_output_r + join_result_offsets[outer_row_index]
: join_output_l + join_result_offsets[outer_row_index];
auto contained_key_begin = thrust::make_discard_iterator();
auto contained_value_begin = swap_tables ? join_output_l + join_result_offsets[outer_row_index]
: join_output_r + join_result_offsets[outer_row_index];
if (join_type == join_kind::LEFT_JOIN || join_type == join_kind::FULL_JOIN) {
hash_table_view.pair_retrieve_outer(this_thread,
query_pair,
probe_key_begin,
probe_value_begin,
contained_key_begin,
contained_value_begin,
equality);
} else {
hash_table_view.pair_retrieve(this_thread,
query_pair,
probe_key_begin,
probe_value_begin,
contained_key_begin,
contained_value_begin,
equality);
}
}
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/scalar/scalar_factories.cpp
|
/*
* Copyright (c) 2019-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/null_mask.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/utilities/error.hpp>
#include <cudf/utilities/traits.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/lists/lists_column_view.hpp>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace {
struct scalar_construction_helper {
template <typename T,
typename ScalarType = scalar_type_t<T>,
std::enable_if_t<is_fixed_width<T>() and not is_fixed_point<T>()>* = nullptr>
std::unique_ptr<scalar> operator()(rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
using Type = device_storage_type_t<T>;
auto s = new ScalarType(Type{}, false, stream, mr);
return std::unique_ptr<scalar>(s);
}
template <typename T,
typename ScalarType = scalar_type_t<T>,
std::enable_if_t<is_fixed_point<T>()>* = nullptr>
std::unique_ptr<scalar> operator()(rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
using Type = device_storage_type_t<T>;
auto s = new ScalarType(Type{}, numeric::scale_type{0}, false, stream, mr);
return std::unique_ptr<scalar>(s);
}
template <typename T, typename... Args, std::enable_if_t<not is_fixed_width<T>()>* = nullptr>
std::unique_ptr<scalar> operator()(Args... args) const
{
CUDF_FAIL("Invalid type.");
}
};
} // namespace
// Allocate storage for a single numeric element
std::unique_ptr<scalar> make_numeric_scalar(data_type type,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(is_numeric(type), "Invalid, non-numeric type.");
return type_dispatcher(type, scalar_construction_helper{}, stream, mr);
}
// Allocate storage for a single timestamp element
std::unique_ptr<scalar> make_timestamp_scalar(data_type type,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(is_timestamp(type), "Invalid, non-timestamp type.");
return type_dispatcher(type, scalar_construction_helper{}, stream, mr);
}
// Allocate storage for a single duration element
std::unique_ptr<scalar> make_duration_scalar(data_type type,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(is_duration(type), "Invalid, non-duration type.");
return type_dispatcher(type, scalar_construction_helper{}, stream, mr);
}
// Allocate storage for a single fixed width element
std::unique_ptr<scalar> make_fixed_width_scalar(data_type type,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(is_fixed_width(type), "Invalid, non-fixed-width type.");
return type_dispatcher(type, scalar_construction_helper{}, stream, mr);
}
std::unique_ptr<scalar> make_list_scalar(column_view elements,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return std::make_unique<list_scalar>(elements, true, stream, mr);
}
std::unique_ptr<scalar> make_struct_scalar(table_view const& data,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return std::make_unique<struct_scalar>(data, true, stream, mr);
}
std::unique_ptr<scalar> make_struct_scalar(host_span<column_view const> data,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return std::make_unique<struct_scalar>(data, true, stream, mr);
}
namespace {
struct default_scalar_functor {
data_type type;
template <typename T, std::enable_if_t<not is_fixed_point<T>()>* = nullptr>
std::unique_ptr<cudf::scalar> operator()(rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return make_fixed_width_scalar(data_type(type_to_id<T>()), stream, mr);
}
template <typename T, std::enable_if_t<is_fixed_point<T>()>* = nullptr>
std::unique_ptr<cudf::scalar> operator()(rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto const scale_ = numeric::scale_type{type.scale()};
auto s = make_fixed_point_scalar<T>(0, scale_, stream, mr);
s->set_valid_async(false, stream);
return s;
}
};
template <>
std::unique_ptr<cudf::scalar> default_scalar_functor::operator()<string_view>(
rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr)
{
return std::unique_ptr<scalar>(new string_scalar("", false, stream, mr));
}
template <>
std::unique_ptr<cudf::scalar> default_scalar_functor::operator()<dictionary32>(
rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr)
{
CUDF_FAIL("dictionary type not supported");
}
template <>
std::unique_ptr<cudf::scalar> default_scalar_functor::operator()<list_view>(
rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr)
{
CUDF_FAIL("list_view type not supported");
}
template <>
std::unique_ptr<cudf::scalar> default_scalar_functor::operator()<struct_view>(
rmm::cuda_stream_view stream, rmm::mr::device_memory_resource* mr)
{
CUDF_FAIL("struct_view type not supported");
}
} // namespace
std::unique_ptr<scalar> make_default_constructed_scalar(data_type type,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return type_dispatcher(type, default_scalar_functor{type}, stream, mr);
}
std::unique_ptr<scalar> make_empty_scalar_like(column_view const& column,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
std::unique_ptr<scalar> result;
switch (column.type().id()) {
case type_id::LIST: {
auto const empty_child = empty_like(lists_column_view(column).child());
result = make_list_scalar(empty_child->view(), stream, mr);
result->set_valid_async(false, stream);
break;
}
case type_id::STRUCT:
// The input column must have at least 1 row to extract a scalar (row) from it.
result = detail::get_element(column, 0, stream, mr);
result->set_valid_async(false, stream);
break;
default: result = make_default_constructed_scalar(column.type(), stream, mr);
}
return result;
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/scalar/scalar.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/structs/utilities.hpp>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/string_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_buffer.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <string>
namespace cudf {
scalar::scalar(data_type type,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: _type(type), _is_valid(is_valid, stream, mr)
{
}
scalar::scalar(scalar const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: _type(other.type()), _is_valid(other._is_valid, stream, mr)
{
}
data_type scalar::type() const noexcept { return _type; }
void scalar::set_valid_async(bool is_valid, rmm::cuda_stream_view stream)
{
_is_valid.set_value_async(is_valid, stream);
}
bool scalar::is_valid(rmm::cuda_stream_view stream) const { return _is_valid.value(stream); }
bool* scalar::validity_data() { return _is_valid.data(); }
bool const* scalar::validity_data() const { return _is_valid.data(); }
string_scalar::string_scalar(std::string const& string,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_id::STRING), is_valid, stream, mr),
_data(string.data(), string.size(), stream, mr)
{
CUDF_EXPECTS(
string.size() <= static_cast<std::size_t>(std::numeric_limits<cudf::size_type>::max()),
"Data exceeds the string size limit",
std::overflow_error);
}
string_scalar::string_scalar(string_scalar const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(other, stream, mr), _data(other._data, stream, mr)
{
}
string_scalar::string_scalar(rmm::device_scalar<value_type>& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: string_scalar(data.value(stream), is_valid, stream, mr)
{
}
string_scalar::string_scalar(value_type const& source,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_id::STRING), is_valid, stream, mr),
_data(source.data(), source.size_bytes(), stream, mr)
{
}
string_scalar::string_scalar(rmm::device_buffer&& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_id::STRING), is_valid, stream, mr), _data(std::move(data))
{
}
string_scalar::value_type string_scalar::value(rmm::cuda_stream_view stream) const
{
return value_type{data(), size()};
}
size_type string_scalar::size() const { return _data.size(); }
char const* string_scalar::data() const { return static_cast<char const*>(_data.data()); }
string_scalar::operator std::string() const { return this->to_string(cudf::get_default_stream()); }
std::string string_scalar::to_string(rmm::cuda_stream_view stream) const
{
std::string result;
result.resize(_data.size());
CUDF_CUDA_TRY(
cudaMemcpyAsync(&result[0], _data.data(), _data.size(), cudaMemcpyDefault, stream.value()));
stream.synchronize();
return result;
}
template <typename T>
fixed_point_scalar<T>::fixed_point_scalar(rep_type value,
numeric::scale_type scale,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar{data_type{type_to_id<T>(), static_cast<int32_t>(scale)}, is_valid, stream, mr},
_data{value, stream, mr}
{
}
template <typename T>
fixed_point_scalar<T>::fixed_point_scalar(rep_type value,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar{data_type{type_to_id<T>(), 0}, is_valid, stream, mr}, _data{value, stream, mr}
{
}
template <typename T>
fixed_point_scalar<T>::fixed_point_scalar(T value,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar{data_type{type_to_id<T>(), value.scale()}, is_valid, stream, mr},
_data{value.value(), stream, mr}
{
}
template <typename T>
fixed_point_scalar<T>::fixed_point_scalar(rmm::device_scalar<rep_type>&& data,
numeric::scale_type scale,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar{data_type{type_to_id<T>(), scale}, is_valid, stream, mr}, _data{std::move(data)}
{
}
template <typename T>
fixed_point_scalar<T>::fixed_point_scalar(fixed_point_scalar<T> const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar{other, stream, mr}, _data(other._data, stream, mr)
{
}
template <typename T>
typename fixed_point_scalar<T>::rep_type fixed_point_scalar<T>::value(
rmm::cuda_stream_view stream) const
{
return _data.value(stream);
}
template <typename T>
T fixed_point_scalar<T>::fixed_point_value(rmm::cuda_stream_view stream) const
{
return value_type{
numeric::scaled_integer<rep_type>{_data.value(stream), numeric::scale_type{type().scale()}}};
}
template <typename T>
fixed_point_scalar<T>::operator value_type() const
{
return this->fixed_point_value(cudf::get_default_stream());
}
template <typename T>
typename fixed_point_scalar<T>::rep_type* fixed_point_scalar<T>::data()
{
return _data.data();
}
template <typename T>
typename fixed_point_scalar<T>::rep_type const* fixed_point_scalar<T>::data() const
{
return _data.data();
}
/**
* @brief These define the valid fixed-point scalar types.
*
* See `is_fixed_point` in @see cudf/utilities/traits.hpp
*
* Adding a new supported type only requires adding the appropriate line here
* and does not require updating the scalar.hpp file.
*/
template class fixed_point_scalar<numeric::decimal32>;
template class fixed_point_scalar<numeric::decimal64>;
template class fixed_point_scalar<numeric::decimal128>;
namespace detail {
template <typename T>
fixed_width_scalar<T>::fixed_width_scalar(T value,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_to_id<T>()), is_valid, stream, mr), _data(value, stream, mr)
{
}
template <typename T>
fixed_width_scalar<T>::fixed_width_scalar(rmm::device_scalar<T>&& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_to_id<T>()), is_valid, stream, mr), _data{std::move(data)}
{
}
template <typename T>
fixed_width_scalar<T>::fixed_width_scalar(fixed_width_scalar<T> const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar{other, stream, mr}, _data(other._data, stream, mr)
{
}
template <typename T>
void fixed_width_scalar<T>::set_value(T value, rmm::cuda_stream_view stream)
{
_data.set_value_async(value, stream);
this->set_valid_async(true, stream);
}
template <typename T>
T fixed_width_scalar<T>::value(rmm::cuda_stream_view stream) const
{
return _data.value(stream);
}
template <typename T>
T* fixed_width_scalar<T>::data()
{
return _data.data();
}
template <typename T>
T const* fixed_width_scalar<T>::data() const
{
return _data.data();
}
template <typename T>
fixed_width_scalar<T>::operator value_type() const
{
return this->value(cudf::get_default_stream());
}
/**
* @brief These define the valid fixed-width scalar types.
*
* See `is_fixed_width` in @see cudf/utilities/traits.hpp
*
* Adding a new supported type only requires adding the appropriate line here
* and does not require updating the scalar.hpp file.
*/
template class fixed_width_scalar<bool>;
template class fixed_width_scalar<int8_t>;
template class fixed_width_scalar<int16_t>;
template class fixed_width_scalar<int32_t>;
template class fixed_width_scalar<int64_t>;
template class fixed_width_scalar<__int128_t>;
template class fixed_width_scalar<uint8_t>;
template class fixed_width_scalar<uint16_t>;
template class fixed_width_scalar<uint32_t>;
template class fixed_width_scalar<uint64_t>;
template class fixed_width_scalar<float>;
template class fixed_width_scalar<double>;
template class fixed_width_scalar<timestamp_D>;
template class fixed_width_scalar<timestamp_s>;
template class fixed_width_scalar<timestamp_ms>;
template class fixed_width_scalar<timestamp_us>;
template class fixed_width_scalar<timestamp_ns>;
template class fixed_width_scalar<duration_D>;
template class fixed_width_scalar<duration_s>;
template class fixed_width_scalar<duration_ms>;
template class fixed_width_scalar<duration_us>;
template class fixed_width_scalar<duration_ns>;
} // namespace detail
template <typename T>
numeric_scalar<T>::numeric_scalar(T value,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: detail::fixed_width_scalar<T>(value, is_valid, stream, mr)
{
}
template <typename T>
numeric_scalar<T>::numeric_scalar(rmm::device_scalar<T>&& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: detail::fixed_width_scalar<T>(std::forward<rmm::device_scalar<T>>(data), is_valid, stream, mr)
{
}
template <typename T>
numeric_scalar<T>::numeric_scalar(numeric_scalar<T> const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: detail::fixed_width_scalar<T>{other, stream, mr}
{
}
/**
* @brief These define the valid numeric scalar types.
*
* See `is_numeric` in @see cudf/utilities/traits.hpp
*
* Adding a new supported type only requires adding the appropriate line here
* and does not require updating the scalar.hpp file.
*/
template class numeric_scalar<bool>;
template class numeric_scalar<int8_t>;
template class numeric_scalar<int16_t>;
template class numeric_scalar<int32_t>;
template class numeric_scalar<int64_t>;
template class numeric_scalar<__int128_t>;
template class numeric_scalar<uint8_t>;
template class numeric_scalar<uint16_t>;
template class numeric_scalar<uint32_t>;
template class numeric_scalar<uint64_t>;
template class numeric_scalar<float>;
template class numeric_scalar<double>;
template <typename T>
chrono_scalar<T>::chrono_scalar(T value,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: detail::fixed_width_scalar<T>(value, is_valid, stream, mr)
{
}
template <typename T>
chrono_scalar<T>::chrono_scalar(rmm::device_scalar<T>&& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: detail::fixed_width_scalar<T>(std::forward<rmm::device_scalar<T>>(data), is_valid, stream, mr)
{
}
template <typename T>
chrono_scalar<T>::chrono_scalar(chrono_scalar<T> const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: detail::fixed_width_scalar<T>{other, stream, mr}
{
}
/**
* @brief These define the valid chrono scalar types.
*
* See `is_chrono` in @see cudf/utilities/traits.hpp
*
* Adding a new supported type only requires adding the appropriate line here
* and does not require updating the scalar.hpp file.
*/
template class chrono_scalar<timestamp_D>;
template class chrono_scalar<timestamp_s>;
template class chrono_scalar<timestamp_ms>;
template class chrono_scalar<timestamp_us>;
template class chrono_scalar<timestamp_ns>;
template class chrono_scalar<duration_D>;
template class chrono_scalar<duration_s>;
template class chrono_scalar<duration_ms>;
template class chrono_scalar<duration_us>;
template class chrono_scalar<duration_ns>;
template <typename T>
duration_scalar<T>::duration_scalar(rep_type value,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: chrono_scalar<T>(T{value}, is_valid, stream, mr)
{
}
template <typename T>
duration_scalar<T>::duration_scalar(duration_scalar<T> const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: chrono_scalar<T>{other, stream, mr}
{
}
template <typename T>
typename duration_scalar<T>::rep_type duration_scalar<T>::count()
{
return this->value().count();
}
/**
* @brief These define the valid duration scalar types.
*
* See `is_duration` in @see cudf/utilities/traits.hpp
*
* Adding a new supported type only requires adding the appropriate line here
* and does not require updating the scalar.hpp file.
*/
template class duration_scalar<duration_D>;
template class duration_scalar<duration_s>;
template class duration_scalar<duration_ms>;
template class duration_scalar<duration_us>;
template class duration_scalar<duration_ns>;
template <typename T>
typename timestamp_scalar<T>::rep_type timestamp_scalar<T>::ticks_since_epoch()
{
return this->value().time_since_epoch().count();
}
/**
* @brief These define the valid timestamp scalar types.
*
* See `is_timestamp` in @see cudf/utilities/traits.hpp
*
* Adding a new supported type only requires adding the appropriate line here
* and does not require updating the scalar.hpp file.
*/
template class timestamp_scalar<timestamp_D>;
template class timestamp_scalar<timestamp_s>;
template class timestamp_scalar<timestamp_ms>;
template class timestamp_scalar<timestamp_us>;
template class timestamp_scalar<timestamp_ns>;
template <typename T>
template <typename D>
timestamp_scalar<T>::timestamp_scalar(D const& value,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: chrono_scalar<T>(T{typename T::duration{value}}, is_valid, stream, mr)
{
}
template <typename T>
timestamp_scalar<T>::timestamp_scalar(timestamp_scalar<T> const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: chrono_scalar<T>{other, stream, mr}
{
}
#define TS_CTOR(TimestampType, DurationType) \
template timestamp_scalar<TimestampType>::timestamp_scalar( \
DurationType const&, bool, rmm::cuda_stream_view, rmm::mr::device_memory_resource*);
/**
* @brief These are the valid combinations of duration types to timestamp types.
*/
TS_CTOR(timestamp_D, duration_D)
TS_CTOR(timestamp_D, int32_t)
TS_CTOR(timestamp_s, duration_D)
TS_CTOR(timestamp_s, duration_s)
TS_CTOR(timestamp_s, int64_t)
TS_CTOR(timestamp_ms, duration_D)
TS_CTOR(timestamp_ms, duration_s)
TS_CTOR(timestamp_ms, duration_ms)
TS_CTOR(timestamp_ms, int64_t)
TS_CTOR(timestamp_us, duration_D)
TS_CTOR(timestamp_us, duration_s)
TS_CTOR(timestamp_us, duration_ms)
TS_CTOR(timestamp_us, duration_us)
TS_CTOR(timestamp_us, int64_t)
TS_CTOR(timestamp_ns, duration_D)
TS_CTOR(timestamp_ns, duration_s)
TS_CTOR(timestamp_ns, duration_ms)
TS_CTOR(timestamp_ns, duration_us)
TS_CTOR(timestamp_ns, duration_ns)
TS_CTOR(timestamp_ns, int64_t)
list_scalar::list_scalar(cudf::column_view const& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_id::LIST), is_valid, stream, mr), _data(data, stream, mr)
{
}
list_scalar::list_scalar(cudf::column&& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_id::LIST), is_valid, stream, mr), _data(std::move(data))
{
}
list_scalar::list_scalar(list_scalar const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar{other, stream, mr}, _data(other._data, stream, mr)
{
}
column_view list_scalar::view() const { return _data.view(); }
struct_scalar::struct_scalar(struct_scalar const& other,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar{other, stream, mr}, _data(other._data, stream, mr)
{
}
struct_scalar::struct_scalar(table_view const& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_id::STRUCT), is_valid, stream, mr),
_data{init_data(table{data}, is_valid, stream, mr)}
{
assert_valid_size();
}
struct_scalar::struct_scalar(host_span<column_view const> data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_id::STRUCT), is_valid, stream, mr),
_data{init_data(
table{table_view{std::vector<column_view>{data.begin(), data.end()}}}, is_valid, stream, mr)}
{
assert_valid_size();
}
struct_scalar::struct_scalar(table&& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
: scalar(data_type(type_id::STRUCT), is_valid, stream, mr),
_data{init_data(std::move(data), is_valid, stream, mr)}
{
assert_valid_size();
}
table_view struct_scalar::view() const { return _data.view(); }
void struct_scalar::assert_valid_size()
{
auto const tv = _data.view();
CUDF_EXPECTS(
std::all_of(tv.begin(), tv.end(), [](column_view const& col) { return col.size() == 1; }),
"Struct scalar inputs must have exactly 1 row");
}
table struct_scalar::init_data(table&& data,
bool is_valid,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
if (is_valid) { return std::move(data); }
auto data_cols = data.release();
// push validity mask down
auto const validity = cudf::detail::create_null_mask(
1, mask_state::ALL_NULL, stream, rmm::mr::get_current_device_resource());
for (auto& col : data_cols) {
col = cudf::structs::detail::superimpose_nulls(
static_cast<bitmask_type const*>(validity.data()), 1, std::move(col), stream, mr);
}
return table{std::move(data_cols)};
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/transpose/transpose.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/reshape.hpp>
#include <cudf/detail/transpose.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cudf/transpose.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/traits.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_iterator.h>
namespace cudf {
namespace detail {
std::pair<std::unique_ptr<column>, table_view> transpose(table_view const& input,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// If there are no rows in the input, return successfully
if (input.num_columns() == 0 || input.num_rows() == 0) {
return {std::make_unique<column>(), table_view{}};
}
// Check datatype homogeneity
auto const dtype = input.column(0).type();
CUDF_EXPECTS(
std::all_of(
input.begin(), input.end(), [dtype](auto const& col) { return dtype == col.type(); }),
"Column type mismatch");
auto output_column = cudf::detail::interleave_columns(input, stream, mr);
auto one_iter = thrust::make_counting_iterator<size_type>(1);
auto splits_iter = thrust::make_transform_iterator(
one_iter, [width = input.num_columns()](size_type idx) { return idx * width; });
auto splits = std::vector<size_type>(splits_iter, splits_iter + input.num_rows() - 1);
auto output_column_views = detail::split(output_column->view(), splits, stream);
return {std::move(output_column), table_view(output_column_views)};
}
} // namespace detail
std::pair<std::unique_ptr<column>, table_view> transpose(table_view const& input,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::transpose(input, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/distinct.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "distinct_helpers.hpp"
#include <cudf/column/column_view.hpp>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
#include <thrust/copy.h>
#include <thrust/distance.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <utility>
#include <vector>
namespace cudf {
namespace detail {
rmm::device_uvector<size_type> get_distinct_indices(table_view const& input,
duplicate_keep_option keep,
null_equality nulls_equal,
nan_equality nans_equal,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
if (input.num_rows() == 0 or input.num_columns() == 0) {
return rmm::device_uvector<size_type>(0, stream, mr);
}
auto map = hash_map_type{compute_hash_table_size(input.num_rows()),
cuco::empty_key{-1},
cuco::empty_value{std::numeric_limits<size_type>::min()},
detail::hash_table_allocator_type{default_allocator<char>{}, stream},
stream.value()};
auto const preprocessed_input =
cudf::experimental::row::hash::preprocessed_table::create(input, stream);
auto const has_nulls = nullate::DYNAMIC{cudf::has_nested_nulls(input)};
auto const has_nested_columns = cudf::detail::has_nested_columns(input);
auto const row_hasher = cudf::experimental::row::hash::row_hasher(preprocessed_input);
auto const key_hasher = row_hasher.device_hasher(has_nulls);
auto const row_comp = cudf::experimental::row::equality::self_comparator(preprocessed_input);
auto const pair_iter = cudf::detail::make_counting_transform_iterator(
size_type{0}, [] __device__(size_type const i) { return cuco::make_pair(i, i); });
auto const insert_keys = [&](auto const value_comp) {
if (has_nested_columns) {
auto const key_equal = row_comp.equal_to<true>(has_nulls, nulls_equal, value_comp);
map.insert(pair_iter, pair_iter + input.num_rows(), key_hasher, key_equal, stream.value());
} else {
auto const key_equal = row_comp.equal_to<false>(has_nulls, nulls_equal, value_comp);
map.insert(pair_iter, pair_iter + input.num_rows(), key_hasher, key_equal, stream.value());
}
};
if (nans_equal == nan_equality::ALL_EQUAL) {
using nan_equal_comparator =
cudf::experimental::row::equality::nan_equal_physical_equality_comparator;
insert_keys(nan_equal_comparator{});
} else {
using nan_unequal_comparator = cudf::experimental::row::equality::physical_equality_comparator;
insert_keys(nan_unequal_comparator{});
}
auto output_indices = rmm::device_uvector<size_type>(map.get_size(), stream, mr);
// If we don't care about order, just gather indices of distinct keys taken from map.
if (keep == duplicate_keep_option::KEEP_ANY) {
map.retrieve_all(output_indices.begin(), thrust::make_discard_iterator(), stream.value());
return output_indices;
}
// For other keep options, reduce by row on rows that compare equal.
auto const reduction_results = reduce_by_row(map,
std::move(preprocessed_input),
input.num_rows(),
has_nulls,
has_nested_columns,
keep,
nulls_equal,
nans_equal,
stream,
rmm::mr::get_current_device_resource());
// Extract the desired output indices from reduction results.
auto const map_end = [&] {
if (keep == duplicate_keep_option::KEEP_NONE) {
// Reduction results with `KEEP_NONE` are either group sizes of equal rows, or `0`.
// Thus, we only output index of the rows in the groups having group size of `1`.
return thrust::copy_if(rmm::exec_policy(stream),
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(input.num_rows()),
output_indices.begin(),
[reduction_results = reduction_results.begin()] __device__(
auto const idx) { return reduction_results[idx] == size_type{1}; });
}
// Reduction results with `KEEP_FIRST` and `KEEP_LAST` are row indices of the first/last row in
// each group of equal rows (which are the desired output indices), or the value given by
// `reduction_init_value()`.
return thrust::copy_if(rmm::exec_policy(stream),
reduction_results.begin(),
reduction_results.end(),
output_indices.begin(),
[init_value = reduction_init_value(keep)] __device__(auto const idx) {
return idx != init_value;
});
}();
output_indices.resize(thrust::distance(output_indices.begin(), map_end), stream);
return output_indices;
}
std::unique_ptr<table> distinct(table_view const& input,
std::vector<size_type> const& keys,
duplicate_keep_option keep,
null_equality nulls_equal,
nan_equality nans_equal,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
if (input.num_rows() == 0 or input.num_columns() == 0 or keys.empty()) {
return empty_like(input);
}
auto const gather_map = get_distinct_indices(input.select(keys),
keep,
nulls_equal,
nans_equal,
stream,
rmm::mr::get_current_device_resource());
return detail::gather(input,
gather_map,
out_of_bounds_policy::DONT_CHECK,
negative_index_policy::NOT_ALLOWED,
stream,
mr);
}
} // namespace detail
std::unique_ptr<table> distinct(table_view const& input,
std::vector<size_type> const& keys,
duplicate_keep_option keep,
null_equality nulls_equal,
nan_equality nans_equal,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::distinct(
input, keys, keep, nulls_equal, nans_equal, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/apply_boolean_mask.cu
|
/*
* Copyright (c) 2019-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/copy_if.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <algorithm>
namespace {
// Returns true if the mask is true and valid (non-null) for index i
// This is the filter functor for apply_boolean_mask
template <bool has_nulls = true>
struct boolean_mask_filter {
boolean_mask_filter(cudf::column_device_view const& boolean_mask) : boolean_mask{boolean_mask} {}
__device__ inline bool operator()(cudf::size_type i)
{
if (true == has_nulls) {
bool valid = boolean_mask.is_valid(i);
bool is_true = boolean_mask.data<bool>()[i];
return is_true && valid;
} else {
return boolean_mask.data<bool>()[i];
}
}
protected:
cudf::column_device_view boolean_mask;
};
} // namespace
namespace cudf {
namespace detail {
/*
* Filters a table_view using a column_view of boolean values as a mask.
*
* calls copy_if() with the `boolean_mask_filter` functor.
*/
std::unique_ptr<table> apply_boolean_mask(table_view const& input,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
if (boolean_mask.is_empty()) { return empty_like(input); }
CUDF_EXPECTS(boolean_mask.type().id() == type_id::BOOL8, "Mask must be Boolean type");
// zero-size inputs are OK, but otherwise input size must match mask size
CUDF_EXPECTS(input.num_rows() == 0 || input.num_rows() == boolean_mask.size(),
"Column size mismatch");
auto device_boolean_mask = cudf::column_device_view::create(boolean_mask, stream);
if (boolean_mask.has_nulls()) {
return detail::copy_if(input, boolean_mask_filter<true>{*device_boolean_mask}, stream, mr);
} else {
return detail::copy_if(input, boolean_mask_filter<false>{*device_boolean_mask}, stream, mr);
}
}
} // namespace detail
/*
* Filters a table_view using a column_view of boolean values as a mask.
*/
std::unique_ptr<table> apply_boolean_mask(table_view const& input,
column_view const& boolean_mask,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::apply_boolean_mask(input, boolean_mask, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/distinct_count.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stream_compaction_common.cuh"
#include "stream_compaction_common.hpp"
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/sorting.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <cuco/static_set.cuh>
#include <thrust/count.h>
#include <thrust/execution_policy.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/logical.h>
#include <cmath>
#include <cstddef>
#include <type_traits>
#include <utility>
#include <vector>
namespace cudf {
namespace detail {
namespace {
/**
* @brief Functor to check for `NaN` at an index in a `column_device_view`.
*
* @tparam T The type of `column_device_view`
*/
template <typename T>
struct check_for_nan {
/*
* @brief Construct from a column_device_view.
*
* @param[in] input The `column_device_view`
*/
check_for_nan(cudf::column_device_view input) : _input{input} {}
/**
* @brief Operator to be called to check for `NaN` at `index` in `_input`
*
* @param[in] index The index at which the `NaN` needs to be checked in `input`
*
* @returns bool true if value at `index` is `NaN` and not null, else false
*/
__device__ bool operator()(size_type index) const noexcept
{
return std::isnan(_input.data<T>()[index]) and _input.is_valid(index);
}
cudf::column_device_view _input;
};
/**
* @brief A structure to be used along with type_dispatcher to check if a
* `column_view` has `NaN`.
*/
struct has_nans {
/**
* @brief Checks if `input` has `NaN`
*
* @note This will be applicable only for floating point type columns.
*
* @param[in] input The `column_view` which will be checked for `NaN`
* @param[in] stream CUDA stream used for device memory operations and kernel launches.
*
* @returns bool true if `input` has `NaN` else false
*/
template <typename T, std::enable_if_t<std::is_floating_point_v<T>>* = nullptr>
bool operator()(column_view const& input, rmm::cuda_stream_view stream)
{
auto input_device_view = cudf::column_device_view::create(input, stream);
auto device_view = *input_device_view;
return thrust::any_of(rmm::exec_policy(stream),
thrust::counting_iterator<cudf::size_type>(0),
thrust::counting_iterator<cudf::size_type>(input.size()),
check_for_nan<T>(device_view));
}
/**
* @brief Checks if `input` has `NaN`
*
* @note This will be applicable only for non-floating point type columns. And
* non-floating point columns can never have `NaN`, so it will always return
* false
*
* @param[in] input The `column_view` which will be checked for `NaN`
* @param[in] stream CUDA stream used for device memory operations and kernel launches.
*
* @returns bool Always false as non-floating point columns can't have `NaN`
*/
template <typename T, std::enable_if_t<not std::is_floating_point_v<T>>* = nullptr>
bool operator()(column_view const&, rmm::cuda_stream_view)
{
return false;
}
};
} // namespace
cudf::size_type distinct_count(table_view const& keys,
null_equality nulls_equal,
rmm::cuda_stream_view stream)
{
auto const num_rows = keys.num_rows();
if (num_rows == 0) { return 0; } // early exit for empty input
auto const has_nulls = nullate::DYNAMIC{cudf::has_nested_nulls(keys)};
auto const preprocessed_input =
cudf::experimental::row::hash::preprocessed_table::create(keys, stream);
auto const row_hasher = cudf::experimental::row::hash::row_hasher(preprocessed_input);
auto const hash_key = row_hasher.device_hasher(has_nulls);
auto const row_comp = cudf::experimental::row::equality::self_comparator(preprocessed_input);
auto const comparator_helper = [&](auto const row_equal) {
using hasher_type = decltype(hash_key);
auto key_set = cuco::experimental::static_set{
cuco::experimental::extent{compute_hash_table_size(num_rows)},
cuco::empty_key<cudf::size_type>{-1},
row_equal,
cuco::experimental::linear_probing<1, hasher_type>{hash_key},
detail::hash_table_allocator_type{default_allocator<char>{}, stream},
stream.value()};
auto const iter = thrust::counting_iterator<cudf::size_type>(0);
// when nulls are equal, we skip hashing any row that has a null
// in every column to improve efficiency.
if (nulls_equal == null_equality::EQUAL and has_nulls) {
thrust::counting_iterator<size_type> stencil(0);
// We must consider a row if any of its column entries is valid,
// hence OR together the validities of the columns.
auto const [row_bitmask, null_count] =
cudf::detail::bitmask_or(keys, stream, rmm::mr::get_current_device_resource());
// Unless all columns have a null mask, row_bitmask will be
// null, and null_count will be zero. Equally, unless there is
// some row which is null in all columns, null_count will be
// zero. So, it is only when null_count is not zero that we need
// to do a filtered insertion.
if (null_count > 0) {
row_validity pred{static_cast<bitmask_type const*>(row_bitmask.data())};
return key_set.insert_if(iter, iter + num_rows, stencil, pred, stream.value()) + 1;
}
}
// otherwise, insert all
return key_set.insert(iter, iter + num_rows, stream.value());
};
if (cudf::detail::has_nested_columns(keys)) {
auto const row_equal = row_comp.equal_to<true>(has_nulls, nulls_equal);
return comparator_helper(row_equal);
} else {
auto const row_equal = row_comp.equal_to<false>(has_nulls, nulls_equal);
return comparator_helper(row_equal);
}
}
cudf::size_type distinct_count(column_view const& input,
null_policy null_handling,
nan_policy nan_handling,
rmm::cuda_stream_view stream)
{
if (0 == input.size() or input.null_count() == input.size()) { return 0; }
auto count = detail::distinct_count(table_view{{input}}, null_equality::EQUAL, stream);
// Check for nulls. If the null policy is EXCLUDE and null values were found,
// we decrement the count.
auto const has_null = input.has_nulls();
if (null_handling == null_policy::EXCLUDE and has_null) { --count; }
// Check for NaNs. There are two cases that can lead to decrementing the
// count. The first case is when the input has no nulls, but has NaN values
// handled as a null via NAN_IS_NULL and has a policy to EXCLUDE null values
// from the count. The second case is when the input has null values and NaN
// values handled as nulls via NAN_IS_NULL. Regardless of whether the null
// policy is set to EXCLUDE, we decrement the count to avoid double-counting
// null and NaN as distinct entities.
auto const has_nan_as_null = (nan_handling == nan_policy::NAN_IS_NULL) and
cudf::type_dispatcher(input.type(), has_nans{}, input, stream);
if (has_nan_as_null and (has_null or null_handling == null_policy::EXCLUDE)) { --count; }
return count;
}
} // namespace detail
cudf::size_type distinct_count(column_view const& input,
null_policy null_handling,
nan_policy nan_handling)
{
CUDF_FUNC_RANGE();
return detail::distinct_count(input, null_handling, nan_handling, cudf::get_default_stream());
}
cudf::size_type distinct_count(table_view const& input, null_equality nulls_equal)
{
CUDF_FUNC_RANGE();
return detail::distinct_count(input, nulls_equal, cudf::get_default_stream());
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/stream_compaction_common.cuh
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "stream_compaction_common.hpp"
#include <cudf/stream_compaction.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/copy.h>
#include <thrust/distance.h>
#include <thrust/iterator/counting_iterator.h>
namespace cudf {
namespace detail {
/**
 * @brief Device functor to determine if a row is valid.
 */
class row_validity {
public:
row_validity(bitmask_type const* row_bitmask) : _row_bitmask{row_bitmask} {}
__device__ inline bool operator()(size_type const& i) const noexcept
{
return cudf::bit_is_set(_row_bitmask, i);
}
private:
bitmask_type const* _row_bitmask;
};
template <typename InputIterator, typename BinaryPredicate>
struct unique_copy_fn {
/**
* @brief Functor for unique_copy()
*
* The logic here is equivalent to:
* @code
* ((keep == duplicate_keep_option::KEEP_LAST) ||
* (i == 0 || !comp(iter[i], iter[i - 1]))) &&
* ((keep == duplicate_keep_option::KEEP_FIRST) ||
* (i == last_index || !comp(iter[i], iter[i + 1])))
* @endcode
*
* It is written this way so that the `comp` comparator
* function appears only once minimizing the inlining
* required and reducing the compile time.
*/
__device__ bool operator()(size_type i)
{
size_type boundary = 0;
size_type offset = 1;
auto keep_option = duplicate_keep_option::KEEP_LAST;
do {
if ((keep != keep_option) && (i != boundary) && comp(iter[i], iter[i - offset])) {
return false;
}
keep_option = duplicate_keep_option::KEEP_FIRST;
boundary = last_index;
offset = -offset;
} while (offset < 0);
return true;
}
InputIterator iter;
duplicate_keep_option const keep;
BinaryPredicate comp;
size_type const last_index;
};
/**
* @brief Copies unique elements from the range [first, last) to output iterator `output`.
*
* In a consecutive group of duplicate elements, depending on parameter `keep`,
* only the first element is copied, or the last element is copied or neither is copied.
*
* @return End of the range to which the elements are copied.
*/
template <typename InputIterator, typename OutputIterator, typename BinaryPredicate>
OutputIterator unique_copy(InputIterator first,
InputIterator last,
OutputIterator output,
BinaryPredicate comp,
duplicate_keep_option const keep,
rmm::cuda_stream_view stream)
{
size_type const last_index = thrust::distance(first, last) - 1;
return thrust::copy_if(
rmm::exec_policy(stream),
first,
last,
thrust::counting_iterator<size_type>(0),
output,
unique_copy_fn<InputIterator, BinaryPredicate>{first, keep, comp, last_index});
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/drop_nulls.cu
|
/*
* Copyright (c) 2019-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/copy_if.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/count.h>
#include <thrust/execution_policy.h>
namespace {
// Returns true if the mask is true for index i in at least keep_threshold
// columns
struct valid_table_filter {
__device__ inline bool operator()(cudf::size_type i)
{
auto valid = [i](auto column_device_view) { return column_device_view.is_valid(i); };
auto count =
thrust::count_if(thrust::seq, keys_device_view.begin(), keys_device_view.end(), valid);
return (count >= keep_threshold);
}
valid_table_filter() = delete;
~valid_table_filter() = default;
valid_table_filter(cudf::table_device_view const& keys_device_view,
cudf::size_type keep_threshold)
: keep_threshold(keep_threshold), keys_device_view(keys_device_view)
{
}
protected:
cudf::size_type keep_threshold;
cudf::size_type num_columns;
cudf::table_device_view keys_device_view;
};
} // namespace
namespace cudf {
namespace detail {
/*
* Filters a table to remove null elements.
*/
std::unique_ptr<table> drop_nulls(table_view const& input,
std::vector<size_type> const& keys,
cudf::size_type keep_threshold,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto keys_view = input.select(keys);
if (keys_view.num_columns() == 0 || keys_view.num_rows() == 0 || not cudf::has_nulls(keys_view)) {
return std::make_unique<table>(input, stream, mr);
}
auto keys_device_view = cudf::table_device_view::create(keys_view, stream);
return cudf::detail::copy_if(
input, valid_table_filter{*keys_device_view, keep_threshold}, stream, mr);
}
} // namespace detail
/*
* Filters a table to remove null elements.
*/
std::unique_ptr<table> drop_nulls(table_view const& input,
std::vector<size_type> const& keys,
cudf::size_type keep_threshold,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::drop_nulls(input, keys, keep_threshold, cudf::get_default_stream(), mr);
}
/*
* Filters a table to remove null elements.
*/
std::unique_ptr<table> drop_nulls(table_view const& input,
std::vector<size_type> const& keys,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::drop_nulls(input, keys, keys.size(), cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/distinct_helpers.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "distinct_helpers.hpp"
#include <cudf/detail/hash_reduce_by_row.cuh>
namespace cudf::detail {
namespace {
/**
* @brief The functor to find the first/last/all duplicate row for rows that compared equal.
*/
template <typename MapView, typename KeyHasher, typename KeyEqual>
struct reduce_fn : reduce_by_row_fn_base<MapView, KeyHasher, KeyEqual, size_type> {
duplicate_keep_option const keep;
reduce_fn(MapView const& d_map,
KeyHasher const& d_hasher,
KeyEqual const& d_equal,
duplicate_keep_option const keep,
size_type* const d_output)
: reduce_by_row_fn_base<MapView, KeyHasher, KeyEqual, size_type>{d_map,
d_hasher,
d_equal,
d_output},
keep{keep}
{
}
__device__ void operator()(size_type const idx) const
{
auto const out_ptr = this->get_output_ptr(idx);
if (keep == duplicate_keep_option::KEEP_FIRST) {
// Store the smallest index of all rows that are equal.
atomicMin(out_ptr, idx);
} else if (keep == duplicate_keep_option::KEEP_LAST) {
// Store the greatest index of all rows that are equal.
atomicMax(out_ptr, idx);
} else {
// Count the number of rows in each group of rows that are compared equal.
atomicAdd(out_ptr, size_type{1});
}
}
};
/**
* @brief The builder to construct an instance of `reduce_fn` functor base on the given
* value of the `duplicate_keep_option` member variable.
*/
struct reduce_func_builder {
duplicate_keep_option const keep;
template <typename MapView, typename KeyHasher, typename KeyEqual>
auto build(MapView const& d_map,
KeyHasher const& d_hasher,
KeyEqual const& d_equal,
size_type* const d_output)
{
return reduce_fn<MapView, KeyHasher, KeyEqual>{d_map, d_hasher, d_equal, keep, d_output};
}
};
} // namespace
// This function is split from `distinct.cu` to improve compile time.
rmm::device_uvector<size_type> reduce_by_row(
hash_map_type const& map,
std::shared_ptr<cudf::experimental::row::equality::preprocessed_table> const preprocessed_input,
size_type num_rows,
cudf::nullate::DYNAMIC has_nulls,
bool has_nested_columns,
duplicate_keep_option keep,
null_equality nulls_equal,
nan_equality nans_equal,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(keep != duplicate_keep_option::KEEP_ANY,
"This function should not be called with KEEP_ANY");
return hash_reduce_by_row(map,
preprocessed_input,
num_rows,
has_nulls,
has_nested_columns,
nulls_equal,
nans_equal,
reduce_func_builder{keep},
reduction_init_value(keep),
stream,
mr);
}
} // namespace cudf::detail
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/stream_compaction_common.hpp
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <cudf/hashing/detail/hash_allocator.cuh>
#include <cudf/hashing/detail/helper_functions.cuh>
#include <cudf/table/row_operators.cuh>
#include <cudf/table/table_device_view.cuh>
#include <rmm/mr/device/polymorphic_allocator.hpp>
#include <cuco/static_map.cuh>
#include <limits>
namespace cudf {
namespace detail {
using hash_table_allocator_type = rmm::mr::stream_allocator_adaptor<default_allocator<char>>;
using hash_map_type =
cuco::static_map<size_type, size_type, cuda::thread_scope_device, hash_table_allocator_type>;
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/drop_nans.cu
|
/*
* Copyright (c) 2020-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/copy_if.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/count.h>
#include <thrust/execution_policy.h>
namespace {
struct dispatch_is_not_nan {
template <typename T>
std::enable_if_t<std::is_floating_point_v<T>, bool> __device__
operator()(cudf::column_device_view col_device_view, cudf::size_type i)
{
return col_device_view.is_valid(i) ? not std::isnan(col_device_view.element<T>(i)) : true;
}
template <typename T>
std::enable_if_t<not std::is_floating_point_v<T>, bool> __device__
operator()(cudf::column_device_view, cudf::size_type)
{
return true;
}
};
// Returns true if the mask is true and it is not NaN for index i in at least keep_threshold
// columns
struct valid_table_filter {
__device__ inline bool operator()(cudf::size_type i)
{
auto valid = [i](auto col_device_view) {
return cudf::type_dispatcher(
col_device_view.type(), dispatch_is_not_nan{}, col_device_view, i);
};
auto count =
thrust::count_if(thrust::seq, keys_device_view.begin(), keys_device_view.end(), valid);
return (count >= keep_threshold);
}
valid_table_filter() = delete;
~valid_table_filter() = default;
valid_table_filter(cudf::table_device_view const& keys_device_view,
cudf::size_type keep_threshold)
: keep_threshold(keep_threshold), keys_device_view(keys_device_view)
{
}
protected:
cudf::size_type keep_threshold;
cudf::size_type num_columns;
cudf::table_device_view keys_device_view;
};
} // namespace
namespace cudf {
namespace detail {
/*
* Filters a table to remove nans elements.
*/
std::unique_ptr<table> drop_nans(table_view const& input,
std::vector<size_type> const& keys,
cudf::size_type keep_threshold,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto keys_view = input.select(keys);
if (keys_view.num_columns() == 0 || keys_view.num_rows() == 0) {
return std::make_unique<table>(input, stream, mr);
}
if (std::any_of(keys_view.begin(), keys_view.end(), [](auto col) {
return not is_floating_point(col.type());
})) {
CUDF_FAIL("Key column is not of type floating-point");
}
auto keys_device_view = cudf::table_device_view::create(keys_view, stream);
return cudf::detail::copy_if(
input, valid_table_filter{*keys_device_view, keep_threshold}, stream, mr);
}
} // namespace detail
/*
* Filters a table to remove nan elements.
*/
std::unique_ptr<table> drop_nans(table_view const& input,
std::vector<size_type> const& keys,
cudf::size_type keep_threshold,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::drop_nans(input, keys, keep_threshold, cudf::get_default_stream(), mr);
}
/*
* Filters a table to remove nan elements.
*/
std::unique_ptr<table> drop_nans(table_view const& input,
std::vector<size_type> const& keys,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::drop_nans(input, keys, keys.size(), cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/distinct_helpers.hpp
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stream_compaction_common.hpp"
#include <cudf/stream_compaction.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/types.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
namespace cudf::detail {
/**
* @brief Return the reduction identity used to initialize results of `hash_reduce_by_row`.
*
* @param keep A value of `duplicate_keep_option` type, must not be `KEEP_ANY`.
* @return The initial reduction value.
*/
auto constexpr reduction_init_value(duplicate_keep_option keep)
{
switch (keep) {
case duplicate_keep_option::KEEP_FIRST: return std::numeric_limits<size_type>::max();
case duplicate_keep_option::KEEP_LAST: return std::numeric_limits<size_type>::min();
case duplicate_keep_option::KEEP_NONE: return size_type{0};
default: CUDF_UNREACHABLE("This function should not be called with KEEP_ANY");
}
}
/**
* @brief Perform a reduction on groups of rows that are compared equal.
*
* This is essentially a reduce-by-key operation with keys are non-contiguous rows and are compared
* equal. A hash table is used to find groups of equal rows.
*
* Depending on the `keep` parameter, the reduction operation for each row group is:
* - If `keep == KEEP_FIRST`: min of row indices in the group.
* - If `keep == KEEP_LAST`: max of row indices in the group.
* - If `keep == KEEP_NONE`: count of equivalent rows (group size).
*
* Note that this function is not needed when `keep == KEEP_NONE`.
*
* At the beginning of the operation, the entire output array is filled with a value given by
* the `reduction_init_value()` function. Then, the reduction result for each row group is written
* into the output array at the index of an unspecified row in the group.
*
* @param map The auxiliary map to perform reduction
* @param preprocessed_input The preprocessed of the input rows for computing row hashing and row
* comparisons
* @param num_rows The number of all input rows
* @param has_nulls Indicate whether the input rows has any nulls at any nested levels
* @param has_nested_columns Indicates whether the input table has any nested columns
* @param keep The parameter to determine what type of reduction to perform
* @param nulls_equal Flag to specify whether null elements should be considered as equal
* @param nans_equal Flag to specify whether NaN values in floating point column should be
* considered equal.
* @param stream CUDA stream used for device memory operations and kernel launches
* @param mr Device memory resource used to allocate the returned vector
* @return A device_uvector containing the reduction results
*/
rmm::device_uvector<size_type> reduce_by_row(
hash_map_type const& map,
std::shared_ptr<cudf::experimental::row::equality::preprocessed_table> const preprocessed_input,
size_type num_rows,
cudf::nullate::DYNAMIC has_nulls,
bool has_nested_columns,
duplicate_keep_option keep,
null_equality nulls_equal,
nan_equality nans_equal,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr);
} // namespace cudf::detail
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/unique_count_column.cu
|
/*
* Copyright (c) 2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/count.h>
#include <thrust/execution_policy.h>
#include <thrust/iterator/counting_iterator.h>
#include <cmath>
namespace cudf {
namespace detail {
namespace {
/**
* @brief A functor to be used along with device type_dispatcher to check if
* the row `index` of `column_device_view` is `NaN`.
*/
struct check_nan {
// Check if a value is `NaN` for floating point type columns
template <typename T, std::enable_if_t<std::is_floating_point_v<T>>* = nullptr>
__device__ inline bool operator()(column_device_view const& input, size_type index)
{
return std::isnan(input.data<T>()[index]);
}
// Non-floating point type columns can never have `NaN`, so it will always return false.
template <typename T, std::enable_if_t<not std::is_floating_point_v<T>>* = nullptr>
__device__ inline bool operator()(column_device_view const&, size_type)
{
return false;
}
};
} // namespace
cudf::size_type unique_count(column_view const& input,
null_policy null_handling,
nan_policy nan_handling,
rmm::cuda_stream_view stream)
{
auto const num_rows = input.size();
if (num_rows == 0 or num_rows == input.null_count()) { return 0; }
auto const count_nulls = null_handling == null_policy::INCLUDE;
auto const nan_is_null = nan_handling == nan_policy::NAN_IS_NULL;
auto const should_check_nan = cudf::is_floating_point(input.type());
auto input_device_view = cudf::column_device_view::create(input, stream);
auto device_view = *input_device_view;
auto input_table_view = table_view{{input}};
auto table_ptr = cudf::table_device_view::create(input_table_view, stream);
row_equality_comparator comp(nullate::DYNAMIC{cudf::has_nulls(input_table_view)},
*table_ptr,
*table_ptr,
null_equality::EQUAL);
return thrust::count_if(
rmm::exec_policy(stream),
thrust::counting_iterator<cudf::size_type>(0),
thrust::counting_iterator<cudf::size_type>(num_rows),
[count_nulls, nan_is_null, should_check_nan, device_view, comp] __device__(cudf::size_type i) {
auto const is_null = device_view.is_null(i);
auto const is_nan = nan_is_null and should_check_nan and
cudf::type_dispatcher(device_view.type(), check_nan{}, device_view, i);
if (not count_nulls and (is_null or (nan_is_null and is_nan))) { return false; }
if (i == 0) { return true; }
if (count_nulls and nan_is_null and (is_nan or is_null)) {
auto const prev_is_nan =
should_check_nan and
cudf::type_dispatcher(device_view.type(), check_nan{}, device_view, i - 1);
return not(prev_is_nan or device_view.is_null(i - 1));
}
return not comp(i, i - 1);
});
}
} // namespace detail
cudf::size_type unique_count(column_view const& input,
null_policy null_handling,
nan_policy nan_handling)
{
CUDF_FUNC_RANGE();
return detail::unique_count(input, null_handling, nan_handling, cudf::get_default_stream());
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/stable_distinct.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/copy_if.cuh>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/span.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/scatter.h>
#include <thrust/uninitialized_fill.h>
namespace cudf {
namespace detail {
std::unique_ptr<table> stable_distinct(table_view const& input,
std::vector<size_type> const& keys,
duplicate_keep_option keep,
null_equality nulls_equal,
nan_equality nans_equal,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
if (input.num_rows() == 0 or input.num_columns() == 0 or keys.empty()) {
return empty_like(input);
}
auto const distinct_indices = get_distinct_indices(input.select(keys),
keep,
nulls_equal,
nans_equal,
stream,
rmm::mr::get_current_device_resource());
// The only difference between this implementation and the unstable version
// is that the stable implementation must retain the input order. The
// distinct indices are not sorted, so we cannot simply copy the rows in the
// order of the distinct indices and retain the input order. Instead, we use
// a boolean mask to indicate which rows to copy to the output. This avoids
// the need to sort the distinct indices, which is slower.
auto const output_markers = [&] {
auto markers = rmm::device_uvector<bool>(input.num_rows(), stream);
thrust::uninitialized_fill(rmm::exec_policy(stream), markers.begin(), markers.end(), false);
thrust::scatter(
rmm::exec_policy(stream),
thrust::constant_iterator<bool>(true, 0),
thrust::constant_iterator<bool>(true, static_cast<size_type>(distinct_indices.size())),
distinct_indices.begin(),
markers.begin());
return markers;
}();
return cudf::detail::apply_boolean_mask(
input, cudf::device_span<bool const>(output_markers), stream, mr);
}
} // namespace detail
std::unique_ptr<table> stable_distinct(table_view const& input,
std::vector<size_type> const& keys,
duplicate_keep_option keep,
null_equality nulls_equal,
nan_equality nans_equal,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::stable_distinct(
input, keys, keep, nulls_equal, nans_equal, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/unique_count.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/count.h>
#include <thrust/execution_policy.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/transform.h>
namespace cudf {
namespace detail {
cudf::size_type unique_count(table_view const& keys,
null_equality nulls_equal,
rmm::cuda_stream_view stream)
{
auto const row_comp = cudf::experimental::row::equality::self_comparator(keys, stream);
if (cudf::detail::has_nested_columns(keys)) {
auto const comp =
row_comp.equal_to<true>(nullate::DYNAMIC{has_nested_nulls(keys)}, nulls_equal);
// Using a temporary buffer for intermediate transform results from the lambda containing
// the comparator speeds up compile-time significantly without much degradation in
// runtime performance over using the comparator directly in thrust::count_if.
auto d_results = rmm::device_uvector<bool>(keys.num_rows(), stream);
thrust::transform(rmm::exec_policy(stream),
thrust::make_counting_iterator<size_type>(0),
thrust::make_counting_iterator<size_type>(keys.num_rows()),
d_results.begin(),
[comp] __device__(auto i) { return (i == 0 or not comp(i, i - 1)); });
return static_cast<size_type>(
thrust::count(rmm::exec_policy(stream), d_results.begin(), d_results.end(), true));
} else {
auto const comp =
row_comp.equal_to<false>(nullate::DYNAMIC{has_nested_nulls(keys)}, nulls_equal);
// Using thrust::copy_if with the comparator directly will compile more slowly but
// improves runtime by up to 2x over the transform/count approach above.
return thrust::count_if(
rmm::exec_policy(stream),
thrust::counting_iterator<cudf::size_type>(0),
thrust::counting_iterator<cudf::size_type>(keys.num_rows()),
[comp] __device__(cudf::size_type i) { return (i == 0 or not comp(i, i - 1)); });
}
}
} // namespace detail
cudf::size_type unique_count(table_view const& input, null_equality nulls_equal)
{
CUDF_FUNC_RANGE();
return detail::unique_count(input, nulls_equal, cudf::get_default_stream());
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/stream_compaction/unique.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stream_compaction_common.cuh"
#include "stream_compaction_common.hpp"
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/sorting.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/stream_compaction.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/copy.h>
#include <thrust/distance.h>
#include <thrust/execution_policy.h>
#include <thrust/iterator/counting_iterator.h>
#include <utility>
#include <vector>
namespace cudf {
namespace detail {
std::unique_ptr<table> unique(table_view const& input,
std::vector<size_type> const& keys,
duplicate_keep_option keep,
null_equality nulls_equal,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// If keep is KEEP_ANY, just alias it to KEEP_FIRST.
if (keep == duplicate_keep_option::KEEP_ANY) { keep = duplicate_keep_option::KEEP_FIRST; }
auto const num_rows = input.num_rows();
if (num_rows == 0 or input.num_columns() == 0 or keys.empty()) { return empty_like(input); }
auto unique_indices = make_numeric_column(
data_type{type_to_id<size_type>()}, num_rows, mask_state::UNALLOCATED, stream, mr);
auto mutable_view = mutable_column_device_view::create(*unique_indices, stream);
auto keys_view = input.select(keys);
auto comp = cudf::experimental::row::equality::self_comparator(keys_view, stream);
size_type const unique_size = [&] {
if (cudf::detail::has_nested_columns(keys_view)) {
// Using a temporary buffer for intermediate transform results from the functor containing
// the comparator speeds up compile-time significantly without much degradation in
// runtime performance over using the comparator directly in thrust::unique_copy.
auto row_equal =
comp.equal_to<true>(nullate::DYNAMIC{has_nested_nulls(keys_view)}, nulls_equal);
auto d_results = rmm::device_uvector<bool>(num_rows, stream);
auto itr = thrust::make_counting_iterator<size_type>(0);
thrust::transform(
rmm::exec_policy(stream),
itr,
itr + num_rows,
d_results.begin(),
unique_copy_fn<decltype(itr), decltype(row_equal)>{itr, keep, row_equal, num_rows - 1});
auto result_end = thrust::copy_if(rmm::exec_policy(stream),
itr,
itr + num_rows,
d_results.begin(),
mutable_view->begin<size_type>(),
thrust::identity<bool>{});
return static_cast<size_type>(thrust::distance(mutable_view->begin<size_type>(), result_end));
} else {
// Using thrust::unique_copy with the comparator directly will compile more slowly but
// improves runtime by up to 2x over the transform/copy_if approach above.
auto row_equal =
comp.equal_to<false>(nullate::DYNAMIC{has_nested_nulls(keys_view)}, nulls_equal);
auto result_end = unique_copy(thrust::counting_iterator<size_type>(0),
thrust::counting_iterator<size_type>(num_rows),
mutable_view->begin<size_type>(),
row_equal,
keep,
stream);
return static_cast<size_type>(thrust::distance(mutable_view->begin<size_type>(), result_end));
}
}();
auto indices_view = cudf::detail::slice(column_view(*unique_indices), 0, unique_size, stream);
// gather unique rows and return
return detail::gather(input,
indices_view,
out_of_bounds_policy::DONT_CHECK,
detail::negative_index_policy::NOT_ALLOWED,
stream,
mr);
}
} // namespace detail
std::unique_ptr<table> unique(table_view const& input,
std::vector<size_type> const& keys,
duplicate_keep_option const keep,
null_equality nulls_equal,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::unique(input, keys, keep, nulls_equal, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/aggregation/aggregation.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/aggregation.hpp>
#include <cudf/detail/aggregation/aggregation.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <memory>
namespace cudf {
namespace detail {
// simple_aggregations_collector ----------------------------------------
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, aggregation const& agg)
{
std::vector<std::unique_ptr<aggregation>> aggs;
aggs.push_back(agg.clone());
return aggs;
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, sum_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, product_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, min_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, max_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, count_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, histogram_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, any_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, all_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, sum_of_squares_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, mean_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, m2_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, var_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, std_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, median_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, quantile_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, argmax_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, argmin_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, nunique_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, nth_element_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, row_number_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, rank_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, collect_list_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, collect_set_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, lead_lag_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, udf_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, merge_lists_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, merge_sets_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, merge_m2_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, merge_histogram_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, covariance_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, correlation_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, tdigest_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
std::vector<std::unique_ptr<aggregation>> simple_aggregations_collector::visit(
data_type col_type, merge_tdigest_aggregation const& agg)
{
return visit(col_type, static_cast<aggregation const&>(agg));
}
// aggregation_finalizer ----------------------------------------
void aggregation_finalizer::visit(aggregation const& agg) {}
void aggregation_finalizer::visit(sum_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(product_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(min_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(max_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(count_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(histogram_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(any_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(all_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(sum_of_squares_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(mean_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(m2_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(var_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(std_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(median_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(quantile_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(argmax_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(argmin_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(nunique_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(nth_element_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(row_number_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(rank_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(collect_list_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(collect_set_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(lead_lag_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(udf_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(merge_lists_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(merge_sets_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(merge_m2_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(merge_histogram_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(covariance_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(correlation_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(tdigest_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
void aggregation_finalizer::visit(merge_tdigest_aggregation const& agg)
{
visit(static_cast<aggregation const&>(agg));
}
} // namespace detail
std::vector<std::unique_ptr<aggregation>> aggregation::get_simple_aggregations(
data_type col_type, cudf::detail::simple_aggregations_collector& collector) const
{
return collector.visit(col_type, *this);
}
/// Factory to create a SUM aggregation
template <typename Base>
std::unique_ptr<Base> make_sum_aggregation()
{
return std::make_unique<detail::sum_aggregation>();
}
template std::unique_ptr<aggregation> make_sum_aggregation<aggregation>();
template std::unique_ptr<rolling_aggregation> make_sum_aggregation<rolling_aggregation>();
template std::unique_ptr<groupby_aggregation> make_sum_aggregation<groupby_aggregation>();
template std::unique_ptr<groupby_scan_aggregation> make_sum_aggregation<groupby_scan_aggregation>();
template std::unique_ptr<reduce_aggregation> make_sum_aggregation<reduce_aggregation>();
template std::unique_ptr<scan_aggregation> make_sum_aggregation<scan_aggregation>();
template std::unique_ptr<segmented_reduce_aggregation>
make_sum_aggregation<segmented_reduce_aggregation>();
/// Factory to create a PRODUCT aggregation
template <typename Base>
std::unique_ptr<Base> make_product_aggregation()
{
return std::make_unique<detail::product_aggregation>();
}
template std::unique_ptr<aggregation> make_product_aggregation<aggregation>();
template std::unique_ptr<groupby_aggregation> make_product_aggregation<groupby_aggregation>();
template std::unique_ptr<reduce_aggregation> make_product_aggregation<reduce_aggregation>();
template std::unique_ptr<scan_aggregation> make_product_aggregation<scan_aggregation>();
template std::unique_ptr<segmented_reduce_aggregation>
make_product_aggregation<segmented_reduce_aggregation>();
/// Factory to create a MIN aggregation
template <typename Base>
std::unique_ptr<Base> make_min_aggregation()
{
return std::make_unique<detail::min_aggregation>();
}
template std::unique_ptr<aggregation> make_min_aggregation<aggregation>();
template std::unique_ptr<rolling_aggregation> make_min_aggregation<rolling_aggregation>();
template std::unique_ptr<groupby_aggregation> make_min_aggregation<groupby_aggregation>();
template std::unique_ptr<groupby_scan_aggregation> make_min_aggregation<groupby_scan_aggregation>();
template std::unique_ptr<reduce_aggregation> make_min_aggregation<reduce_aggregation>();
template std::unique_ptr<scan_aggregation> make_min_aggregation<scan_aggregation>();
template std::unique_ptr<segmented_reduce_aggregation>
make_min_aggregation<segmented_reduce_aggregation>();
/// Factory to create a MAX aggregation
template <typename Base>
std::unique_ptr<Base> make_max_aggregation()
{
return std::make_unique<detail::max_aggregation>();
}
template std::unique_ptr<aggregation> make_max_aggregation<aggregation>();
template std::unique_ptr<rolling_aggregation> make_max_aggregation<rolling_aggregation>();
template std::unique_ptr<groupby_aggregation> make_max_aggregation<groupby_aggregation>();
template std::unique_ptr<groupby_scan_aggregation> make_max_aggregation<groupby_scan_aggregation>();
template std::unique_ptr<reduce_aggregation> make_max_aggregation<reduce_aggregation>();
template std::unique_ptr<scan_aggregation> make_max_aggregation<scan_aggregation>();
template std::unique_ptr<segmented_reduce_aggregation>
make_max_aggregation<segmented_reduce_aggregation>();
/// Factory to create a COUNT aggregation
template <typename Base>
std::unique_ptr<Base> make_count_aggregation(null_policy null_handling)
{
auto kind =
(null_handling == null_policy::INCLUDE) ? aggregation::COUNT_ALL : aggregation::COUNT_VALID;
return std::make_unique<detail::count_aggregation>(kind);
}
template std::unique_ptr<aggregation> make_count_aggregation<aggregation>(
null_policy null_handling);
template std::unique_ptr<rolling_aggregation> make_count_aggregation<rolling_aggregation>(
null_policy null_handling);
template std::unique_ptr<groupby_aggregation> make_count_aggregation<groupby_aggregation>(
null_policy null_handling);
template std::unique_ptr<groupby_scan_aggregation> make_count_aggregation<groupby_scan_aggregation>(
null_policy null_handling);
/// Factory to create a HISTOGRAM aggregation
template <typename Base>
std::unique_ptr<Base> make_histogram_aggregation()
{
return std::make_unique<detail::histogram_aggregation>();
}
template std::unique_ptr<aggregation> make_histogram_aggregation<aggregation>();
template std::unique_ptr<groupby_aggregation> make_histogram_aggregation<groupby_aggregation>();
template std::unique_ptr<reduce_aggregation> make_histogram_aggregation<reduce_aggregation>();
/// Factory to create a ANY aggregation
template <typename Base>
std::unique_ptr<Base> make_any_aggregation()
{
return std::make_unique<detail::any_aggregation>();
}
template std::unique_ptr<aggregation> make_any_aggregation<aggregation>();
template std::unique_ptr<reduce_aggregation> make_any_aggregation<reduce_aggregation>();
template std::unique_ptr<segmented_reduce_aggregation>
make_any_aggregation<segmented_reduce_aggregation>();
/// Factory to create a ALL aggregation
template <typename Base>
std::unique_ptr<Base> make_all_aggregation()
{
return std::make_unique<detail::all_aggregation>();
}
template std::unique_ptr<aggregation> make_all_aggregation<aggregation>();
template std::unique_ptr<reduce_aggregation> make_all_aggregation<reduce_aggregation>();
template std::unique_ptr<segmented_reduce_aggregation>
make_all_aggregation<segmented_reduce_aggregation>();
/// Factory to create a SUM_OF_SQUARES aggregation
template <typename Base>
std::unique_ptr<Base> make_sum_of_squares_aggregation()
{
return std::make_unique<detail::sum_of_squares_aggregation>();
}
template std::unique_ptr<aggregation> make_sum_of_squares_aggregation<aggregation>();
template std::unique_ptr<groupby_aggregation>
make_sum_of_squares_aggregation<groupby_aggregation>();
template std::unique_ptr<reduce_aggregation> make_sum_of_squares_aggregation<reduce_aggregation>();
template std::unique_ptr<segmented_reduce_aggregation>
make_sum_of_squares_aggregation<segmented_reduce_aggregation>();
/// Factory to create a MEAN aggregation
template <typename Base>
std::unique_ptr<Base> make_mean_aggregation()
{
return std::make_unique<detail::mean_aggregation>();
}
template std::unique_ptr<aggregation> make_mean_aggregation<aggregation>();
template std::unique_ptr<rolling_aggregation> make_mean_aggregation<rolling_aggregation>();
template std::unique_ptr<groupby_aggregation> make_mean_aggregation<groupby_aggregation>();
template std::unique_ptr<reduce_aggregation> make_mean_aggregation<reduce_aggregation>();
template std::unique_ptr<segmented_reduce_aggregation>
make_mean_aggregation<segmented_reduce_aggregation>();
/// Factory to create a M2 aggregation
template <typename Base>
std::unique_ptr<Base> make_m2_aggregation()
{
return std::make_unique<detail::m2_aggregation>();
}
template std::unique_ptr<aggregation> make_m2_aggregation<aggregation>();
template std::unique_ptr<groupby_aggregation> make_m2_aggregation<groupby_aggregation>();
/// Factory to create a VARIANCE aggregation
template <typename Base>
std::unique_ptr<Base> make_variance_aggregation(size_type ddof)
{
return std::make_unique<detail::var_aggregation>(ddof);
}
template std::unique_ptr<aggregation> make_variance_aggregation<aggregation>(size_type ddof);
template std::unique_ptr<rolling_aggregation> make_variance_aggregation<rolling_aggregation>(
size_type ddof);
template std::unique_ptr<groupby_aggregation> make_variance_aggregation<groupby_aggregation>(
size_type ddof);
template std::unique_ptr<reduce_aggregation> make_variance_aggregation<reduce_aggregation>(
size_type ddof);
template std::unique_ptr<segmented_reduce_aggregation>
make_variance_aggregation<segmented_reduce_aggregation>(size_type ddof);
/// Factory to create a STD aggregation
template <typename Base>
std::unique_ptr<Base> make_std_aggregation(size_type ddof)
{
return std::make_unique<detail::std_aggregation>(ddof);
}
template std::unique_ptr<aggregation> make_std_aggregation<aggregation>(size_type ddof);
template std::unique_ptr<rolling_aggregation> make_std_aggregation<rolling_aggregation>(
size_type ddof);
template std::unique_ptr<groupby_aggregation> make_std_aggregation<groupby_aggregation>(
size_type ddof);
template std::unique_ptr<reduce_aggregation> make_std_aggregation<reduce_aggregation>(
size_type ddof);
template std::unique_ptr<segmented_reduce_aggregation>
make_std_aggregation<segmented_reduce_aggregation>(size_type ddof);
/// Factory to create a MEDIAN aggregation
template <typename Base>
std::unique_ptr<Base> make_median_aggregation()
{
return std::make_unique<detail::median_aggregation>();
}
template std::unique_ptr<aggregation> make_median_aggregation<aggregation>();
template std::unique_ptr<groupby_aggregation> make_median_aggregation<groupby_aggregation>();
template std::unique_ptr<reduce_aggregation> make_median_aggregation<reduce_aggregation>();
/// Factory to create a QUANTILE aggregation
template <typename Base>
std::unique_ptr<Base> make_quantile_aggregation(std::vector<double> const& quantiles,
interpolation interp)
{
return std::make_unique<detail::quantile_aggregation>(quantiles, interp);
}
template std::unique_ptr<aggregation> make_quantile_aggregation<aggregation>(
std::vector<double> const& quantiles, interpolation interp);
template std::unique_ptr<groupby_aggregation> make_quantile_aggregation<groupby_aggregation>(
std::vector<double> const& quantiles, interpolation interp);
template std::unique_ptr<reduce_aggregation> make_quantile_aggregation<reduce_aggregation>(
std::vector<double> const& quantiles, interpolation interp);
/// Factory to create an ARGMAX aggregation
template <typename Base>
std::unique_ptr<Base> make_argmax_aggregation()
{
return std::make_unique<detail::argmax_aggregation>();
}
template std::unique_ptr<aggregation> make_argmax_aggregation<aggregation>();
template std::unique_ptr<rolling_aggregation> make_argmax_aggregation<rolling_aggregation>();
template std::unique_ptr<groupby_aggregation> make_argmax_aggregation<groupby_aggregation>();
/// Factory to create an ARGMIN aggregation
template <typename Base>
std::unique_ptr<Base> make_argmin_aggregation()
{
return std::make_unique<detail::argmin_aggregation>();
}
template std::unique_ptr<aggregation> make_argmin_aggregation<aggregation>();
template std::unique_ptr<rolling_aggregation> make_argmin_aggregation<rolling_aggregation>();
template std::unique_ptr<groupby_aggregation> make_argmin_aggregation<groupby_aggregation>();
/// Factory to create an NUNIQUE aggregation
template <typename Base>
std::unique_ptr<Base> make_nunique_aggregation(null_policy null_handling)
{
return std::make_unique<detail::nunique_aggregation>(null_handling);
}
template std::unique_ptr<aggregation> make_nunique_aggregation<aggregation>(
null_policy null_handling);
template std::unique_ptr<groupby_aggregation> make_nunique_aggregation<groupby_aggregation>(
null_policy null_handling);
template std::unique_ptr<reduce_aggregation> make_nunique_aggregation<reduce_aggregation>(
null_policy null_handling);
template std::unique_ptr<segmented_reduce_aggregation>
make_nunique_aggregation<segmented_reduce_aggregation>(null_policy null_handling);
/// Factory to create an NTH_ELEMENT aggregation
template <typename Base>
std::unique_ptr<Base> make_nth_element_aggregation(size_type n, null_policy null_handling)
{
return std::make_unique<detail::nth_element_aggregation>(n, null_handling);
}
template std::unique_ptr<aggregation> make_nth_element_aggregation<aggregation>(
size_type n, null_policy null_handling);
template std::unique_ptr<groupby_aggregation> make_nth_element_aggregation<groupby_aggregation>(
size_type n, null_policy null_handling);
template std::unique_ptr<reduce_aggregation> make_nth_element_aggregation<reduce_aggregation>(
size_type n, null_policy null_handling);
template std::unique_ptr<rolling_aggregation> make_nth_element_aggregation<rolling_aggregation>(
size_type n, null_policy null_handling);
/// Factory to create a ROW_NUMBER aggregation
template <typename Base>
std::unique_ptr<Base> make_row_number_aggregation()
{
return std::make_unique<detail::row_number_aggregation>();
}
template std::unique_ptr<aggregation> make_row_number_aggregation<aggregation>();
template std::unique_ptr<rolling_aggregation> make_row_number_aggregation<rolling_aggregation>();
/// Factory to create a RANK aggregation
template <typename Base>
std::unique_ptr<Base> make_rank_aggregation(rank_method method,
order column_order,
null_policy null_handling,
null_order null_precedence,
rank_percentage percentage)
{
return std::make_unique<detail::rank_aggregation>(
method, column_order, null_handling, null_precedence, percentage);
}
template std::unique_ptr<aggregation> make_rank_aggregation<aggregation>(
rank_method method,
order column_order,
null_policy null_handling,
null_order null_precedence,
rank_percentage percentage);
template std::unique_ptr<groupby_scan_aggregation> make_rank_aggregation<groupby_scan_aggregation>(
rank_method method,
order column_order,
null_policy null_handling,
null_order null_precedence,
rank_percentage percentage);
template std::unique_ptr<scan_aggregation> make_rank_aggregation<scan_aggregation>(
rank_method method,
order column_order,
null_policy null_handling,
null_order null_precedence,
rank_percentage percentage);
/// Factory to create a COLLECT_LIST aggregation
template <typename Base>
std::unique_ptr<Base> make_collect_list_aggregation(null_policy null_handling)
{
return std::make_unique<detail::collect_list_aggregation>(null_handling);
}
template std::unique_ptr<aggregation> make_collect_list_aggregation<aggregation>(
null_policy null_handling);
template std::unique_ptr<rolling_aggregation> make_collect_list_aggregation<rolling_aggregation>(
null_policy null_handling);
template std::unique_ptr<groupby_aggregation> make_collect_list_aggregation<groupby_aggregation>(
null_policy null_handling);
template std::unique_ptr<reduce_aggregation> make_collect_list_aggregation<reduce_aggregation>(
null_policy null_handling);
/// Factory to create a COLLECT_SET aggregation
template <typename Base>
std::unique_ptr<Base> make_collect_set_aggregation(null_policy null_handling,
null_equality nulls_equal,
nan_equality nans_equal)
{
return std::make_unique<detail::collect_set_aggregation>(null_handling, nulls_equal, nans_equal);
}
template std::unique_ptr<aggregation> make_collect_set_aggregation<aggregation>(
null_policy null_handling, null_equality nulls_equal, nan_equality nans_equal);
template std::unique_ptr<rolling_aggregation> make_collect_set_aggregation<rolling_aggregation>(
null_policy null_handling, null_equality nulls_equal, nan_equality nans_equal);
template std::unique_ptr<groupby_aggregation> make_collect_set_aggregation<groupby_aggregation>(
null_policy null_handling, null_equality nulls_equal, nan_equality nans_equal);
template std::unique_ptr<reduce_aggregation> make_collect_set_aggregation<reduce_aggregation>(
null_policy null_handling, null_equality nulls_equal, nan_equality nans_equal);
/// Factory to create a LAG aggregation
template <typename Base>
std::unique_ptr<Base> make_lag_aggregation(size_type offset)
{
return std::make_unique<detail::lead_lag_aggregation>(aggregation::LAG, offset);
}
template std::unique_ptr<aggregation> make_lag_aggregation<aggregation>(size_type offset);
template std::unique_ptr<rolling_aggregation> make_lag_aggregation<rolling_aggregation>(
size_type offset);
/// Factory to create a LEAD aggregation
template <typename Base>
std::unique_ptr<Base> make_lead_aggregation(size_type offset)
{
return std::make_unique<detail::lead_lag_aggregation>(aggregation::LEAD, offset);
}
template std::unique_ptr<aggregation> make_lead_aggregation<aggregation>(size_type offset);
template std::unique_ptr<rolling_aggregation> make_lead_aggregation<rolling_aggregation>(
size_type offset);
/// Factory to create a UDF aggregation
template <typename Base>
std::unique_ptr<Base> make_udf_aggregation(udf_type type,
std::string const& user_defined_aggregator,
data_type output_type)
{
auto* a =
new detail::udf_aggregation{type == udf_type::PTX ? aggregation::PTX : aggregation::CUDA,
user_defined_aggregator,
output_type};
return std::unique_ptr<detail::udf_aggregation>(a);
}
template std::unique_ptr<aggregation> make_udf_aggregation<aggregation>(
udf_type type, std::string const& user_defined_aggregator, data_type output_type);
template std::unique_ptr<rolling_aggregation> make_udf_aggregation<rolling_aggregation>(
udf_type type, std::string const& user_defined_aggregator, data_type output_type);
/// Factory to create a MERGE_LISTS aggregation
template <typename Base>
std::unique_ptr<Base> make_merge_lists_aggregation()
{
return std::make_unique<detail::merge_lists_aggregation>();
}
template std::unique_ptr<aggregation> make_merge_lists_aggregation<aggregation>();
template std::unique_ptr<groupby_aggregation> make_merge_lists_aggregation<groupby_aggregation>();
template std::unique_ptr<reduce_aggregation> make_merge_lists_aggregation<reduce_aggregation>();
/// Factory to create a MERGE_SETS aggregation
template <typename Base>
std::unique_ptr<Base> make_merge_sets_aggregation(null_equality nulls_equal,
nan_equality nans_equal)
{
return std::make_unique<detail::merge_sets_aggregation>(nulls_equal, nans_equal);
}
template std::unique_ptr<aggregation> make_merge_sets_aggregation<aggregation>(null_equality,
nan_equality);
template std::unique_ptr<groupby_aggregation> make_merge_sets_aggregation<groupby_aggregation>(
null_equality, nan_equality);
template std::unique_ptr<reduce_aggregation> make_merge_sets_aggregation<reduce_aggregation>(
null_equality, nan_equality);
/// Factory to create a MERGE_M2 aggregation
template <typename Base>
std::unique_ptr<Base> make_merge_m2_aggregation()
{
return std::make_unique<detail::merge_m2_aggregation>();
}
template std::unique_ptr<aggregation> make_merge_m2_aggregation<aggregation>();
template std::unique_ptr<groupby_aggregation> make_merge_m2_aggregation<groupby_aggregation>();
/// Factory to create a MERGE_HISTOGRAM aggregation
template <typename Base>
std::unique_ptr<Base> make_merge_histogram_aggregation()
{
return std::make_unique<detail::merge_histogram_aggregation>();
}
template std::unique_ptr<aggregation> make_merge_histogram_aggregation<aggregation>();
template std::unique_ptr<groupby_aggregation>
make_merge_histogram_aggregation<groupby_aggregation>();
template std::unique_ptr<reduce_aggregation> make_merge_histogram_aggregation<reduce_aggregation>();
/// Factory to create a COVARIANCE aggregation
template <typename Base>
std::unique_ptr<Base> make_covariance_aggregation(size_type min_periods, size_type ddof)
{
return std::make_unique<detail::covariance_aggregation>(min_periods, ddof);
}
template std::unique_ptr<aggregation> make_covariance_aggregation<aggregation>(
size_type min_periods, size_type ddof);
template std::unique_ptr<groupby_aggregation> make_covariance_aggregation<groupby_aggregation>(
size_type min_periods, size_type ddof);
/// Factory to create a CORRELATION aggregation
template <typename Base>
std::unique_ptr<Base> make_correlation_aggregation(correlation_type type, size_type min_periods)
{
return std::make_unique<detail::correlation_aggregation>(type, min_periods);
}
template std::unique_ptr<aggregation> make_correlation_aggregation<aggregation>(
correlation_type type, size_type min_periods);
template std::unique_ptr<groupby_aggregation> make_correlation_aggregation<groupby_aggregation>(
correlation_type type, size_type min_periods);
template <typename Base>
std::unique_ptr<Base> make_tdigest_aggregation(int max_centroids)
{
return std::make_unique<detail::tdigest_aggregation>(max_centroids);
}
template std::unique_ptr<aggregation> make_tdigest_aggregation<aggregation>(int max_centroids);
template std::unique_ptr<groupby_aggregation> make_tdigest_aggregation<groupby_aggregation>(
int max_centroids);
template std::unique_ptr<reduce_aggregation> make_tdigest_aggregation<reduce_aggregation>(
int max_centroids);
template <typename Base>
std::unique_ptr<Base> make_merge_tdigest_aggregation(int max_centroids)
{
return std::make_unique<detail::merge_tdigest_aggregation>(max_centroids);
}
template std::unique_ptr<aggregation> make_merge_tdigest_aggregation<aggregation>(
int max_centroids);
template std::unique_ptr<groupby_aggregation> make_merge_tdigest_aggregation<groupby_aggregation>(
int max_centroids);
template std::unique_ptr<reduce_aggregation> make_merge_tdigest_aggregation<reduce_aggregation>(
int max_centroids);
namespace detail {
namespace {
struct target_type_functor {
data_type type;
template <typename Source, aggregation::Kind k>
constexpr data_type operator()() const noexcept
{
using Type = target_type_t<Source, k>;
auto const id = type_to_id<Type>();
return cudf::is_fixed_point<Type>() ? data_type{id, type.scale()} : data_type{id};
}
};
struct is_valid_aggregation_impl {
template <typename Source, aggregation::Kind k>
constexpr bool operator()() const noexcept
{
return is_valid_aggregation<Source, k>();
}
};
} // namespace
// Return target data_type for the given source_type and aggregation
data_type target_type(data_type source, aggregation::Kind k)
{
return dispatch_type_and_aggregation(source, k, target_type_functor{source});
}
// Verifies the aggregation `k` is valid on the type `source`
bool is_valid_aggregation(data_type source, aggregation::Kind k)
{
return dispatch_type_and_aggregation(source, k, is_valid_aggregation_impl{});
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/aggregation/result_cache.cpp
|
/*
* Copyright (c) 2019, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/aggregation/result_cache.hpp>
namespace cudf {
namespace detail {
bool result_cache::has_result(column_view const& input, aggregation const& agg) const
{
return _cache.count({input, agg});
}
void result_cache::add_result(column_view const& input,
aggregation const& agg,
std::unique_ptr<column>&& col)
{
// We can't guarantee that agg will outlive the cache, so we need to take ownership of a copy.
// To allow lookup by reference, make the key a reference and keep the owner in the value pair.
auto owned_agg = agg.clone();
auto const& key = *owned_agg;
// try_emplace doesn't update/insert if already present
_cache.try_emplace({input, key}, std::move(owned_agg), std::move(col));
}
column_view result_cache::get_result(column_view const& input, aggregation const& agg) const
{
auto result_it = _cache.find({input, agg});
CUDF_EXPECTS(result_it != _cache.end(), "Result does not exist in cache");
return result_it->second.second->view();
}
std::unique_ptr<column> result_cache::release_result(column_view const& input,
aggregation const& agg)
{
auto node = _cache.extract({input, agg});
CUDF_EXPECTS(not node.empty(), "Result does not exist in cache");
return std::move(node.mapped().second);
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/aggregation/aggregation.cu
|
/*
* Copyright (c) 2020-2021, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/aggregation/aggregation.cuh>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace detail {
void initialize_with_identity(mutable_table_view& table,
std::vector<aggregation::Kind> const& aggs,
rmm::cuda_stream_view stream)
{
// TODO: Initialize all the columns in a single kernel instead of invoking one
// kernel per column
for (size_type i = 0; i < table.num_columns(); ++i) {
auto col = table.column(i);
dispatch_type_and_aggregation(col.type(), aggs[i], identity_initializer{}, col, stream);
}
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/round/round.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_factories.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/copy_range.cuh>
#include <cudf/detail/fill.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/round.hpp>
#include <cudf/detail/unary.hpp>
#include <cudf/fixed_point/fixed_point.hpp>
#include <cudf/fixed_point/temporary.hpp>
#include <cudf/round.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/transform.h>
#include <thrust/uninitialized_fill.h>
#include <type_traits>
namespace cudf {
namespace detail {
namespace { // anonymous
inline float __device__ generic_round(float f) { return roundf(f); }
inline double __device__ generic_round(double d) { return ::round(d); }
inline float __device__ generic_round_half_even(float f) { return rintf(f); }
inline double __device__ generic_round_half_even(double d) { return rint(d); }
inline float __device__ generic_modf(float a, float* b) { return modff(a, b); }
inline double __device__ generic_modf(double a, double* b) { return modf(a, b); }
template <typename T, std::enable_if_t<cuda::std::is_signed_v<T>>* = nullptr>
T __device__ generic_abs(T value)
{
return numeric::detail::abs(value);
}
template <typename T, std::enable_if_t<not cuda::std::is_signed_v<T>>* = nullptr>
T __device__ generic_abs(T value)
{
return value;
}
template <typename T, std::enable_if_t<cuda::std::is_signed_v<T>>* = nullptr>
int16_t __device__ generic_sign(T value)
{
return value < 0 ? -1 : 1;
}
// this is needed to suppress warning: pointless comparison of unsigned integer with zero
template <typename T, std::enable_if_t<not cuda::std::is_signed_v<T>>* = nullptr>
int16_t __device__ generic_sign(T)
{
return 1;
}
template <typename T>
constexpr inline auto is_supported_round_type()
{
return (cudf::is_numeric<T>() && not std::is_same_v<T, bool>) || cudf::is_fixed_point<T>();
}
template <typename T>
struct half_up_zero {
T n; // unused in the decimal_places = 0 case
template <typename U = T, std::enable_if_t<cudf::is_floating_point<U>()>* = nullptr>
__device__ U operator()(U e)
{
return generic_round(e);
}
template <typename U = T, std::enable_if_t<cuda::std::is_integral_v<U>>* = nullptr>
__device__ U operator()(U)
{
assert(false); // Should never get here. Just for compilation
return U{};
}
};
template <typename T>
struct half_up_positive {
T n;
template <typename U = T, std::enable_if_t<cudf::is_floating_point<U>()>* = nullptr>
__device__ U operator()(U e)
{
T integer_part;
T const fractional_part = generic_modf(e, &integer_part);
return integer_part + generic_round(fractional_part * n) / n;
}
template <typename U = T, std::enable_if_t<cuda::std::is_integral_v<U>>* = nullptr>
__device__ U operator()(U)
{
assert(false); // Should never get here. Just for compilation
return U{};
}
};
template <typename T>
struct half_up_negative {
T n;
template <typename U = T, std::enable_if_t<cudf::is_floating_point<U>()>* = nullptr>
__device__ U operator()(U e)
{
return generic_round(e / n) * n;
}
template <typename U = T, std::enable_if_t<cuda::std::is_integral_v<U>>* = nullptr>
__device__ U operator()(U e)
{
auto const down = (e / n) * n; // result from rounding down
return down + generic_sign(e) * (generic_abs(e - down) >= n / 2 ? n : 0);
}
};
template <typename T>
struct half_even_zero {
T n; // unused in the decimal_places = 0 case
template <typename U = T, std::enable_if_t<cudf::is_floating_point<U>()>* = nullptr>
__device__ U operator()(U e)
{
return generic_round_half_even(e);
}
template <typename U = T, std::enable_if_t<cuda::std::is_integral_v<U>>* = nullptr>
__device__ U operator()(U)
{
assert(false); // Should never get here. Just for compilation
return U{};
}
};
template <typename T>
struct half_even_positive {
T n;
template <typename U = T, std::enable_if_t<cudf::is_floating_point<U>()>* = nullptr>
__device__ U operator()(U e)
{
T integer_part;
T const fractional_part = generic_modf(e, &integer_part);
return integer_part + generic_round_half_even(fractional_part * n) / n;
}
template <typename U = T, std::enable_if_t<cuda::std::is_integral_v<U>>* = nullptr>
__device__ U operator()(U)
{
assert(false); // Should never get here. Just for compilation
return U{};
}
};
template <typename T>
struct half_even_negative {
T n;
template <typename U = T, std::enable_if_t<cudf::is_floating_point<U>()>* = nullptr>
__device__ U operator()(U e)
{
return generic_round_half_even(e / n) * n;
}
template <typename U = T, std::enable_if_t<cuda::std::is_integral_v<U>>* = nullptr>
__device__ U operator()(U e)
{
auto const down_over_n = e / n; // use this to determine HALF_EVEN case
auto const down = down_over_n * n; // result from rounding down
auto const diff = generic_abs(e - down);
auto const adjustment =
(diff > n / 2) or (diff == n / 2 && generic_abs(down_over_n) % 2 == 1) ? n : 0;
return down + generic_sign(e) * adjustment;
}
};
template <typename T>
struct half_up_fixed_point {
T n;
__device__ T operator()(T e) { return half_up_negative<T>{n}(e) / n; }
};
template <typename T>
struct half_even_fixed_point {
T n;
__device__ T operator()(T e) { return half_even_negative<T>{n}(e) / n; }
};
template <typename T,
template <typename>
typename RoundFunctor,
std::enable_if_t<not cudf::is_fixed_point<T>()>* = nullptr>
std::unique_ptr<column> round_with(column_view const& input,
int32_t decimal_places,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using Functor = RoundFunctor<T>;
if (decimal_places >= 0 && std::is_integral_v<T>)
return std::make_unique<cudf::column>(input, stream, mr);
auto result = cudf::make_fixed_width_column(input.type(),
input.size(),
detail::copy_bitmask(input, stream, mr),
input.null_count(),
stream,
mr);
auto out_view = result->mutable_view();
T const n = std::pow(10, std::abs(decimal_places));
thrust::transform(
rmm::exec_policy(stream), input.begin<T>(), input.end<T>(), out_view.begin<T>(), Functor{n});
result->set_null_count(input.null_count());
return result;
}
template <typename T,
template <typename>
typename RoundFunctor,
std::enable_if_t<cudf::is_fixed_point<T>()>* = nullptr>
std::unique_ptr<column> round_with(column_view const& input,
int32_t decimal_places,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using namespace numeric;
using Type = device_storage_type_t<T>;
using FixedPointRoundFunctor = RoundFunctor<Type>;
if (input.type().scale() == -decimal_places)
return std::make_unique<cudf::column>(input, stream, mr);
auto const result_type = data_type{input.type().id(), scale_type{-decimal_places}};
// if rounding to more precision than fixed_point is capable of, just need to rescale
// note: decimal_places has the opposite sign of numeric::scale_type (therefore have to negate)
if (input.type().scale() > -decimal_places)
return cudf::detail::cast(input, result_type, stream, mr);
auto result = cudf::make_fixed_width_column(result_type,
input.size(),
detail::copy_bitmask(input, stream, mr),
input.null_count(),
stream,
mr);
auto out_view = result->mutable_view();
auto const scale_movement = -decimal_places - input.type().scale();
// If scale_movement is larger than max precision of current type, the pow operation will
// overflow. Under this circumstance, we can simply output a zero column because no digits can
// survive such a large scale movement.
if (scale_movement > cuda::std::numeric_limits<Type>::digits10) {
thrust::uninitialized_fill(rmm::exec_policy(stream),
out_view.template begin<Type>(),
out_view.template end<Type>(),
static_cast<Type>(0));
} else {
Type n = 10;
for (int i = 1; i < scale_movement; ++i) {
n *= 10;
}
thrust::transform(rmm::exec_policy(stream),
input.begin<Type>(),
input.end<Type>(),
out_view.begin<Type>(),
FixedPointRoundFunctor{n});
}
result->set_null_count(input.null_count());
return result;
}
struct round_type_dispatcher {
template <typename T, typename... Args>
std::enable_if_t<not is_supported_round_type<T>(), std::unique_ptr<column>> operator()(Args&&...)
{
CUDF_FAIL("Type not support for cudf::round");
}
template <typename T>
std::enable_if_t<is_supported_round_type<T>(), std::unique_ptr<column>> operator()(
column_view const& input,
int32_t decimal_places,
cudf::rounding_method method,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// clang-format off
switch (method) {
case cudf::rounding_method::HALF_UP:
if (is_fixed_point<T>()) return round_with<T, half_up_fixed_point>(input, decimal_places, stream, mr);
else if (decimal_places == 0) return round_with<T, half_up_zero >(input, decimal_places, stream, mr);
else if (decimal_places > 0) return round_with<T, half_up_positive >(input, decimal_places, stream, mr);
else return round_with<T, half_up_negative >(input, decimal_places, stream, mr);
case cudf::rounding_method::HALF_EVEN:
if (is_fixed_point<T>()) return round_with<T, half_even_fixed_point>(input, decimal_places, stream, mr);
else if (decimal_places == 0) return round_with<T, half_even_zero >(input, decimal_places, stream, mr);
else if (decimal_places > 0) return round_with<T, half_even_positive >(input, decimal_places, stream, mr);
else return round_with<T, half_even_negative >(input, decimal_places, stream, mr);
default: CUDF_FAIL("Undefined rounding method");
}
// clang-format on
}
};
} // anonymous namespace
std::unique_ptr<column> round(column_view const& input,
int32_t decimal_places,
cudf::rounding_method method,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(cudf::is_numeric(input.type()) || cudf::is_fixed_point(input.type()),
"Only integral/floating point/fixed point currently supported.");
if (input.is_empty()) {
if (is_fixed_point(input.type())) {
auto const type = data_type{input.type().id(), numeric::scale_type{-decimal_places}};
return make_empty_column(type);
}
return empty_like(input);
}
return type_dispatcher(
input.type(), round_type_dispatcher{}, input, decimal_places, method, stream, mr);
}
} // namespace detail
std::unique_ptr<column> round(column_view const& input,
int32_t decimal_places,
rounding_method method,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::round(input, decimal_places, method, cudf::get_default_stream(), mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/pack.cpp
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/contiguous_split.hpp>
#include <cudf/detail/contiguous_split.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace detail {
namespace {
/**
* @brief The data that is stored as anonymous bytes in the `packed_columns` metadata
* field.
*
* The metadata field of the `packed_columns` struct is simply an array of these.
* This struct is exposed here because it is needed by both contiguous_split, pack
* and unpack.
*/
struct serialized_column {
serialized_column() = default;
serialized_column(data_type _type,
size_type _size,
size_type _null_count,
int64_t _data_offset,
int64_t _null_mask_offset,
size_type _num_children)
: type(_type),
size(_size),
null_count(_null_count),
data_offset(_data_offset),
null_mask_offset(_null_mask_offset),
num_children(_num_children),
pad(0)
{
}
data_type type;
size_type size;
size_type null_count;
int64_t data_offset; // offset into contiguous data buffer, or -1 if column data is null
int64_t null_mask_offset; // offset into contiguous data buffer, or -1 if column data is null
size_type num_children;
// Explicitly pad to avoid uninitialized padding bits, allowing `serialized_column` to be bit-wise
// comparable
int pad;
};
/**
* @brief Deserialize a single column into a column_view
*
* Deserializes a single column (it's children are assumed to be already deserialized)
* non-recursively.
*
* @param serial_column Serialized column information
* @param children Children for the column
* @param base_ptr Base pointer for the entire contiguous buffer from which all columns
* were serialized into
* @return Fully formed column_view
*/
column_view deserialize_column(serialized_column serial_column,
std::vector<column_view> const& children,
uint8_t const* base_ptr)
{
auto const data_ptr =
serial_column.data_offset != -1 ? base_ptr + serial_column.data_offset : nullptr;
auto const null_mask_ptr =
serial_column.null_mask_offset != -1
? reinterpret_cast<bitmask_type const*>(base_ptr + serial_column.null_mask_offset)
: nullptr;
return column_view(serial_column.type,
serial_column.size,
data_ptr,
null_mask_ptr,
serial_column.null_count,
0,
children);
}
/**
* @brief Build and add metadata for a column and all of it's children, recursively
*
*
* @param mb metadata_builder instance
* @param col Column to build metadata for
* @param base_ptr Base pointer for the entire contiguous buffer from which all columns
* were serialized into
* @param data_size Size of the incoming buffer
*/
void build_column_metadata(metadata_builder& mb,
column_view const& col,
uint8_t const* base_ptr,
size_t data_size)
{
uint8_t const* data_ptr = col.size() == 0 || !col.head<uint8_t>() ? nullptr : col.head<uint8_t>();
if (data_ptr != nullptr) {
CUDF_EXPECTS(data_ptr >= base_ptr && data_ptr < base_ptr + data_size,
"Encountered column data outside the range of input buffer");
}
int64_t const data_offset = data_ptr ? data_ptr - base_ptr : -1;
uint8_t const* null_mask_ptr = col.size() == 0 || !col.nullable()
? nullptr
: reinterpret_cast<uint8_t const*>(col.null_mask());
if (null_mask_ptr != nullptr) {
CUDF_EXPECTS(null_mask_ptr >= base_ptr && null_mask_ptr < base_ptr + data_size,
"Encountered column null mask outside the range of input buffer");
}
int64_t const null_mask_offset = null_mask_ptr ? null_mask_ptr - base_ptr : -1;
// add metadata
mb.add_column_info_to_meta(
col.type(), col.size(), col.null_count(), data_offset, null_mask_offset, col.num_children());
std::for_each(
col.child_begin(), col.child_end(), [&mb, &base_ptr, &data_size](column_view const& col) {
build_column_metadata(mb, col, base_ptr, data_size);
});
}
} // anonymous namespace
/**
* @copydoc cudf::detail::pack
*/
packed_columns pack(cudf::table_view const& input,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// do a contiguous_split with no splits to get the memory for the table
// arranged as we want it
auto contig_split_result = cudf::detail::contiguous_split(input, {}, stream, mr);
return contig_split_result.empty() ? packed_columns{} : std::move(contig_split_result[0].data);
}
std::vector<uint8_t> pack_metadata(table_view const& table,
uint8_t const* contiguous_buffer,
size_t buffer_size,
metadata_builder& builder)
{
std::for_each(
table.begin(), table.end(), [&builder, contiguous_buffer, buffer_size](column_view const& col) {
build_column_metadata(builder, col, contiguous_buffer, buffer_size);
});
return builder.build();
}
class metadata_builder_impl {
public:
metadata_builder_impl(size_type const num_root_columns) { metadata.reserve(num_root_columns); }
void add_column_info_to_meta(data_type const col_type,
size_type const col_size,
size_type const col_null_count,
int64_t const data_offset,
int64_t const null_mask_offset,
size_type const num_children)
{
metadata.emplace_back(
col_type, col_size, col_null_count, data_offset, null_mask_offset, num_children);
}
std::vector<uint8_t> build() const
{
auto output = std::vector<uint8_t>(metadata.size() * sizeof(detail::serialized_column));
std::memcpy(output.data(), metadata.data(), output.size());
return output;
}
void clear()
{
// Clear all, except the first metadata entry storing the number of top level columns that
// was added upon object construction.
metadata.resize(1);
}
private:
std::vector<detail::serialized_column> metadata;
};
/**
* @copydoc cudf::detail::unpack
*/
table_view unpack(uint8_t const* metadata, uint8_t const* gpu_data)
{
// gpu data can be null if everything is empty but the metadata must always be valid
CUDF_EXPECTS(metadata != nullptr, "Encountered invalid packed column input");
auto serialized_columns = reinterpret_cast<serialized_column const*>(metadata);
uint8_t const* base_ptr = gpu_data;
// first entry is a stub where size == the total # of top level columns (see pack_metadata above)
auto const num_columns = serialized_columns[0].size;
size_t current_index = 1;
std::function<std::vector<column_view>(size_type)> get_columns;
get_columns = [&serialized_columns, ¤t_index, base_ptr, &get_columns](size_t num_columns) {
std::vector<column_view> cols;
for (size_t i = 0; i < num_columns; i++) {
auto serial_column = serialized_columns[current_index];
current_index++;
std::vector<column_view> children = get_columns(serial_column.num_children);
cols.emplace_back(deserialize_column(serial_column, children, base_ptr));
}
return cols;
};
return table_view{get_columns(num_columns)};
}
metadata_builder::metadata_builder(size_type const num_root_columns)
: impl(std::make_unique<metadata_builder_impl>(num_root_columns +
1 /*one more extra metadata entry as below*/))
{
// first metadata entry is a stub indicating how many total (top level) columns
// there are
impl->add_column_info_to_meta(data_type{type_id::EMPTY}, num_root_columns, 0, -1, -1, 0);
}
metadata_builder::~metadata_builder() = default;
void metadata_builder::add_column_info_to_meta(data_type const col_type,
size_type const col_size,
size_type const col_null_count,
int64_t const data_offset,
int64_t const null_mask_offset,
size_type const num_children)
{
impl->add_column_info_to_meta(
col_type, col_size, col_null_count, data_offset, null_mask_offset, num_children);
}
std::vector<uint8_t> metadata_builder::build() const { return impl->build(); }
void metadata_builder::clear() { return impl->clear(); }
} // namespace detail
/**
* @copydoc cudf::pack
*/
packed_columns pack(cudf::table_view const& input, rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::pack(input, cudf::get_default_stream(), mr);
}
/**
* @copydoc cudf::pack_metadata
*/
std::vector<uint8_t> pack_metadata(table_view const& table,
uint8_t const* contiguous_buffer,
size_t buffer_size)
{
CUDF_FUNC_RANGE();
if (table.is_empty()) { return std::vector<uint8_t>{}; }
auto builder = cudf::detail::metadata_builder(table.num_columns());
return detail::pack_metadata(table, contiguous_buffer, buffer_size, builder);
}
/**
* @copydoc cudf::unpack
*/
table_view unpack(packed_columns const& input)
{
CUDF_FUNC_RANGE();
return input.metadata->size() == 0
? table_view{}
: detail::unpack(input.metadata->data(),
reinterpret_cast<uint8_t const*>(input.gpu_data->data()));
}
/**
* @copydoc cudf::unpack(uint8_t const*, uint8_t const* )
*/
table_view unpack(uint8_t const* metadata, uint8_t const* gpu_data)
{
CUDF_FUNC_RANGE();
return detail::unpack(metadata, gpu_data);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/scatter.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/indexalator.cuh>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/scatter.cuh>
#include <cudf/detail/scatter.hpp>
#include <cudf/detail/stream_compaction.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/dictionary/detail/search.hpp>
#include <cudf/lists/list_view.hpp>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/strings/detail/scatter.cuh>
#include <cudf/strings/string_view.cuh>
#include <cudf/structs/struct_view.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/count.h>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/permutation_iterator.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/scatter.h>
#include <thrust/sequence.h>
namespace cudf {
namespace detail {
namespace {
template <bool mark_true, typename MapIterator>
__global__ void marking_bitmask_kernel(mutable_column_device_view destination,
MapIterator scatter_map,
size_type num_scatter_rows)
{
auto row = cudf::detail::grid_1d::global_thread_id();
auto const stride = cudf::detail::grid_1d::grid_stride();
while (row < num_scatter_rows) {
size_type const output_row = scatter_map[row];
if (mark_true) {
destination.set_valid(output_row);
} else {
destination.set_null(output_row);
}
row += stride;
}
}
template <typename MapIterator>
void scatter_scalar_bitmask_inplace(std::reference_wrapper<scalar const> const& source,
MapIterator scatter_map,
size_type num_scatter_rows,
column& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
constexpr size_type block_size = 256;
size_type const grid_size = grid_1d(num_scatter_rows, block_size).num_blocks;
auto const source_is_valid = source.get().is_valid(stream);
if (target.nullable() or not source_is_valid) {
if (not target.nullable()) {
// Target must have a null mask if the source is not valid
auto mask = detail::create_null_mask(target.size(), mask_state::ALL_VALID, stream, mr);
target.set_null_mask(std::move(mask), 0);
}
auto target_view = mutable_column_device_view::create(target, stream);
auto bitmask_kernel = source_is_valid ? marking_bitmask_kernel<true, decltype(scatter_map)>
: marking_bitmask_kernel<false, decltype(scatter_map)>;
bitmask_kernel<<<grid_size, block_size, 0, stream.value()>>>(
*target_view, scatter_map, num_scatter_rows);
target.set_null_count(
cudf::detail::null_count(target.view().null_mask(), 0, target.size(), stream));
}
}
template <typename Element, typename MapIterator>
struct column_scalar_scatterer_impl {
std::unique_ptr<column> operator()(std::reference_wrapper<scalar const> const& source,
MapIterator scatter_iter,
size_type scatter_rows,
column_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
CUDF_EXPECTS(source.get().type() == target.type(), "scalar and column types must match");
// make a copy of data and null mask from source
auto result = std::make_unique<column>(target, stream, mr);
auto result_view = result->mutable_view();
// Use permutation iterator with constant index to dereference scalar data
auto scalar_impl = static_cast<scalar_type_t<Element> const*>(&source.get());
auto scalar_iter =
thrust::make_permutation_iterator(scalar_impl->data(), thrust::make_constant_iterator(0));
thrust::scatter(rmm::exec_policy_nosync(stream),
scalar_iter,
scalar_iter + scatter_rows,
scatter_iter,
result_view.begin<Element>());
scatter_scalar_bitmask_inplace(source, scatter_iter, scatter_rows, *result, stream, mr);
return result;
}
};
template <typename MapIterator>
struct column_scalar_scatterer_impl<string_view, MapIterator> {
std::unique_ptr<column> operator()(std::reference_wrapper<scalar const> const& source,
MapIterator scatter_iter,
size_type scatter_rows,
column_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
CUDF_EXPECTS(source.get().type() == target.type(), "scalar and column types must match");
auto const scalar_impl = static_cast<string_scalar const*>(&source.get());
auto const source_view = string_view(scalar_impl->data(), scalar_impl->size());
auto const begin = thrust::make_constant_iterator(source_view);
auto const end = begin + scatter_rows;
auto result = strings::detail::scatter(begin, end, scatter_iter, target, stream, mr);
scatter_scalar_bitmask_inplace(source, scatter_iter, scatter_rows, *result, stream, mr);
return result;
}
};
template <typename MapIterator>
struct column_scalar_scatterer_impl<list_view, MapIterator> {
std::unique_ptr<column> operator()(std::reference_wrapper<scalar const> const& source,
MapIterator scatter_iter,
size_type scatter_rows,
column_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
auto result =
lists::detail::scatter(source, scatter_iter, scatter_iter + scatter_rows, target, stream, mr);
scatter_scalar_bitmask_inplace(source, scatter_iter, scatter_rows, *result, stream, mr);
return result;
}
};
template <typename MapIterator>
struct column_scalar_scatterer_impl<dictionary32, MapIterator> {
std::unique_ptr<column> operator()(std::reference_wrapper<scalar const> const& source,
MapIterator scatter_iter,
size_type scatter_rows,
column_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
auto dict_target =
dictionary::detail::add_keys(dictionary_column_view(target),
make_column_from_scalar(source.get(), 1, stream)->view(),
stream,
mr);
auto dict_view = dictionary_column_view(dict_target->view());
auto scalar_index = dictionary::detail::get_index(
dict_view, source.get(), stream, rmm::mr::get_current_device_resource());
auto scalar_iter = thrust::make_permutation_iterator(
indexalator_factory::make_input_iterator(*scalar_index), thrust::make_constant_iterator(0));
auto new_indices = std::make_unique<column>(dict_view.get_indices_annotated(), stream, mr);
auto target_iter = indexalator_factory::make_output_iterator(new_indices->mutable_view());
thrust::scatter(rmm::exec_policy_nosync(stream),
scalar_iter,
scalar_iter + scatter_rows,
scatter_iter,
target_iter);
// build the dictionary indices column from the result
auto const indices_type = new_indices->type();
auto const output_size = new_indices->size();
auto const null_count = new_indices->null_count();
auto contents = new_indices->release();
auto indices_column = std::make_unique<column>(indices_type,
static_cast<size_type>(output_size),
std::move(*(contents.data.release())),
rmm::device_buffer{},
0);
// use the keys from the matched column
std::unique_ptr<column> keys_column(std::move(dict_target->release().children.back()));
// create the output column
auto result = make_dictionary_column(std::move(keys_column),
std::move(indices_column),
std::move(*(contents.null_mask.release())),
null_count);
scatter_scalar_bitmask_inplace(source, scatter_iter, scatter_rows, *result, stream, mr);
return result;
}
};
template <typename MapIterator>
struct column_scalar_scatterer {
template <typename Element>
std::unique_ptr<column> operator()(std::reference_wrapper<scalar const> const& source,
MapIterator scatter_iter,
size_type scatter_rows,
column_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
column_scalar_scatterer_impl<Element, MapIterator> scatterer{};
return scatterer(source, scatter_iter, scatter_rows, target, stream, mr);
}
};
template <typename MapIterator>
struct column_scalar_scatterer_impl<struct_view, MapIterator> {
std::unique_ptr<column> operator()(std::reference_wrapper<scalar const> const& source,
MapIterator scatter_iter,
size_type scatter_rows,
column_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
// For each field of `source`, copy construct a scalar from the field
// and dispatch to the corresponding scalar scatterer
auto typed_s = static_cast<struct_scalar const*>(&source.get());
size_type const n_fields = typed_s->view().num_columns();
CUDF_EXPECTS(n_fields == target.num_children(), "Mismatched number of fields.");
auto scatter_functor = column_scalar_scatterer<decltype(scatter_iter)>{};
auto fields_iter_begin = make_counting_transform_iterator(0, [&](auto const& i) {
auto row_slr = detail::get_element(
typed_s->view().column(i), 0, stream, rmm::mr::get_current_device_resource());
return type_dispatcher<dispatch_storage_type>(row_slr->type(),
scatter_functor,
*row_slr,
scatter_iter,
scatter_rows,
target.child(i),
stream,
mr);
});
std::vector<std::unique_ptr<column>> fields(fields_iter_begin, fields_iter_begin + n_fields);
// Compute null mask
rmm::device_buffer null_mask =
target.nullable()
? detail::copy_bitmask(target, stream, mr)
: detail::create_null_mask(target.size(), mask_state::UNALLOCATED, stream, mr);
column null_mask_stub(data_type{type_id::STRUCT},
target.size(),
rmm::device_buffer{},
std::move(null_mask),
target.null_count());
scatter_scalar_bitmask_inplace(source, scatter_iter, scatter_rows, null_mask_stub, stream, mr);
size_type null_count = null_mask_stub.null_count();
auto contents = null_mask_stub.release();
// Null mask pushdown inside factory method
return make_structs_column(
target.size(), std::move(fields), null_count, std::move(*contents.null_mask), stream, mr);
}
};
} // namespace
std::unique_ptr<table> scatter(table_view const& source,
column_view const& scatter_map,
table_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(source.num_columns() == target.num_columns(),
"Number of columns in source and target not equal");
CUDF_EXPECTS(scatter_map.size() <= source.num_rows(),
"Size of scatter map must be equal to or less than source rows");
CUDF_EXPECTS(std::equal(source.begin(),
source.end(),
target.begin(),
[](auto const& col1, auto const& col2) {
return col1.type().id() == col2.type().id();
}),
"Column types do not match between source and target");
CUDF_EXPECTS(not scatter_map.has_nulls(), "Scatter map contains nulls");
if (scatter_map.is_empty()) { return std::make_unique<table>(target, stream, mr); }
// create index type normalizing iterator for the scatter_map
auto map_begin = indexalator_factory::make_input_iterator(scatter_map);
auto map_end = map_begin + scatter_map.size();
return detail::scatter(source, map_begin, map_end, target, stream, mr);
}
std::unique_ptr<table> scatter(table_view const& source,
device_span<size_type const> const scatter_map,
table_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(scatter_map.size() <= static_cast<size_t>(std::numeric_limits<size_type>::max()),
"scatter map size exceeds the column size limit",
std::overflow_error);
auto map_col = column_view(data_type{type_to_id<size_type>()},
static_cast<size_type>(scatter_map.size()),
scatter_map.data(),
nullptr,
0);
return detail::scatter(source, map_col, target, stream, mr);
}
std::unique_ptr<table> scatter(std::vector<std::reference_wrapper<scalar const>> const& source,
column_view const& indices,
table_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(source.size() == static_cast<size_t>(target.num_columns()),
"Number of columns in source and target not equal");
CUDF_EXPECTS(not indices.has_nulls(), "indices contains nulls");
if (indices.is_empty()) { return std::make_unique<table>(target, stream, mr); }
// Create normalizing iterator for indices column
auto map_begin = indexalator_factory::make_input_iterator(indices);
// Optionally check map index values are within the number of target rows.
auto const n_rows = target.num_rows();
// Transform negative indices to index + target size
auto scatter_rows = indices.size();
// note: the intermediate ((in % n_rows) + n_rows) will overflow a size_type for any value of `in`
// > (2^31)/2, but the end result after the final (% n_rows) will fit. so we'll do the computation
// using a signed 64 bit value.
auto scatter_iter = thrust::make_transform_iterator(
map_begin, [n_rows = static_cast<int64_t>(n_rows)] __device__(size_type in) -> size_type {
return ((static_cast<int64_t>(in) % n_rows) + n_rows) % n_rows;
});
// Dispatch over data type per column
auto result = std::vector<std::unique_ptr<column>>(target.num_columns());
auto scatter_functor = column_scalar_scatterer<decltype(scatter_iter)>{};
std::transform(source.begin(),
source.end(),
target.begin(),
result.begin(),
[=](auto const& source_scalar, auto const& target_col) {
return type_dispatcher<dispatch_storage_type>(target_col.type(),
scatter_functor,
source_scalar,
scatter_iter,
scatter_rows,
target_col,
stream,
mr);
});
return std::make_unique<table>(std::move(result));
}
std::unique_ptr<column> boolean_mask_scatter(column_view const& input,
column_view const& target,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto indices = cudf::make_numeric_column(
data_type{type_id::INT32}, target.size(), mask_state::UNALLOCATED, stream);
auto mutable_indices = indices->mutable_view();
thrust::sequence(rmm::exec_policy_nosync(stream),
mutable_indices.begin<size_type>(),
mutable_indices.end<size_type>(),
0);
// The scatter map is actually a table with only one column, which is scatter map.
auto scatter_map = detail::apply_boolean_mask(
table_view{{indices->view()}}, boolean_mask, stream, rmm::mr::get_current_device_resource());
auto output_table = detail::scatter(
table_view{{input}}, scatter_map->get_column(0).view(), table_view{{target}}, stream, mr);
// There is only one column in output_table
return std::make_unique<column>(std::move(output_table->get_column(0)));
}
std::unique_ptr<column> boolean_mask_scatter(scalar const& input,
column_view const& target,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return detail::copy_if_else(input, target, boolean_mask, stream, mr);
}
std::unique_ptr<table> boolean_mask_scatter(table_view const& input,
table_view const& target,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(input.num_columns() == target.num_columns(),
"Mismatch in number of input columns and target columns");
CUDF_EXPECTS(boolean_mask.size() == target.num_rows(),
"Boolean mask size and number of target rows mismatch");
CUDF_EXPECTS(boolean_mask.type().id() == type_id::BOOL8, "Mask must be of Boolean type");
// Count valid pair of input and columns as per type at each column index i
CUDF_EXPECTS(
std::all_of(thrust::counting_iterator<size_type>(0),
thrust::counting_iterator<size_type>(target.num_columns()),
[&input, &target](auto index) {
return ((input.column(index).type().id()) == (target.column(index).type().id()));
}),
"Type mismatch in input column and target column");
if (target.num_rows() != 0) {
std::vector<std::unique_ptr<column>> out_columns(target.num_columns());
std::transform(
input.begin(),
input.end(),
target.begin(),
out_columns.begin(),
[&boolean_mask, mr, stream](auto const& input_column, auto const& target_column) {
return boolean_mask_scatter(input_column, target_column, boolean_mask, stream, mr);
});
return std::make_unique<table>(std::move(out_columns));
} else {
return empty_like(target);
}
}
std::unique_ptr<table> boolean_mask_scatter(
std::vector<std::reference_wrapper<scalar const>> const& input,
table_view const& target,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(static_cast<size_type>(input.size()) == target.num_columns(),
"Mismatch in number of scalars and target columns");
CUDF_EXPECTS(boolean_mask.size() == target.num_rows(),
"Boolean mask size and number of target rows mismatch");
CUDF_EXPECTS(boolean_mask.type().id() == type_id::BOOL8, "Mask must be of Boolean type");
// Count valid pair of input and columns as per type at each column/scalar index i
CUDF_EXPECTS(
std::all_of(thrust::counting_iterator<size_type>(0),
thrust::counting_iterator<size_type>(target.num_columns()),
[&input, &target](auto index) {
return (input[index].get().type().id() == target.column(index).type().id());
}),
"Type mismatch in input scalar and target column");
if (target.num_rows() != 0) {
std::vector<std::unique_ptr<column>> out_columns(target.num_columns());
std::transform(input.begin(),
input.end(),
target.begin(),
out_columns.begin(),
[&boolean_mask, mr, stream](auto const& scalar, auto const& target_column) {
return boolean_mask_scatter(
scalar.get(), target_column, boolean_mask, stream, mr);
});
return std::make_unique<table>(std::move(out_columns));
} else {
return empty_like(target);
}
}
} // namespace detail
std::unique_ptr<table> scatter(table_view const& source,
column_view const& scatter_map,
table_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::scatter(source, scatter_map, target, stream, mr);
}
std::unique_ptr<table> scatter(std::vector<std::reference_wrapper<scalar const>> const& source,
column_view const& indices,
table_view const& target,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::scatter(source, indices, target, stream, mr);
}
std::unique_ptr<table> boolean_mask_scatter(table_view const& input,
table_view const& target,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::boolean_mask_scatter(input, target, boolean_mask, stream, mr);
}
std::unique_ptr<table> boolean_mask_scatter(
std::vector<std::reference_wrapper<scalar const>> const& input,
table_view const& target,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::boolean_mask_scatter(input, target, boolean_mask, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/slice.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <algorithm>
namespace cudf {
namespace detail {
template <typename ColumnView>
ColumnView slice(ColumnView const& input,
size_type begin,
size_type end,
rmm::cuda_stream_view stream)
{
CUDF_EXPECTS(begin >= 0, "Invalid beginning of range.");
CUDF_EXPECTS(end >= begin, "Invalid end of range.");
CUDF_EXPECTS(end <= input.size(), "Slice range out of bounds.");
std::vector<ColumnView> children{};
children.reserve(input.num_children());
for (size_type index = 0; index < input.num_children(); index++) {
children.emplace_back(input.child(index));
}
return ColumnView(
input.type(),
end - begin,
input.head(),
input.null_mask(),
input.null_count() ? cudf::detail::null_count(input.null_mask(), begin, end, stream) : 0,
input.offset() + begin,
children);
}
template column_view slice<column_view>(column_view const&,
size_type,
size_type,
rmm::cuda_stream_view);
template mutable_column_view slice<mutable_column_view>(mutable_column_view const&,
size_type,
size_type,
rmm::cuda_stream_view);
std::vector<column_view> slice(column_view const& input,
host_span<size_type const> indices,
rmm::cuda_stream_view stream)
{
CUDF_EXPECTS(indices.size() % 2 == 0, "indices size must be even");
if (indices.empty()) return {};
// need to shift incoming indices by the column offset to generate the correct bit ranges
// to count
auto indices_iter = cudf::detail::make_counting_transform_iterator(
0, [offset = input.offset(), &indices](size_type index) { return indices[index] + offset; });
auto null_counts = cudf::detail::segmented_null_count(
input.null_mask(), indices_iter, indices_iter + indices.size(), stream);
auto const children = std::vector<column_view>(input.child_begin(), input.child_end());
auto op = [&](auto i) {
auto begin = indices[2 * i];
auto end = indices[2 * i + 1];
CUDF_EXPECTS(begin >= 0, "Starting index cannot be negative.");
CUDF_EXPECTS(end >= begin, "End index cannot be smaller than the starting index.");
CUDF_EXPECTS(end <= input.size(), "Slice range out of bounds.");
return column_view{input.type(),
end - begin,
input.head(),
input.null_mask(),
null_counts[i],
input.offset() + begin,
children};
};
auto begin = cudf::detail::make_counting_transform_iterator(0, op);
return std::vector<column_view>{begin, begin + indices.size() / 2};
}
std::vector<table_view> slice(table_view const& input,
host_span<size_type const> indices,
rmm::cuda_stream_view stream)
{
CUDF_EXPECTS(indices.size() % 2 == 0, "indices size must be even");
if (indices.empty()) { return {}; }
// 2d arrangement of column_views that represent the outgoing table_views sliced_table[i][j]
// where i is the i'th column of the j'th table_view
auto op = [&indices, &stream](auto const& c) { return cudf::detail::slice(c, indices, stream); };
auto f = thrust::make_transform_iterator(input.begin(), op);
auto sliced_table = std::vector<std::vector<cudf::column_view>>(f, f + input.num_columns());
sliced_table.reserve(indices.size() + 1);
std::vector<cudf::table_view> result{};
// distribute columns into outgoing table_views
size_t num_output_tables = indices.size() / 2;
for (size_t i = 0; i < num_output_tables; i++) {
std::vector<cudf::column_view> table_columns;
for (size_type j = 0; j < input.num_columns(); j++) {
table_columns.emplace_back(sliced_table[j][i]);
}
result.emplace_back(table_view{table_columns});
}
return result;
}
std::vector<column_view> slice(column_view const& input,
std::initializer_list<size_type> indices,
rmm::cuda_stream_view stream)
{
return detail::slice(input, host_span<size_type const>(indices.begin(), indices.size()), stream);
}
std::vector<table_view> slice(table_view const& input,
std::initializer_list<size_type> indices,
rmm::cuda_stream_view stream)
{
return detail::slice(input, host_span<size_type const>(indices.begin(), indices.size()), stream);
};
} // namespace detail
std::vector<column_view> slice(column_view const& input,
host_span<size_type const> indices,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::slice(input, indices, stream);
}
std::vector<table_view> slice(table_view const& input,
host_span<size_type const> indices,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::slice(input, indices, stream);
};
std::vector<column_view> slice(column_view const& input,
std::initializer_list<size_type> indices,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::slice(input, indices, stream);
}
std::vector<table_view> slice(table_view const& input,
std::initializer_list<size_type> indices,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::slice(input, indices, stream);
};
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/copy_range.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_factories.hpp>
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/copy_range.cuh>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/dictionary/detail/update_keys.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/dictionary/dictionary_factories.hpp>
#include <cudf/strings/detail/copy_range.cuh>
#include <cudf/strings/strings_column_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <cudf/utilities/traits.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <memory>
namespace {
template <typename T>
void in_place_copy_range(cudf::column_view const& source,
cudf::mutable_column_view& target,
cudf::size_type source_begin,
cudf::size_type source_end,
cudf::size_type target_begin,
rmm::cuda_stream_view stream)
{
auto p_source_device_view = cudf::column_device_view::create(source, stream);
if (source.has_nulls()) {
cudf::detail::copy_range(
cudf::detail::make_null_replacement_iterator<T>(*p_source_device_view, T()) + source_begin,
cudf::detail::make_validity_iterator(*p_source_device_view) + source_begin,
target,
target_begin,
target_begin + (source_end - source_begin),
stream);
} else {
cudf::detail::copy_range(p_source_device_view->begin<T>() + source_begin,
thrust::make_constant_iterator(true), // dummy
target,
target_begin,
target_begin + (source_end - source_begin),
stream);
}
}
struct in_place_copy_range_dispatch {
cudf::column_view const& source;
cudf::mutable_column_view& target;
template <typename T, CUDF_ENABLE_IF(cudf::is_rep_layout_compatible<T>())>
void operator()(cudf::size_type source_begin,
cudf::size_type source_end,
cudf::size_type target_begin,
rmm::cuda_stream_view stream)
{
in_place_copy_range<T>(source, target, source_begin, source_end, target_begin, stream);
}
template <typename T, typename... Args>
void operator()(Args&&...)
{
CUDF_FAIL("Unsupported type for in-place copy.");
}
};
struct out_of_place_copy_range_dispatch {
cudf::column_view const& source;
cudf::column_view const& target;
template <typename T, CUDF_ENABLE_IF(cudf::is_rep_layout_compatible<T>())>
std::unique_ptr<cudf::column> operator()(
cudf::size_type source_begin,
cudf::size_type source_end,
cudf::size_type target_begin,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr = rmm::mr::get_current_device_resource())
{
auto p_ret = std::make_unique<cudf::column>(target, stream, mr);
if ((!p_ret->nullable()) && source.has_nulls(source_begin, source_end)) {
p_ret->set_null_mask(
cudf::detail::create_null_mask(p_ret->size(), cudf::mask_state::ALL_VALID, stream, mr), 0);
}
if (source_end != source_begin) { // otherwise no-op
auto ret_view = p_ret->mutable_view();
in_place_copy_range<T>(source, ret_view, source_begin, source_end, target_begin, stream);
p_ret->set_null_count(ret_view.null_count());
}
return p_ret;
}
template <typename T, typename... Args>
std::enable_if_t<not cudf::is_rep_layout_compatible<T>(), std::unique_ptr<cudf::column>>
operator()(Args...)
{
CUDF_FAIL("Unsupported type for out of place copy.");
}
};
template <>
std::unique_ptr<cudf::column> out_of_place_copy_range_dispatch::operator()<cudf::string_view>(
cudf::size_type source_begin,
cudf::size_type source_end,
cudf::size_type target_begin,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto target_end = target_begin + (source_end - source_begin);
auto p_source_device_view = cudf::column_device_view::create(source, stream);
if (source.has_nulls()) {
return cudf::strings::detail::copy_range(
cudf::detail::make_null_replacement_iterator<cudf::string_view>(*p_source_device_view,
cudf::string_view()) +
source_begin,
cudf::detail::make_validity_iterator(*p_source_device_view) + source_begin,
cudf::strings_column_view(target),
target_begin,
target_end,
stream,
mr);
} else {
return cudf::strings::detail::copy_range(
p_source_device_view->begin<cudf::string_view>() + source_begin,
thrust::make_constant_iterator(true),
cudf::strings_column_view(target),
target_begin,
target_end,
stream,
mr);
}
}
template <>
std::unique_ptr<cudf::column> out_of_place_copy_range_dispatch::operator()<cudf::dictionary32>(
cudf::size_type source_begin,
cudf::size_type source_end,
cudf::size_type target_begin,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// check the keys in the source and target
cudf::dictionary_column_view const dict_source(source);
cudf::dictionary_column_view const dict_target(target);
CUDF_EXPECTS(dict_source.keys().type() == dict_target.keys().type(),
"dictionary keys must be the same type");
// combine keys so both dictionaries have the same set
auto target_matched =
cudf::dictionary::detail::add_keys(dict_target, dict_source.keys(), stream, mr);
auto const target_view = cudf::dictionary_column_view(target_matched->view());
auto source_matched = cudf::dictionary::detail::set_keys(
dict_source, target_view.keys(), stream, rmm::mr::get_current_device_resource());
auto const source_view = cudf::dictionary_column_view(source_matched->view());
// build the new indices by calling in_place_copy_range on just the indices
auto const source_indices = source_view.get_indices_annotated();
auto target_contents = target_matched->release();
auto target_indices(std::move(target_contents.children.front()));
cudf::mutable_column_view new_indices(
target_indices->type(),
dict_target.size(),
target_indices->mutable_view().head(),
static_cast<cudf::bitmask_type*>(target_contents.null_mask->data()),
dict_target.null_count());
cudf::type_dispatcher(new_indices.type(),
in_place_copy_range_dispatch{source_indices, new_indices},
source_begin,
source_end,
target_begin,
stream);
auto null_count = new_indices.null_count();
auto indices_column =
std::make_unique<cudf::column>(new_indices.type(),
new_indices.size(),
std::move(*(target_indices->release().data.release())),
rmm::device_buffer{0, stream, mr},
0);
// take the keys from the matched column allocated using mr
auto keys_column(std::move(target_contents.children.back()));
// create column with keys_column and indices_column
return make_dictionary_column(std::move(keys_column),
std::move(indices_column),
std::move(*(target_contents.null_mask.release())),
null_count);
}
} // namespace
namespace cudf {
namespace detail {
void copy_range_in_place(column_view const& source,
mutable_column_view& target,
size_type source_begin,
size_type source_end,
size_type target_begin,
rmm::cuda_stream_view stream)
{
CUDF_EXPECTS(cudf::is_fixed_width(target.type()),
"In-place copy_range does not support variable-sized types.");
CUDF_EXPECTS((source_begin >= 0) && (source_end <= source.size()) &&
(source_begin <= source_end) && (target_begin >= 0) &&
(target_begin <= target.size() - (source_end - source_begin)),
"Range is out of bounds.");
CUDF_EXPECTS(target.type() == source.type(), "Data type mismatch.");
CUDF_EXPECTS(target.nullable() || not source.has_nulls(),
"target should be nullable if source has null values.");
if (source_end != source_begin) { // otherwise no-op
cudf::type_dispatcher<dispatch_storage_type>(target.type(),
in_place_copy_range_dispatch{source, target},
source_begin,
source_end,
target_begin,
stream);
}
}
std::unique_ptr<column> copy_range(column_view const& source,
column_view const& target,
size_type source_begin,
size_type source_end,
size_type target_begin,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS((source_begin >= 0) && (source_end <= source.size()) &&
(source_begin <= source_end) && (target_begin >= 0) &&
(target_begin <= target.size() - (source_end - source_begin)),
"Range is out of bounds.");
CUDF_EXPECTS(target.type() == source.type(), "Data type mismatch.");
return cudf::type_dispatcher<dispatch_storage_type>(
target.type(),
out_of_place_copy_range_dispatch{source, target},
source_begin,
source_end,
target_begin,
stream,
mr);
}
} // namespace detail
void copy_range_in_place(column_view const& source,
mutable_column_view& target,
size_type source_begin,
size_type source_end,
size_type target_begin,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::copy_range_in_place(
source, target, source_begin, source_end, target_begin, stream);
}
std::unique_ptr<column> copy_range(column_view const& source,
column_view const& target,
size_type source_begin,
size_type source_end,
size_type target_begin,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::copy_range(source, target, source_begin, source_end, target_begin, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/get_element.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/indexalator.cuh>
#include <cudf/detail/is_element_valid.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/lists/detail/copying.hpp>
#include <cudf/lists/lists_column_view.hpp>
#include <cudf/scalar/scalar_device_view.cuh>
#include <cudf/scalar/scalar_factories.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace detail {
namespace {
struct get_element_functor {
template <typename T, std::enable_if_t<is_fixed_width<T>() && !is_fixed_point<T>()>* p = nullptr>
std::unique_ptr<scalar> operator()(column_view const& input,
size_type index,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto s = make_fixed_width_scalar(data_type(type_to_id<T>()), stream, mr);
using ScalarType = cudf::scalar_type_t<T>;
auto typed_s = static_cast<ScalarType*>(s.get());
auto device_s = get_scalar_device_view(*typed_s);
auto device_col = column_device_view::create(input, stream);
device_single_thread(
[device_s, d_col = *device_col, index] __device__() mutable {
device_s.set_value(d_col.element<T>(index));
device_s.set_valid(d_col.is_valid(index));
},
stream);
return s;
}
template <typename T, std::enable_if_t<std::is_same_v<T, string_view>>* p = nullptr>
std::unique_ptr<scalar> operator()(column_view const& input,
size_type index,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto device_col = column_device_view::create(input, stream);
rmm::device_scalar<string_view> temp_data(stream, mr);
rmm::device_scalar<bool> temp_valid(stream, mr);
device_single_thread(
[buffer = temp_data.data(),
validity = temp_valid.data(),
d_col = *device_col,
index] __device__() mutable {
*buffer = d_col.element<string_view>(index);
*validity = d_col.is_valid(index);
},
stream);
return std::make_unique<string_scalar>(temp_data, temp_valid.value(stream), stream, mr);
}
template <typename T, std::enable_if_t<std::is_same_v<T, dictionary32>>* p = nullptr>
std::unique_ptr<scalar> operator()(column_view const& input,
size_type index,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto dict_view = dictionary_column_view(input);
auto indices_iter = detail::indexalator_factory::make_input_iterator(dict_view.indices());
numeric_scalar<size_type> key_index_scalar{index, true, stream};
auto d_key_index = get_scalar_device_view(key_index_scalar);
auto d_col = column_device_view::create(input, stream);
// retrieve the indices value at index
device_single_thread(
[d_key_index, d_col = *d_col, indices_iter, index] __device__() mutable {
d_key_index.set_value(indices_iter[index]);
d_key_index.set_valid(d_col.is_valid(index));
},
stream);
if (!key_index_scalar.is_valid(stream)) {
auto null_result = make_default_constructed_scalar(dict_view.keys().type(), stream, mr);
null_result->set_valid_async(false, stream);
return null_result;
}
// retrieve the key element using the key-index
return type_dispatcher(dict_view.keys().type(),
get_element_functor{},
dict_view.keys(),
key_index_scalar.value(stream),
stream,
mr);
}
template <typename T, std::enable_if_t<std::is_same_v<T, list_view>>* p = nullptr>
std::unique_ptr<scalar> operator()(column_view const& input,
size_type index,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
bool valid = is_element_valid_sync(input, index, stream);
auto const child_col_idx = lists_column_view::child_column_index;
if (valid) {
lists_column_view lcv(input);
// Make a copy of the row
auto row_slice_contents =
lists::detail::copy_slice(lcv, index, index + 1, stream, mr)->release();
// Construct scalar with row data
return std::make_unique<list_scalar>(
std::move(*row_slice_contents.children[child_col_idx]), valid, stream, mr);
} else {
auto empty_row_contents = empty_like(input)->release();
return std::make_unique<list_scalar>(
std::move(*empty_row_contents.children[child_col_idx]), valid, stream, mr);
}
}
template <typename T, std::enable_if_t<cudf::is_fixed_point<T>()>* p = nullptr>
std::unique_ptr<scalar> operator()(column_view const& input,
size_type index,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using Type = typename T::rep;
auto device_col = column_device_view::create(input, stream);
rmm::device_scalar<Type> temp_data(stream, mr);
rmm::device_scalar<bool> temp_valid(stream, mr);
device_single_thread(
[buffer = temp_data.data(),
validity = temp_valid.data(),
d_col = *device_col,
index] __device__() mutable {
*buffer = d_col.element<Type>(index);
*validity = d_col.is_valid(index);
},
stream);
return std::make_unique<fixed_point_scalar<T>>(std::move(temp_data),
numeric::scale_type{input.type().scale()},
temp_valid.value(stream),
stream,
mr);
}
template <typename T, std::enable_if_t<std::is_same_v<T, struct_view>>* p = nullptr>
std::unique_ptr<scalar> operator()(column_view const& input,
size_type index,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
bool valid = is_element_valid_sync(input, index, stream);
auto row_contents =
std::make_unique<column>(slice(input, index, index + 1, stream), stream, mr)->release();
auto scalar_contents = table(std::move(row_contents.children));
return std::make_unique<struct_scalar>(std::move(scalar_contents), valid, stream, mr);
}
};
} // namespace
std::unique_ptr<scalar> get_element(column_view const& input,
size_type index,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(index >= 0 and index < input.size(), "Index out of bounds");
return type_dispatcher(input.type(), get_element_functor{}, input, index, stream, mr);
}
} // namespace detail
std::unique_ptr<scalar> get_element(column_view const& input,
size_type index,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::get_element(input, index, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/split.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <algorithm>
namespace cudf {
namespace detail {
namespace {
template <typename T>
std::vector<T> split(T const& input,
size_type column_size,
host_span<size_type const> splits,
rmm::cuda_stream_view stream)
{
if (splits.empty() or column_size == 0) { return std::vector<T>{input}; }
CUDF_EXPECTS(splits.back() <= column_size, "splits can't exceed size of input columns");
// If the size is not zero, the split will always start at `0`
std::vector<size_type> indices{0};
std::for_each(splits.begin(), splits.end(), [&indices](auto split) {
indices.push_back(split); // This for end
indices.push_back(split); // This for the start
});
indices.push_back(column_size); // This to include rest of the elements
return detail::slice(input, indices, stream);
}
}; // anonymous namespace
std::vector<cudf::column_view> split(cudf::column_view const& input,
host_span<size_type const> splits,
rmm::cuda_stream_view stream)
{
return split(input, input.size(), splits, stream);
}
std::vector<cudf::table_view> split(cudf::table_view const& input,
host_span<size_type const> splits,
rmm::cuda_stream_view stream)
{
if (input.num_columns() == 0) { return {}; }
return split(input, input.column(0).size(), splits, stream);
}
std::vector<column_view> split(column_view const& input,
std::initializer_list<size_type> splits,
rmm::cuda_stream_view stream)
{
return detail::split(input, host_span<size_type const>(splits.begin(), splits.size()), stream);
}
std::vector<table_view> split(table_view const& input,
std::initializer_list<size_type> splits,
rmm::cuda_stream_view stream)
{
return detail::split(input, host_span<size_type const>(splits.begin(), splits.size()), stream);
}
} // namespace detail
std::vector<cudf::column_view> split(cudf::column_view const& input,
host_span<size_type const> splits,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::split(input, splits, stream);
}
std::vector<cudf::table_view> split(cudf::table_view const& input,
host_span<size_type const> splits,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::split(input, splits, stream);
}
std::vector<column_view> split(column_view const& input,
std::initializer_list<size_type> splits,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::split(input, splits, stream);
}
std::vector<table_view> split(table_view const& input,
std::initializer_list<size_type> splits,
rmm::cuda_stream_view stream)
{
CUDF_FUNC_RANGE();
return detail::split(input, splits, stream);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/copy.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/copy.hpp>
#include <cudf/detail/copy_if_else.cuh>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/scatter.hpp>
#include <cudf/dictionary/dictionary_column_view.hpp>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/detail/copy_if_else.cuh>
#include <cudf/strings/string_view.cuh>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/traits.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
#include <thrust/copy.h>
#include <thrust/distance.h>
#include <thrust/iterator/counting_iterator.h>
namespace cudf {
namespace detail {
namespace {
template <typename T, typename Enable = void>
struct copy_if_else_functor_impl {
template <typename... Args>
std::unique_ptr<column> operator()(Args&&...)
{
CUDF_FAIL("Unsupported type for copy_if_else.");
}
};
/**
* @brief Functor to fetch a device-view for the specified scalar/column_view.
*/
struct get_iterable_device_view {
template <typename T, CUDF_ENABLE_IF(std::is_same_v<T, cudf::column_view>)>
auto operator()(T const& input, rmm::cuda_stream_view stream)
{
return cudf::column_device_view::create(input, stream);
}
template <typename T, CUDF_ENABLE_IF(std::is_same_v<T, cudf::scalar>)>
auto operator()(T const& input, rmm::cuda_stream_view)
{
return &input;
}
};
template <typename T>
struct copy_if_else_functor_impl<T, std::enable_if_t<is_rep_layout_compatible<T>()>> {
template <typename Left, typename Right, typename Filter>
std::unique_ptr<column> operator()(Left const& lhs_h,
Right const& rhs_h,
size_type size,
bool left_nullable,
bool right_nullable,
Filter filter,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto p_lhs = get_iterable_device_view{}(lhs_h, stream);
auto p_rhs = get_iterable_device_view{}(rhs_h, stream);
auto const& lhs = *p_lhs;
auto const& rhs = *p_rhs;
auto lhs_iter = cudf::detail::make_optional_iterator<T>(lhs, nullate::DYNAMIC{left_nullable});
auto rhs_iter = cudf::detail::make_optional_iterator<T>(rhs, nullate::DYNAMIC{right_nullable});
return detail::copy_if_else(left_nullable || right_nullable,
lhs_iter,
lhs_iter + size,
rhs_iter,
filter,
lhs.type(),
stream,
mr);
}
};
/**
* @brief Specialization of copy_if_else_functor for string_views.
*/
template <>
struct copy_if_else_functor_impl<string_view> {
template <typename Left, typename Right, typename Filter>
std::unique_ptr<column> operator()(Left const& lhs_h,
Right const& rhs_h,
size_type size,
bool left_nullable,
bool right_nullable,
Filter filter,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using T = string_view;
auto p_lhs = get_iterable_device_view{}(lhs_h, stream);
auto p_rhs = get_iterable_device_view{}(rhs_h, stream);
auto const& lhs = *p_lhs;
auto const& rhs = *p_rhs;
auto lhs_iter = cudf::detail::make_optional_iterator<T>(lhs, nullate::DYNAMIC{left_nullable});
auto rhs_iter = cudf::detail::make_optional_iterator<T>(rhs, nullate::DYNAMIC{right_nullable});
return strings::detail::copy_if_else(lhs_iter, lhs_iter + size, rhs_iter, filter, stream, mr);
}
};
/**
* @brief Adapter to negate predicates.
*/
template <typename Predicate>
class logical_not {
public:
explicit logical_not(Predicate predicate) : _pred{predicate} {}
bool __device__ operator()(size_type i) const { return not _pred(i); }
private:
Predicate _pred;
};
/**
* @brief Implementation of copy_if_else() with gather()/scatter().
*
* Handles nested-typed column views. Uses the iterator `is_left` to decide what row to pick for
* the output column.
*
* Uses `rhs` as the destination for scatter. First gathers indices of rows to copy from lhs.
*
* @tparam Filter Bool iterator producing `true` for indices of output rows to copy from `lhs` and
* `false` for indices of output rows to copy from `rhs`
* @param lhs Left-hand side input column view
* @param rhs Right-hand side input column view
* @param size The size of the output column, inputs rows are iterated from 0 to `size - 1`
* @param is_left Predicate for picking rows from `lhs` on `true` or `rhs` on `false`
* @param stream The stream on which to perform the allocation
* @param mr The resource used to allocate the device storage
* @return Column with rows populated according to the `is_left` predicate
*/
template <typename Filter>
std::unique_ptr<column> scatter_gather_based_if_else(cudf::column_view const& lhs,
cudf::column_view const& rhs,
size_type size,
Filter is_left,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto gather_map = rmm::device_uvector<size_type>{static_cast<std::size_t>(size), stream};
auto const gather_map_end = thrust::copy_if(rmm::exec_policy(stream),
thrust::make_counting_iterator(size_type{0}),
thrust::make_counting_iterator(size_type{size}),
gather_map.begin(),
is_left);
gather_map.resize(thrust::distance(gather_map.begin(), gather_map_end), stream);
auto const scatter_src_lhs = cudf::detail::gather(table_view{std::vector<column_view>{lhs}},
gather_map,
out_of_bounds_policy::DONT_CHECK,
negative_index_policy::NOT_ALLOWED,
stream,
rmm::mr::get_current_device_resource());
auto result = cudf::detail::scatter(
table_view{std::vector<column_view>{scatter_src_lhs->get_column(0).view()}},
gather_map,
table_view{std::vector<column_view>{rhs}},
stream,
mr);
return std::move(result->release()[0]);
}
template <typename Filter>
std::unique_ptr<column> scatter_gather_based_if_else(cudf::scalar const& lhs,
cudf::column_view const& rhs,
size_type size,
Filter is_left,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto scatter_map = rmm::device_uvector<size_type>{static_cast<std::size_t>(size), stream};
auto const scatter_map_end = thrust::copy_if(rmm::exec_policy(stream),
thrust::make_counting_iterator(size_type{0}),
thrust::make_counting_iterator(size_type{size}),
scatter_map.begin(),
is_left);
auto const scatter_map_size = std::distance(scatter_map.begin(), scatter_map_end);
auto scatter_source = std::vector<std::reference_wrapper<scalar const>>{std::ref(lhs)};
auto scatter_map_column_view = cudf::column_view{cudf::data_type{cudf::type_id::INT32},
static_cast<cudf::size_type>(scatter_map_size),
scatter_map.begin(),
nullptr,
0};
auto result = cudf::detail::scatter(
scatter_source, scatter_map_column_view, table_view{std::vector<column_view>{rhs}}, stream, mr);
return std::move(result->release()[0]);
}
template <typename Filter>
std::unique_ptr<column> scatter_gather_based_if_else(cudf::column_view const& lhs,
cudf::scalar const& rhs,
size_type size,
Filter is_left,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return scatter_gather_based_if_else(rhs, lhs, size, logical_not{is_left}, stream, mr);
}
template <typename Filter>
std::unique_ptr<column> scatter_gather_based_if_else(cudf::scalar const& lhs,
cudf::scalar const& rhs,
size_type size,
Filter is_left,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto rhs_col = cudf::make_column_from_scalar(rhs, size, stream, mr);
return scatter_gather_based_if_else(lhs, rhs_col->view(), size, is_left, stream, mr);
}
template <>
struct copy_if_else_functor_impl<struct_view> {
template <typename Left, typename Right, typename Filter>
std::unique_ptr<column> operator()(Left const& lhs,
Right const& rhs,
size_type size,
bool,
bool,
Filter filter,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return scatter_gather_based_if_else(lhs, rhs, size, filter, stream, mr);
}
};
template <>
struct copy_if_else_functor_impl<list_view> {
template <typename Left, typename Right, typename Filter>
std::unique_ptr<column> operator()(Left const& lhs,
Right const& rhs,
size_type size,
bool,
bool,
Filter filter,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return scatter_gather_based_if_else(lhs, rhs, size, filter, stream, mr);
}
};
template <>
struct copy_if_else_functor_impl<dictionary32> {
template <typename Left, typename Right, typename Filter>
std::unique_ptr<column> operator()(Left const& lhs,
Right const& rhs,
size_type size,
bool,
bool,
Filter filter,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return scatter_gather_based_if_else(lhs, rhs, size, filter, stream, mr);
}
};
/**
* @brief Functor called by the `type_dispatcher` to invoke copy_if_else on combinations
* of column_view and scalar
*/
struct copy_if_else_functor {
template <typename T, typename Left, typename Right, typename Filter>
std::unique_ptr<column> operator()(Left const& lhs,
Right const& rhs,
size_type size,
bool left_nullable,
bool right_nullable,
Filter filter,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
copy_if_else_functor_impl<T> copier{};
return copier(lhs, rhs, size, left_nullable, right_nullable, filter, stream, mr);
}
};
// wrap up boolean_mask into a filter lambda
template <typename Left, typename Right>
std::unique_ptr<column> copy_if_else(Left const& lhs,
Right const& rhs,
bool left_nullable,
bool right_nullable,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(boolean_mask.type() == data_type(type_id::BOOL8),
"Boolean mask column must be of type type_id::BOOL8");
if (boolean_mask.is_empty()) { return cudf::empty_like(lhs); }
auto bool_mask_device_p = column_device_view::create(boolean_mask, stream);
column_device_view bool_mask_device = *bool_mask_device_p;
auto const has_nulls = boolean_mask.has_nulls();
auto filter = [bool_mask_device, has_nulls] __device__(cudf::size_type i) {
return (!has_nulls || bool_mask_device.is_valid_nocheck(i)) and
bool_mask_device.element<bool>(i);
};
// always dispatch on dictionary-type if either input is a dictionary
auto dispatch_type = cudf::is_dictionary(rhs.type()) ? rhs.type() : lhs.type();
return cudf::type_dispatcher<dispatch_storage_type>(dispatch_type,
copy_if_else_functor{},
lhs,
rhs,
boolean_mask.size(),
left_nullable,
right_nullable,
filter,
stream,
mr);
}
}; // namespace
std::unique_ptr<column> copy_if_else(column_view const& lhs,
column_view const& rhs,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(boolean_mask.size() == lhs.size(),
"Boolean mask column must be the same size as lhs and rhs columns");
CUDF_EXPECTS(lhs.size() == rhs.size(), "Both columns must be of the size");
CUDF_EXPECTS(lhs.type() == rhs.type(), "Both inputs must be of the same type");
return copy_if_else(lhs, rhs, lhs.has_nulls(), rhs.has_nulls(), boolean_mask, stream, mr);
}
std::unique_ptr<column> copy_if_else(scalar const& lhs,
column_view const& rhs,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(boolean_mask.size() == rhs.size(),
"Boolean mask column must be the same size as rhs column");
auto rhs_type =
cudf::is_dictionary(rhs.type()) ? cudf::dictionary_column_view(rhs).keys_type() : rhs.type();
CUDF_EXPECTS(lhs.type() == rhs_type, "Both inputs must be of the same type");
return copy_if_else(lhs, rhs, !lhs.is_valid(stream), rhs.has_nulls(), boolean_mask, stream, mr);
}
std::unique_ptr<column> copy_if_else(column_view const& lhs,
scalar const& rhs,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(boolean_mask.size() == lhs.size(),
"Boolean mask column must be the same size as lhs column");
auto lhs_type =
cudf::is_dictionary(lhs.type()) ? cudf::dictionary_column_view(lhs).keys_type() : lhs.type();
CUDF_EXPECTS(lhs_type == rhs.type(), "Both inputs must be of the same type");
return copy_if_else(lhs, rhs, lhs.has_nulls(), !rhs.is_valid(stream), boolean_mask, stream, mr);
}
std::unique_ptr<column> copy_if_else(scalar const& lhs,
scalar const& rhs,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(lhs.type() == rhs.type(), "Both inputs must be of the same type");
return copy_if_else(
lhs, rhs, !lhs.is_valid(stream), !rhs.is_valid(stream), boolean_mask, stream, mr);
}
}; // namespace detail
std::unique_ptr<column> copy_if_else(column_view const& lhs,
column_view const& rhs,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::copy_if_else(lhs, rhs, boolean_mask, stream, mr);
}
std::unique_ptr<column> copy_if_else(scalar const& lhs,
column_view const& rhs,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::copy_if_else(lhs, rhs, boolean_mask, stream, mr);
}
std::unique_ptr<column> copy_if_else(column_view const& lhs,
scalar const& rhs,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::copy_if_else(lhs, rhs, boolean_mask, stream, mr);
}
std::unique_ptr<column> copy_if_else(scalar const& lhs,
scalar const& rhs,
column_view const& boolean_mask,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::copy_if_else(lhs, rhs, boolean_mask, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/purge_nonempty_nulls.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/copying.hpp>
#include <cudf/detail/gather.cuh>
#include <cudf/utilities/default_stream.hpp>
#include <thrust/count.h>
#include <thrust/iterator/counting_iterator.h>
namespace cudf {
namespace detail {
using cudf::type_id;
namespace {
/// Check if nonempty-null checks can be skipped for a given type.
bool type_may_have_nonempty_nulls(cudf::type_id const& type)
{
return type == type_id::STRING || type == type_id::LIST || type == type_id::STRUCT;
}
/// Check if the (STRING/LIST) column has any null rows with non-zero length.
bool has_nonempty_null_rows(cudf::column_view const& input, rmm::cuda_stream_view stream)
{
if (not input.has_nulls()) { return false; } // No nulls => no dirty rows.
if ((input.size() == input.null_count()) && (input.num_children() == 0)) { return false; }
// Cross-reference nullmask and offsets.
auto const type = input.type().id();
auto const offsets = (type == type_id::STRING) ? (strings_column_view{input}).offsets_begin()
: (lists_column_view{input}).offsets_begin();
auto const d_input = cudf::column_device_view::create(input, stream);
auto const is_dirty_row = [d_input = *d_input, offsets] __device__(size_type const& row_idx) {
return d_input.is_null_nocheck(row_idx) && (offsets[row_idx] != offsets[row_idx + 1]);
};
auto const row_begin = thrust::counting_iterator<cudf::size_type>(0);
auto const row_end = row_begin + input.size();
return thrust::count_if(rmm::exec_policy(stream), row_begin, row_end, is_dirty_row) > 0;
}
} // namespace
/**
* @copydoc cudf::detail::has_nonempty_nulls
*/
bool has_nonempty_nulls(cudf::column_view const& input, rmm::cuda_stream_view stream)
{
auto const type = input.type().id();
if (not type_may_have_nonempty_nulls(type)) { return false; }
// For types with variable-length rows, check if any rows are "dirty".
// A dirty row is a null row with non-zero length.
if ((type == type_id::STRING || type == type_id::LIST) && has_nonempty_null_rows(input, stream)) {
return true;
}
// For complex types, check if child columns need purging.
if ((type == type_id::STRUCT || type == type_id::LIST) &&
std::any_of(input.child_begin(), input.child_end(), [stream](auto const& child) {
return cudf::detail::has_nonempty_nulls(child, stream);
})) {
return true;
}
return false;
}
std::unique_ptr<column> purge_nonempty_nulls(column_view const& input,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// If not compound types (LIST/STRING/STRUCT/DICTIONARY) then just copy the input into output.
if (!cudf::is_compound(input.type())) { return std::make_unique<column>(input, stream, mr); }
// Implement via identity gather.
auto gathered_table = cudf::detail::gather(table_view{{input}},
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(input.size()),
out_of_bounds_policy::DONT_CHECK,
stream,
mr);
return std::move(gathered_table->release().front());
}
} // namespace detail
/**
* @copydoc cudf::may_have_nonempty_nulls
*/
bool may_have_nonempty_nulls(column_view const& input)
{
auto const type = input.type().id();
if (not detail::type_may_have_nonempty_nulls(type)) { return false; }
if ((type == type_id::STRING || type == type_id::LIST) && input.has_nulls()) { return true; }
if ((type == type_id::STRUCT || type == type_id::LIST) &&
std::any_of(input.child_begin(), input.child_end(), may_have_nonempty_nulls)) {
return true;
}
return false;
}
/**
* @copydoc cudf::has_nonempty_nulls
*/
bool has_nonempty_nulls(column_view const& input, rmm::cuda_stream_view stream)
{
return detail::has_nonempty_nulls(input, stream);
}
/**
* @copydoc cudf::purge_nonempty_nulls(column_view const&, rmm::mr::device_memory_resource*)
*/
std::unique_ptr<cudf::column> purge_nonempty_nulls(column_view const& input,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return detail::purge_nonempty_nulls(input, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/contiguous_split.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/column/column_view.hpp>
#include <cudf/contiguous_split.hpp>
#include <cudf/detail/contiguous_split.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/lists/lists_column_view.hpp>
#include <cudf/structs/structs_column_view.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/bit.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/binary_search.h>
#include <thrust/execution_policy.h>
#include <thrust/for_each.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/discard_iterator.h>
#include <thrust/iterator/iterator_categories.h>
#include <thrust/iterator/transform_iterator.h>
#include <thrust/pair.h>
#include <thrust/reduce.h>
#include <thrust/scan.h>
#include <thrust/transform.h>
#include <thrust/tuple.h>
#include <cstddef>
#include <numeric>
namespace cudf {
namespace {
// Align all column size allocations to this boundary so that all output column buffers
// start at that alignment.
static constexpr std::size_t split_align = 64;
// The size that contiguous split uses internally as the GPU unit of work.
// The number of `desired_batch_size` batches equals the number of CUDA blocks
// that will be used for the main kernel launch (`copy_partitions`).
static constexpr std::size_t desired_batch_size = 1 * 1024 * 1024;
/**
* @brief Struct which contains information on a source buffer.
*
* The definition of "buffer" used throughout this module is a component piece of a
* cudf column. So for example, a fixed-width column with validity would have 2 associated
* buffers : the data itself and the validity buffer. contiguous_split operates by breaking
* each column up into it's individual components and copying each one as a separate kernel
* block.
*/
struct src_buf_info {
src_buf_info(cudf::type_id _type,
int const* _offsets,
int _offset_stack_pos,
int _parent_offsets_index,
bool _is_validity,
size_type _column_offset)
: type(_type),
offsets(_offsets),
offset_stack_pos(_offset_stack_pos),
parent_offsets_index(_parent_offsets_index),
is_validity(_is_validity),
column_offset(_column_offset)
{
}
cudf::type_id type;
int const* offsets; // a pointer to device memory offsets if I am an offset buffer
int offset_stack_pos; // position in the offset stack buffer
int parent_offsets_index; // immediate parent that has offsets, or -1 if none
bool is_validity; // if I am a validity buffer
size_type column_offset; // offset in the case of a sliced column
};
/**
* @brief Struct which contains information on a destination buffer.
*
* Similar to src_buf_info, dst_buf_info contains information on a destination buffer we
* are going to copy to. If we have N input buffers (which come from X columns), and
* M partitions, then we have N*M destination buffers.
*/
struct dst_buf_info {
// constant across all copy commands for this buffer
std::size_t buf_size; // total size of buffer, including padding
int num_elements; // # of elements to be copied
int element_size; // size of each element in bytes
int num_rows; // # of rows to be copied(which may be different from num_elements in the case of
// validity or offset buffers)
int src_element_index; // element index to start reading from my associated source buffer
std::size_t dst_offset; // my offset into the per-partition allocation
int value_shift; // amount to shift values down by (for offset buffers)
int bit_shift; // # of bits to shift right by (for validity buffers)
size_type valid_count; // validity count for this block of work
int src_buf_index; // source buffer index
int dst_buf_index; // destination buffer index
};
/**
* @brief Copy a single buffer of column data, shifting values (for offset columns),
* and validity (for validity buffers) as necessary.
*
* Copies a single partition of a source column buffer to a destination buffer. Shifts
* element values by value_shift in the case of a buffer of offsets (value_shift will
* only ever be > 0 in that case). Shifts elements bitwise by bit_shift in the case of
* a validity buffer (bit_shift will only ever be > 0 in that case). This function assumes
* value_shift and bit_shift will never be > 0 at the same time.
*
* This function expects:
* - src may be a misaligned address
* - dst must be an aligned address
*
* This function always does the ALU work related to value_shift and bit_shift because it is
* entirely memory-bandwidth bound.
*
* @param dst Destination buffer
* @param src Source buffer
* @param t Thread index
* @param num_elements Number of elements to copy
* @param element_size Size of each element in bytes
* @param src_element_index Element index to start copying at
* @param stride Size of the kernel block
* @param value_shift Shift incoming 4-byte offset values down by this amount
* @param bit_shift Shift incoming data right by this many bits
* @param num_rows Number of rows being copied
* @param valid_count Optional pointer to a value to store count of set bits
*/
template <int block_size>
__device__ void copy_buffer(uint8_t* __restrict__ dst,
uint8_t const* __restrict__ src,
int t,
std::size_t num_elements,
std::size_t element_size,
std::size_t src_element_index,
uint32_t stride,
int value_shift,
int bit_shift,
std::size_t num_rows,
size_type* valid_count)
{
src += (src_element_index * element_size);
size_type thread_valid_count = 0;
// handle misalignment. read 16 bytes in 4 byte reads. write in a single 16 byte store.
std::size_t const num_bytes = num_elements * element_size;
// how many bytes we're misaligned from 4-byte alignment
uint32_t const ofs = reinterpret_cast<uintptr_t>(src) % 4;
std::size_t pos = t * 16;
stride *= 16;
while (pos + 20 <= num_bytes) {
// read from the nearest aligned address.
uint32_t const* in32 = reinterpret_cast<uint32_t const*>((src + pos) - ofs);
uint4 v = uint4{in32[0], in32[1], in32[2], in32[3]};
if (ofs || bit_shift) {
v.x = __funnelshift_r(v.x, v.y, ofs * 8 + bit_shift);
v.y = __funnelshift_r(v.y, v.z, ofs * 8 + bit_shift);
v.z = __funnelshift_r(v.z, v.w, ofs * 8 + bit_shift);
v.w = __funnelshift_r(v.w, in32[4], ofs * 8 + bit_shift);
}
v.x -= value_shift;
v.y -= value_shift;
v.z -= value_shift;
v.w -= value_shift;
reinterpret_cast<uint4*>(dst)[pos / 16] = v;
if (valid_count) {
thread_valid_count += (__popc(v.x) + __popc(v.y) + __popc(v.z) + __popc(v.w));
}
pos += stride;
}
// copy trailing bytes
if (t == 0) {
std::size_t remainder;
if (num_bytes < 16) {
remainder = num_bytes;
} else {
std::size_t const last_bracket = (num_bytes / 16) * 16;
remainder = num_bytes - last_bracket;
if (remainder < 4) {
// we had less than 20 bytes for the last possible 16 byte copy, so copy 16 + the extra
remainder += 16;
}
}
// if we're performing a value shift (offsets), or a bit shift (validity) the # of bytes and
// alignment must be a multiple of 4. value shifting and bit shifting are mutually exclusive
// and will never both be true at the same time.
if (value_shift || bit_shift) {
std::size_t idx = (num_bytes - remainder) / 4;
uint32_t v = remainder > 0 ? (reinterpret_cast<uint32_t const*>(src)[idx] - value_shift) : 0;
constexpr size_type rows_per_element = 32;
auto const have_trailing_bits = ((num_elements * rows_per_element) - num_rows) < bit_shift;
while (remainder) {
// if we're at the very last word of a validity copy, we do not always need to read the next
// word to get the final trailing bits.
auto const read_trailing_bits = bit_shift > 0 && remainder == 4 && have_trailing_bits;
uint32_t const next = (read_trailing_bits || remainder > 4)
? (reinterpret_cast<uint32_t const*>(src)[idx + 1] - value_shift)
: 0;
uint32_t const val = (v >> bit_shift) | (next << (32 - bit_shift));
if (valid_count) { thread_valid_count += __popc(val); }
reinterpret_cast<uint32_t*>(dst)[idx] = val;
v = next;
idx++;
remainder -= 4;
}
} else {
while (remainder) {
std::size_t const idx = num_bytes - remainder--;
uint32_t const val = reinterpret_cast<uint8_t const*>(src)[idx];
if (valid_count) { thread_valid_count += __popc(val); }
reinterpret_cast<uint8_t*>(dst)[idx] = val;
}
}
}
if (valid_count) {
if (num_bytes == 0) {
if (!t) { *valid_count = 0; }
} else {
using BlockReduce = cub::BlockReduce<size_type, block_size>;
__shared__ typename BlockReduce::TempStorage temp_storage;
size_type block_valid_count{BlockReduce(temp_storage).Sum(thread_valid_count)};
if (!t) {
// we may have copied more bits than there are actual rows in the output.
// so we need to subtract off the count of any bits that shouldn't have been
// considered during the copy step.
std::size_t const max_row = (num_bytes * 8);
std::size_t const slack_bits = max_row > num_rows ? max_row - num_rows : 0;
auto const slack_mask = set_most_significant_bits(slack_bits);
if (slack_mask > 0) {
uint32_t const last_word = reinterpret_cast<uint32_t*>(dst + (num_bytes - 4))[0];
block_valid_count -= __popc(last_word & slack_mask);
}
*valid_count = block_valid_count;
}
}
}
}
/**
* @brief Kernel which copies data from multiple source buffers to multiple
* destination buffers.
*
* When doing a contiguous_split on X columns comprising N total internal buffers
* with M splits, we end up having to copy N*M source/destination buffer pairs.
* These logical copies are further subdivided to distribute the amount of work
* to be done as evenly as possible across the multiprocessors on the device.
* This kernel is arranged such that each block copies 1 source/destination pair.
*
* @param index_to_buffer A function that given a `buf_index` returns the destination buffer
* @param src_bufs Input source buffers
* @param buf_info Information on the range of values to be copied for each destination buffer
*/
template <int block_size, typename IndexToDstBuf>
__global__ void copy_partitions(IndexToDstBuf index_to_buffer,
uint8_t const** src_bufs,
dst_buf_info* buf_info)
{
auto const buf_index = blockIdx.x;
auto const src_buf_index = buf_info[buf_index].src_buf_index;
// copy, shifting offsets and validity bits as needed
copy_buffer<block_size>(
index_to_buffer(buf_index) + buf_info[buf_index].dst_offset,
src_bufs[src_buf_index],
threadIdx.x,
buf_info[buf_index].num_elements,
buf_info[buf_index].element_size,
buf_info[buf_index].src_element_index,
blockDim.x,
buf_info[buf_index].value_shift,
buf_info[buf_index].bit_shift,
buf_info[buf_index].num_rows,
buf_info[buf_index].valid_count > 0 ? &buf_info[buf_index].valid_count : nullptr);
}
// The block of functions below are all related:
//
// compute_offset_stack_size()
// setup_src_buf_data()
// count_src_bufs()
// setup_source_buf_info()
// build_output_columns()
//
// Critically, they all traverse the hierarchy of source columns and their children
// in a specific order to guarantee they produce various outputs in a consistent
// way. For example, setup_src_buf_info() produces a series of information
// structs that must appear in the same order that setup_src_buf_data() produces
// buffers.
//
// So please be careful if you change the way in which these functions and
// functors traverse the hierarchy.
/**
* @brief Returns whether or not the specified type is a column that contains offsets.
*/
bool is_offset_type(type_id id) { return (id == type_id::STRING or id == type_id::LIST); }
/**
* @brief Compute total device memory stack size needed to process nested
* offsets per-output buffer.
*
* When determining the range of rows to be copied for each output buffer
* we have to recursively apply the stack of offsets from our parent columns
* (lists or strings). We want to do this computation on the gpu because offsets
* are stored in device memory. However we don't want to do recursion on the gpu, so
* each destination buffer gets a "stack" of space to work with equal in size to
* it's offset nesting depth. This function computes the total size of all of those
* stacks.
*
* This function is called recursively in the case of nested types.
*
* @param begin Beginning of input columns
* @param end End of input columns
* @param offset_depth Current offset nesting depth
*
* @returns Total offset stack size needed for this range of columns
*/
template <typename InputIter>
std::size_t compute_offset_stack_size(InputIter begin, InputIter end, int offset_depth = 0)
{
return std::accumulate(begin, end, 0, [offset_depth](auto stack_size, column_view const& col) {
auto const num_buffers = 1 + (col.nullable() ? 1 : 0);
return stack_size + (offset_depth * num_buffers) +
compute_offset_stack_size(
col.child_begin(), col.child_end(), offset_depth + is_offset_type(col.type().id()));
});
}
/**
* @brief Retrieve all buffers for a range of source columns.
*
* Retrieve the individual buffers that make up a range of input columns.
*
* This function is called recursively in the case of nested types.
*
* @param begin Beginning of input columns
* @param end End of input columns
* @param out_buf Iterator into output buffer infos
*
* @returns next output buffer iterator
*/
template <typename InputIter, typename OutputIter>
OutputIter setup_src_buf_data(InputIter begin, InputIter end, OutputIter out_buf)
{
std::for_each(begin, end, [&out_buf](column_view const& col) {
if (col.nullable()) {
*out_buf = reinterpret_cast<uint8_t const*>(col.null_mask());
out_buf++;
}
// NOTE: we're always returning the base pointer here. column-level offset is accounted
// for later. Also, for some column types (string, list, struct) this pointer will be null
// because there is no associated data with the root column.
*out_buf = col.head<uint8_t>();
out_buf++;
out_buf = setup_src_buf_data(col.child_begin(), col.child_end(), out_buf);
});
return out_buf;
}
/**
* @brief Count the total number of source buffers we will be copying
* from.
*
* This count includes buffers for all input columns. For example a
* fixed-width column with validity would be 2 buffers (data, validity).
* A string column with validity would be 3 buffers (chars, offsets, validity).
*
* This function is called recursively in the case of nested types.
*
* @param begin Beginning of input columns
* @param end End of input columns
*
* @returns total number of source buffers for this range of columns
*/
template <typename InputIter>
size_type count_src_bufs(InputIter begin, InputIter end)
{
auto buf_iter = thrust::make_transform_iterator(begin, [](column_view const& col) {
auto const children_counts = count_src_bufs(col.child_begin(), col.child_end());
return 1 + (col.nullable() ? 1 : 0) + children_counts;
});
return std::accumulate(buf_iter, buf_iter + std::distance(begin, end), 0);
}
/**
* @brief Computes source buffer information for the copy kernel.
*
* For each input column to be split we need to know several pieces of information
* in the copy kernel. This function traverses the input columns and prepares this
* information for the gpu.
*
* This function is called recursively in the case of nested types.
*
* @param begin Beginning of input columns
* @param end End of input columns
* @param head Beginning of source buffer info array
* @param current Current source buffer info to be written to
* @param offset_stack_pos Integer representing our current offset nesting depth
* (how many list or string levels deep we are)
* @param parent_offset_index Index into src_buf_info output array indicating our nearest
* containing list parent. -1 if we have no list parent
* @param offset_depth Current offset nesting depth (how many list levels deep we are)
*
* @returns next src_buf_output after processing this range of input columns
*/
// setup source buf info
template <typename InputIter>
std::pair<src_buf_info*, size_type> setup_source_buf_info(InputIter begin,
InputIter end,
src_buf_info* head,
src_buf_info* current,
rmm::cuda_stream_view stream,
int offset_stack_pos = 0,
int parent_offset_index = -1,
int offset_depth = 0);
/**
* @brief Functor that builds source buffer information based on input columns.
*
* Called by setup_source_buf_info to build information for a single source column. This function
* will recursively call setup_source_buf_info in the case of nested types.
*/
struct buf_info_functor {
src_buf_info* head;
template <typename T>
std::pair<src_buf_info*, size_type> operator()(column_view const& col,
src_buf_info* current,
int offset_stack_pos,
int parent_offset_index,
int offset_depth,
rmm::cuda_stream_view)
{
if (col.nullable()) {
std::tie(current, offset_stack_pos) =
add_null_buffer(col, current, offset_stack_pos, parent_offset_index, offset_depth);
}
// info for the data buffer
*current = src_buf_info(
col.type().id(), nullptr, offset_stack_pos, parent_offset_index, false, col.offset());
return {current + 1, offset_stack_pos + offset_depth};
}
template <typename T, typename... Args>
std::enable_if_t<std::is_same_v<T, cudf::dictionary32>, std::pair<src_buf_info*, size_type>>
operator()(Args&&...)
{
CUDF_FAIL("Unsupported type");
}
private:
std::pair<src_buf_info*, size_type> add_null_buffer(column_view const& col,
src_buf_info* current,
int offset_stack_pos,
int parent_offset_index,
int offset_depth)
{
// info for the validity buffer
*current = src_buf_info(
type_id::INT32, nullptr, offset_stack_pos, parent_offset_index, true, col.offset());
return {current + 1, offset_stack_pos + offset_depth};
}
};
template <>
std::pair<src_buf_info*, size_type> buf_info_functor::operator()<cudf::string_view>(
column_view const& col,
src_buf_info* current,
int offset_stack_pos,
int parent_offset_index,
int offset_depth,
rmm::cuda_stream_view)
{
if (col.nullable()) {
std::tie(current, offset_stack_pos) =
add_null_buffer(col, current, offset_stack_pos, parent_offset_index, offset_depth);
}
// string columns hold no actual data, but we need to keep a record
// of it so we know it's size when we are constructing the output columns
*current = src_buf_info(
type_id::STRING, nullptr, offset_stack_pos, parent_offset_index, false, col.offset());
current++;
offset_stack_pos += offset_depth;
// string columns don't necessarily have children
if (col.num_children() > 0) {
CUDF_EXPECTS(col.num_children() == 2, "Encountered malformed string column");
strings_column_view scv(col);
// info for the offsets buffer
auto offset_col = current;
CUDF_EXPECTS(not scv.offsets().nullable(), "Encountered nullable string offsets column");
*current = src_buf_info(type_id::INT32,
// note: offsets can be null in the case where the string column
// has been created with empty_like().
scv.offsets().begin<cudf::id_to_type<type_id::INT32>>(),
offset_stack_pos,
parent_offset_index,
false,
col.offset());
current++;
offset_stack_pos += offset_depth;
// since we are crossing an offset boundary, calculate our new depth and parent offset index.
offset_depth++;
parent_offset_index = offset_col - head;
// prevent appending buf_info for non-existent chars buffer
CUDF_EXPECTS(not scv.chars().nullable(), "Encountered nullable string chars column");
// info for the chars buffer
*current = src_buf_info(
type_id::INT8, nullptr, offset_stack_pos, parent_offset_index, false, col.offset());
current++;
offset_stack_pos += offset_depth;
}
return {current, offset_stack_pos};
}
template <>
std::pair<src_buf_info*, size_type> buf_info_functor::operator()<cudf::list_view>(
column_view const& col,
src_buf_info* current,
int offset_stack_pos,
int parent_offset_index,
int offset_depth,
rmm::cuda_stream_view stream)
{
lists_column_view lcv(col);
if (col.nullable()) {
std::tie(current, offset_stack_pos) =
add_null_buffer(col, current, offset_stack_pos, parent_offset_index, offset_depth);
}
// list columns hold no actual data, but we need to keep a record
// of it so we know it's size when we are constructing the output columns
*current = src_buf_info(
type_id::LIST, nullptr, offset_stack_pos, parent_offset_index, false, col.offset());
current++;
offset_stack_pos += offset_depth;
CUDF_EXPECTS(col.num_children() == 2, "Encountered malformed list column");
// info for the offsets buffer
auto offset_col = current;
*current = src_buf_info(type_id::INT32,
// note: offsets can be null in the case where the lists column
// has been created with empty_like().
lcv.offsets().begin<cudf::id_to_type<type_id::INT32>>(),
offset_stack_pos,
parent_offset_index,
false,
col.offset());
current++;
offset_stack_pos += offset_depth;
// since we are crossing an offset boundary, calculate our new depth and parent offset index.
offset_depth++;
parent_offset_index = offset_col - head;
return setup_source_buf_info(col.child_begin() + 1,
col.child_end(),
head,
current,
stream,
offset_stack_pos,
parent_offset_index,
offset_depth);
}
template <>
std::pair<src_buf_info*, size_type> buf_info_functor::operator()<cudf::struct_view>(
column_view const& col,
src_buf_info* current,
int offset_stack_pos,
int parent_offset_index,
int offset_depth,
rmm::cuda_stream_view stream)
{
if (col.nullable()) {
std::tie(current, offset_stack_pos) =
add_null_buffer(col, current, offset_stack_pos, parent_offset_index, offset_depth);
}
// struct columns hold no actual data, but we need to keep a record
// of it so we know it's size when we are constructing the output columns
*current = src_buf_info(
type_id::STRUCT, nullptr, offset_stack_pos, parent_offset_index, false, col.offset());
current++;
offset_stack_pos += offset_depth;
// recurse on children
cudf::structs_column_view scv(col);
std::vector<column_view> sliced_children;
sliced_children.reserve(scv.num_children());
std::transform(
thrust::make_counting_iterator(0),
thrust::make_counting_iterator(scv.num_children()),
std::back_inserter(sliced_children),
[&scv, &stream](size_type child_index) { return scv.get_sliced_child(child_index, stream); });
return setup_source_buf_info(sliced_children.begin(),
sliced_children.end(),
head,
current,
stream,
offset_stack_pos,
parent_offset_index,
offset_depth);
}
template <typename InputIter>
std::pair<src_buf_info*, size_type> setup_source_buf_info(InputIter begin,
InputIter end,
src_buf_info* head,
src_buf_info* current,
rmm::cuda_stream_view stream,
int offset_stack_pos,
int parent_offset_index,
int offset_depth)
{
std::for_each(begin, end, [&](column_view const& col) {
std::tie(current, offset_stack_pos) = cudf::type_dispatcher(col.type(),
buf_info_functor{head},
col,
current,
offset_stack_pos,
parent_offset_index,
offset_depth,
stream);
});
return {current, offset_stack_pos};
}
/**
* @brief Given a column, processed split buffers, and a metadata builder, populate
* the metadata for this column in the builder, and return a tuple of:
* column size, data offset, bitmask offset and null count.
*
* @param src column_view to create metadata from
* @param current_info dst_buf_info pointer reference, pointing to this column's buffer info
* This is a pointer reference because it is updated by this function as the
* columns's validity and data buffers are visited
* @param mb A metadata_builder instance to update with the column's packed metadata
* @param use_src_null_count True for the chunked_pack case where current_info has invalid null
* count information. The null count should be taken
* from `src` because this case is restricted to a single partition
* (no splits)
* @returns a std::tuple containing:
* column size, data offset, bitmask offset, and null count
*/
template <typename BufInfo>
std::tuple<size_type, int64_t, int64_t, size_type> build_output_column_metadata(
column_view const& src,
BufInfo& current_info,
detail::metadata_builder& mb,
bool use_src_null_count)
{
auto [bitmask_offset, null_count] = [&]() {
if (src.nullable()) {
// offsets in the existing serialized_column metadata are int64_t
// that's the reason for the casting in this code.
int64_t const bitmask_offset =
current_info->num_elements == 0
? -1 // this means that the bitmask buffer pointer should be nullptr
: static_cast<int64_t>(current_info->dst_offset);
// use_src_null_count is used for the chunked contig split case, where we have
// no splits: the null_count is just the source column's null_count
size_type const null_count = use_src_null_count
? src.null_count()
: (current_info->num_elements == 0
? 0
: (current_info->num_rows - current_info->valid_count));
++current_info;
return std::pair(bitmask_offset, null_count);
}
return std::pair(static_cast<int64_t>(-1), 0);
}();
// size/data pointer for the column
auto const col_size = static_cast<size_type>(current_info->num_elements);
int64_t const data_offset = src.num_children() > 0 || col_size == 0 || src.head() == nullptr
? -1
: static_cast<int64_t>(current_info->dst_offset);
mb.add_column_info_to_meta(
src.type(), col_size, null_count, data_offset, bitmask_offset, src.num_children());
++current_info;
return {col_size, data_offset, bitmask_offset, null_count};
}
/**
* @brief Given a set of input columns and processed split buffers, produce
* output columns.
*
* After performing the split we are left with 1 large buffer per incoming split
* partition. We need to traverse this buffer and distribute the individual
* subpieces that represent individual columns and children to produce the final
* output columns.
*
* This function is called recursively in the case of nested types.
*
* @param begin Beginning of input columns
* @param end End of input columns
* @param info_begin Iterator of dst_buf_info structs containing information about each
* copied buffer
* @param out_begin Output iterator of column views
* @param base_ptr Pointer to the base address of copied data for the working partition
*
* @returns new dst_buf_info iterator after processing this range of input columns
*/
template <typename InputIter, typename BufInfo, typename Output>
BufInfo build_output_columns(InputIter begin,
InputIter end,
BufInfo info_begin,
Output out_begin,
uint8_t const* const base_ptr,
detail::metadata_builder& mb)
{
auto current_info = info_begin;
std::transform(begin, end, out_begin, [¤t_info, base_ptr, &mb](column_view const& src) {
auto [col_size, data_offset, bitmask_offset, null_count] =
build_output_column_metadata<BufInfo>(src, current_info, mb, false);
auto const bitmask_ptr =
base_ptr != nullptr && bitmask_offset != -1
? reinterpret_cast<bitmask_type const*>(base_ptr + static_cast<uint64_t>(bitmask_offset))
: nullptr;
// size/data pointer for the column
uint8_t const* data_ptr = base_ptr != nullptr && data_offset != -1
? base_ptr + static_cast<uint64_t>(data_offset)
: nullptr;
// children
auto children = std::vector<column_view>{};
children.reserve(src.num_children());
current_info = build_output_columns(
src.child_begin(), src.child_end(), current_info, std::back_inserter(children), base_ptr, mb);
return column_view{
src.type(), col_size, data_ptr, bitmask_ptr, null_count, 0, std::move(children)};
});
return current_info;
}
/**
* @brief Given a set of input columns, processed split buffers, and a metadata_builder,
* append column metadata using the builder.
*
* After performing the split we are left with 1 large buffer per incoming split
* partition. We need to traverse this buffer and distribute the individual
* subpieces that represent individual columns and children to produce the final
* output columns.
*
* This function is called recursively in the case of nested types.
*
* @param begin Beginning of input columns
* @param end End of input columns
* @param info_begin Iterator of dst_buf_info structs containing information about each
* copied buffer
* @param mb packed column metadata builder
*
* @returns new dst_buf_info iterator after processing this range of input columns
*/
template <typename InputIter, typename BufInfo>
BufInfo populate_metadata(InputIter begin,
InputIter end,
BufInfo info_begin,
detail::metadata_builder& mb)
{
auto current_info = info_begin;
std::for_each(begin, end, [¤t_info, &mb](column_view const& src) {
build_output_column_metadata<BufInfo>(src, current_info, mb, true);
// children
current_info = populate_metadata(src.child_begin(), src.child_end(), current_info, mb);
});
return current_info;
}
/**
* @brief Functor that retrieves the size of a destination buffer
*/
struct buf_size_functor {
dst_buf_info const* ci;
std::size_t operator() __device__(int index) { return ci[index].buf_size; }
};
/**
* @brief Functor that retrieves the split "key" for a given output
* buffer index.
*
* The key is simply the partition index.
*/
struct split_key_functor {
int const num_src_bufs;
int operator() __device__(int buf_index) const { return buf_index / num_src_bufs; }
};
/**
* @brief Output iterator for writing values to the dst_offset field of the
* dst_buf_info struct
*/
struct dst_offset_output_iterator {
dst_buf_info* c;
using value_type = std::size_t;
using difference_type = std::size_t;
using pointer = std::size_t*;
using reference = std::size_t&;
using iterator_category = thrust::output_device_iterator_tag;
dst_offset_output_iterator operator+ __host__ __device__(int i) { return {c + i}; }
void operator++ __host__ __device__() { c++; }
reference operator[] __device__(int i) { return dereference(c + i); }
reference operator* __device__() { return dereference(c); }
private:
reference __device__ dereference(dst_buf_info* c) { return c->dst_offset; }
};
/**
* @brief Output iterator for writing values to the valid_count field of the
* dst_buf_info struct
*/
struct dst_valid_count_output_iterator {
dst_buf_info* c;
using value_type = size_type;
using difference_type = size_type;
using pointer = size_type*;
using reference = size_type&;
using iterator_category = thrust::output_device_iterator_tag;
dst_valid_count_output_iterator operator+ __host__ __device__(int i)
{
return dst_valid_count_output_iterator{c + i};
}
void operator++ __host__ __device__() { c++; }
reference operator[] __device__(int i) { return dereference(c + i); }
reference operator* __device__() { return dereference(c); }
private:
reference __device__ dereference(dst_buf_info* c) { return c->valid_count; }
};
/**
* @brief Functor for computing size of data elements for a given cudf type.
*
* Note: columns types which themselves inherently have no data (strings, lists,
* structs) return 0.
*/
struct size_of_helper {
template <typename T>
constexpr std::enable_if_t<not is_fixed_width<T>(), int> __device__ operator()() const
{
return 0;
}
template <typename T>
constexpr std::enable_if_t<is_fixed_width<T>(), int> __device__ operator()() const noexcept
{
return sizeof(cudf::device_storage_type_t<T>);
}
};
/**
* @brief Functor for returning the number of batches an input buffer is being
* subdivided into during the repartitioning step.
*
* Note: columns types which themselves inherently have no data (strings, lists,
* structs) return 0.
*/
struct num_batches_func {
thrust::pair<std::size_t, std::size_t> const* const batches;
__device__ std::size_t operator()(size_type i) const { return thrust::get<0>(batches[i]); }
};
/**
* @brief Get the size in bytes of a batch described by `dst_buf_info`.
*/
struct batch_byte_size_function {
size_type const num_batches;
dst_buf_info const* const infos;
__device__ std::size_t operator()(size_type i) const
{
if (i == num_batches) { return 0; }
auto const& buf = *(infos + i);
std::size_t const bytes =
static_cast<std::size_t>(buf.num_elements) * static_cast<std::size_t>(buf.element_size);
return util::round_up_unsafe(bytes, split_align);
}
};
/**
* @brief Get the input buffer index given the output buffer index.
*/
struct out_to_in_index_function {
size_type const* const batch_offsets;
int const num_bufs;
__device__ int operator()(size_type i) const
{
return static_cast<size_type>(
thrust::upper_bound(thrust::seq, batch_offsets, batch_offsets + num_bufs + 1, i) -
batch_offsets) -
1;
}
};
// packed block of memory 1: split indices and src_buf_info structs
struct packed_split_indices_and_src_buf_info {
packed_split_indices_and_src_buf_info(cudf::table_view const& input,
std::vector<size_type> const& splits,
std::size_t num_partitions,
cudf::size_type num_src_bufs,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* temp_mr)
: indices_size(
cudf::util::round_up_safe((num_partitions + 1) * sizeof(size_type), split_align)),
src_buf_info_size(
cudf::util::round_up_safe(num_src_bufs * sizeof(src_buf_info), split_align)),
// host-side
h_indices_and_source_info(indices_size + src_buf_info_size),
h_indices{reinterpret_cast<size_type*>(h_indices_and_source_info.data())},
h_src_buf_info{
reinterpret_cast<src_buf_info*>(h_indices_and_source_info.data() + indices_size)}
{
// compute splits -> indices.
// these are row numbers per split
h_indices[0] = 0;
h_indices[num_partitions] = input.column(0).size();
std::copy(splits.begin(), splits.end(), std::next(h_indices));
// setup source buf info
setup_source_buf_info(input.begin(), input.end(), h_src_buf_info, h_src_buf_info, stream);
offset_stack_partition_size = compute_offset_stack_size(input.begin(), input.end());
offset_stack_size = offset_stack_partition_size * num_partitions * sizeof(size_type);
// device-side
// gpu-only : stack space needed for nested list offset calculation
d_indices_and_source_info =
rmm::device_buffer(indices_size + src_buf_info_size + offset_stack_size, stream, temp_mr);
d_indices = reinterpret_cast<size_type*>(d_indices_and_source_info.data());
d_src_buf_info = reinterpret_cast<src_buf_info*>(
reinterpret_cast<uint8_t*>(d_indices_and_source_info.data()) + indices_size);
d_offset_stack =
reinterpret_cast<size_type*>(reinterpret_cast<uint8_t*>(d_indices_and_source_info.data()) +
indices_size + src_buf_info_size);
CUDF_CUDA_TRY(cudaMemcpyAsync(
d_indices, h_indices, indices_size + src_buf_info_size, cudaMemcpyDefault, stream.value()));
}
size_type const indices_size;
std::size_t const src_buf_info_size;
std::size_t offset_stack_size;
std::vector<uint8_t> h_indices_and_source_info;
rmm::device_buffer d_indices_and_source_info;
size_type* const h_indices;
src_buf_info* const h_src_buf_info;
int offset_stack_partition_size;
size_type* d_indices;
src_buf_info* d_src_buf_info;
size_type* d_offset_stack;
};
// packed block of memory 2: partition buffer sizes and dst_buf_info structs
struct packed_partition_buf_size_and_dst_buf_info {
packed_partition_buf_size_and_dst_buf_info(std::size_t num_partitions,
std::size_t num_bufs,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* temp_mr)
: stream(stream),
buf_sizes_size{cudf::util::round_up_safe(num_partitions * sizeof(std::size_t), split_align)},
dst_buf_info_size{cudf::util::round_up_safe(num_bufs * sizeof(dst_buf_info), split_align)},
// host-side
h_buf_sizes_and_dst_info(buf_sizes_size + dst_buf_info_size),
h_buf_sizes{reinterpret_cast<std::size_t*>(h_buf_sizes_and_dst_info.data())},
h_dst_buf_info{
reinterpret_cast<dst_buf_info*>(h_buf_sizes_and_dst_info.data() + buf_sizes_size)},
// device-side
d_buf_sizes_and_dst_info(buf_sizes_size + dst_buf_info_size, stream, temp_mr),
d_buf_sizes{reinterpret_cast<std::size_t*>(d_buf_sizes_and_dst_info.data())},
// destination buffer info
d_dst_buf_info{reinterpret_cast<dst_buf_info*>(
static_cast<uint8_t*>(d_buf_sizes_and_dst_info.data()) + buf_sizes_size)}
{
}
void copy_to_host()
{
// DtoH buf sizes and col info back to the host
CUDF_CUDA_TRY(cudaMemcpyAsync(h_buf_sizes,
d_buf_sizes,
buf_sizes_size + dst_buf_info_size,
cudaMemcpyDefault,
stream.value()));
}
rmm::cuda_stream_view const stream;
// buffer sizes and destination info (used in batched copies)
std::size_t const buf_sizes_size;
std::size_t const dst_buf_info_size;
std::vector<uint8_t> h_buf_sizes_and_dst_info;
std::size_t* const h_buf_sizes;
dst_buf_info* const h_dst_buf_info;
rmm::device_buffer d_buf_sizes_and_dst_info;
std::size_t* const d_buf_sizes;
dst_buf_info* const d_dst_buf_info;
};
// Packed block of memory 3:
// Pointers to source and destination buffers (and stack space on the
// gpu for offset computation)
struct packed_src_and_dst_pointers {
packed_src_and_dst_pointers(cudf::table_view const& input,
std::size_t num_partitions,
cudf::size_type num_src_bufs,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* temp_mr)
: stream(stream),
src_bufs_size{cudf::util::round_up_safe(num_src_bufs * sizeof(uint8_t*), split_align)},
dst_bufs_size{cudf::util::round_up_safe(num_partitions * sizeof(uint8_t*), split_align)},
// host-side
h_src_and_dst_buffers(src_bufs_size + dst_bufs_size),
h_src_bufs{reinterpret_cast<uint8_t const**>(h_src_and_dst_buffers.data())},
h_dst_bufs{reinterpret_cast<uint8_t**>(h_src_and_dst_buffers.data() + src_bufs_size)},
// device-side
d_src_and_dst_buffers{rmm::device_buffer(src_bufs_size + dst_bufs_size, stream, temp_mr)},
d_src_bufs{reinterpret_cast<uint8_t const**>(d_src_and_dst_buffers.data())},
d_dst_bufs{reinterpret_cast<uint8_t**>(
reinterpret_cast<uint8_t*>(d_src_and_dst_buffers.data()) + src_bufs_size)}
{
// setup src buffers
setup_src_buf_data(input.begin(), input.end(), h_src_bufs);
}
void copy_to_device()
{
CUDF_CUDA_TRY(cudaMemcpyAsync(d_src_and_dst_buffers.data(),
h_src_and_dst_buffers.data(),
src_bufs_size + dst_bufs_size,
cudaMemcpyDefault,
stream.value()));
}
rmm::cuda_stream_view const stream;
std::size_t const src_bufs_size;
std::size_t const dst_bufs_size;
std::vector<uint8_t> h_src_and_dst_buffers;
uint8_t const** const h_src_bufs;
uint8_t** const h_dst_bufs;
rmm::device_buffer d_src_and_dst_buffers;
uint8_t const** const d_src_bufs;
uint8_t** const d_dst_bufs;
};
/**
* @brief Create an instance of `packed_src_and_dst_pointers` populating destination
* partitition buffers (if any) from `out_buffers`. In the chunked_pack case
* `out_buffers` is empty, and the destination pointer is provided separately
* to the `copy_partitions` kernel.
*
* @param input source table view
* @param num_partitions the number of partitions (1 meaning no splits)
* @param num_src_bufs number of buffers for the source columns including children
* @param out_buffers the destination buffers per partition if in the non-chunked case
* @param stream Optional CUDA stream on which to execute kernels
* @param temp_mr A memory resource for temporary and scratch space
*
* @returns new unique pointer to packed_src_and_dst_pointers
*/
std::unique_ptr<packed_src_and_dst_pointers> setup_src_and_dst_pointers(
cudf::table_view const& input,
std::size_t num_partitions,
cudf::size_type num_src_bufs,
std::vector<rmm::device_buffer>& out_buffers,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* temp_mr)
{
auto src_and_dst_pointers = std::make_unique<packed_src_and_dst_pointers>(
input, num_partitions, num_src_bufs, stream, temp_mr);
std::transform(
out_buffers.begin(), out_buffers.end(), src_and_dst_pointers->h_dst_bufs, [](auto& buf) {
return static_cast<uint8_t*>(buf.data());
});
// copy the struct to device memory to access from the kernel
src_and_dst_pointers->copy_to_device();
return src_and_dst_pointers;
}
/**
* @brief Create an instance of `packed_partition_buf_size_and_dst_buf_info` containing
* the partition-level dst_buf_info structs for each partition and column buffer.
*
* @param input source table view
* @param splits the numeric value (in rows) for each split, empty for 1 partition
* @param num_partitions the number of partitions create (1 meaning no splits)
* @param num_src_bufs number of buffers for the source columns including children
* @param num_bufs num_src_bufs times the number of partitions
* @param stream Optional CUDA stream on which to execute kernels
* @param temp_mr A memory resource for temporary and scratch space
*
* @returns new unique pointer to `packed_partition_buf_size_and_dst_buf_info`
*/
std::unique_ptr<packed_partition_buf_size_and_dst_buf_info> compute_splits(
cudf::table_view const& input,
std::vector<size_type> const& splits,
std::size_t num_partitions,
cudf::size_type num_src_bufs,
std::size_t num_bufs,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* temp_mr)
{
auto partition_buf_size_and_dst_buf_info =
std::make_unique<packed_partition_buf_size_and_dst_buf_info>(
num_partitions, num_bufs, stream, temp_mr);
auto const d_dst_buf_info = partition_buf_size_and_dst_buf_info->d_dst_buf_info;
auto const d_buf_sizes = partition_buf_size_and_dst_buf_info->d_buf_sizes;
auto const split_indices_and_src_buf_info = packed_split_indices_and_src_buf_info(
input, splits, num_partitions, num_src_bufs, stream, temp_mr);
auto const d_src_buf_info = split_indices_and_src_buf_info.d_src_buf_info;
auto const offset_stack_partition_size =
split_indices_and_src_buf_info.offset_stack_partition_size;
auto const d_offset_stack = split_indices_and_src_buf_info.d_offset_stack;
auto const d_indices = split_indices_and_src_buf_info.d_indices;
// compute sizes of each column in each partition, including alignment.
thrust::transform(
rmm::exec_policy(stream, temp_mr),
thrust::make_counting_iterator<std::size_t>(0),
thrust::make_counting_iterator<std::size_t>(num_bufs),
d_dst_buf_info,
[d_src_buf_info,
offset_stack_partition_size,
d_offset_stack,
d_indices,
num_src_bufs] __device__(std::size_t t) {
int const split_index = t / num_src_bufs;
int const src_buf_index = t % num_src_bufs;
auto const& src_info = d_src_buf_info[src_buf_index];
// apply nested offsets (lists and string columns).
//
// We can't just use the incoming row indices to figure out where to read from in a
// nested list situation. We have to apply offsets every time we cross a boundary
// (list or string). This loop applies those offsets so that our incoming row_index_start
// and row_index_end get transformed to our final values.
//
int const stack_pos = src_info.offset_stack_pos + (split_index * offset_stack_partition_size);
size_type* offset_stack = &d_offset_stack[stack_pos];
int parent_offsets_index = src_info.parent_offsets_index;
int stack_size = 0;
int root_column_offset = src_info.column_offset;
while (parent_offsets_index >= 0) {
offset_stack[stack_size++] = parent_offsets_index;
root_column_offset = d_src_buf_info[parent_offsets_index].column_offset;
parent_offsets_index = d_src_buf_info[parent_offsets_index].parent_offsets_index;
}
// make sure to include the -column- offset on the root column in our calculation.
int row_start = d_indices[split_index] + root_column_offset;
int row_end = d_indices[split_index + 1] + root_column_offset;
while (stack_size > 0) {
stack_size--;
auto const offsets = d_src_buf_info[offset_stack[stack_size]].offsets;
// this case can happen when you have empty string or list columns constructed with
// empty_like()
if (offsets != nullptr) {
row_start = offsets[row_start];
row_end = offsets[row_end];
}
}
// final element indices and row count
int const out_element_index = src_info.is_validity ? row_start / 32 : row_start;
int const num_rows = row_end - row_start;
// if I am an offsets column, all my values need to be shifted
int const value_shift = src_info.offsets == nullptr ? 0 : src_info.offsets[row_start];
// if I am a validity column, we may need to shift bits
int const bit_shift = src_info.is_validity ? row_start % 32 : 0;
// # of rows isn't necessarily the same as # of elements to be copied.
auto const num_elements = [&]() {
if (src_info.offsets != nullptr && num_rows > 0) {
return num_rows + 1;
} else if (src_info.is_validity) {
return (num_rows + 31) / 32;
}
return num_rows;
}();
int const element_size = cudf::type_dispatcher(data_type{src_info.type}, size_of_helper{});
std::size_t const bytes =
static_cast<std::size_t>(num_elements) * static_cast<std::size_t>(element_size);
return dst_buf_info{util::round_up_unsafe(bytes, split_align),
num_elements,
element_size,
num_rows,
out_element_index,
0,
value_shift,
bit_shift,
src_info.is_validity ? 1 : 0,
src_buf_index,
split_index};
});
// compute total size of each partition
// key is the split index
{
auto const keys = cudf::detail::make_counting_transform_iterator(
0, split_key_functor{static_cast<int>(num_src_bufs)});
auto values =
cudf::detail::make_counting_transform_iterator(0, buf_size_functor{d_dst_buf_info});
thrust::reduce_by_key(rmm::exec_policy(stream, temp_mr),
keys,
keys + num_bufs,
values,
thrust::make_discard_iterator(),
d_buf_sizes);
}
// compute start offset for each output buffer for each split
{
auto const keys = cudf::detail::make_counting_transform_iterator(
0, split_key_functor{static_cast<int>(num_src_bufs)});
auto values =
cudf::detail::make_counting_transform_iterator(0, buf_size_functor{d_dst_buf_info});
thrust::exclusive_scan_by_key(rmm::exec_policy(stream, temp_mr),
keys,
keys + num_bufs,
values,
dst_offset_output_iterator{d_dst_buf_info},
std::size_t{0});
}
partition_buf_size_and_dst_buf_info->copy_to_host();
stream.synchronize();
return partition_buf_size_and_dst_buf_info;
}
/**
* @brief Struct containing information about the actual batches we will send to the
* `copy_partitions` kernel and the number of iterations we need to carry out this copy.
*
* For the non-chunked contiguous_split case, this contains the batched dst_buf_infos and the
* number of iterations is going to be 1 since the non-chunked case is single pass.
*
* For the chunked_pack case, this also contains the batched dst_buf_infos for all
* iterations in addition to helping keep the state about what batches have been copied so far
* and what are the sizes (in bytes) of each iteration.
*/
struct chunk_iteration_state {
chunk_iteration_state(rmm::device_uvector<dst_buf_info> _d_batched_dst_buf_info,
rmm::device_uvector<size_type> _d_batch_offsets,
std::vector<std::size_t>&& _h_num_buffs_per_iteration,
std::vector<std::size_t>&& _h_size_of_buffs_per_iteration,
std::size_t total_size)
: num_iterations(_h_num_buffs_per_iteration.size()),
current_iteration{0},
starting_batch{0},
d_batched_dst_buf_info(std::move(_d_batched_dst_buf_info)),
d_batch_offsets(std::move(_d_batch_offsets)),
h_num_buffs_per_iteration(std::move(_h_num_buffs_per_iteration)),
h_size_of_buffs_per_iteration(std::move(_h_size_of_buffs_per_iteration)),
total_size(total_size)
{
}
static std::unique_ptr<chunk_iteration_state> create(
rmm::device_uvector<thrust::pair<std::size_t, std::size_t>> const& batches,
int num_bufs,
dst_buf_info* d_orig_dst_buf_info,
std::size_t const* const h_buf_sizes,
std::size_t num_partitions,
std::size_t user_buffer_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* temp_mr);
/**
* @brief As of the time of the call, return the starting 1MB batch index, and the
* number of batches to copy.
*
* @return the current iteration's starting_batch and batch count as a pair
*/
std::pair<std::size_t, std::size_t> get_current_starting_index_and_buff_count() const
{
CUDF_EXPECTS(current_iteration < num_iterations,
"current_iteration cannot exceed num_iterations");
auto count_for_current = h_num_buffs_per_iteration[current_iteration];
return {starting_batch, count_for_current};
}
/**
* @brief Advance the iteration state if there are iterations left, updating the
* starting batch and returning the amount of bytes were copied in the iteration
* we just finished.
* @throws cudf::logic_error If the state was at the last iteration before entering
* this function.
* @return size in bytes that were copied in the finished iteration
*/
std::size_t advance_iteration()
{
CUDF_EXPECTS(current_iteration < num_iterations,
"current_iteration cannot exceed num_iterations");
std::size_t bytes_copied = h_size_of_buffs_per_iteration[current_iteration];
starting_batch += h_num_buffs_per_iteration[current_iteration];
++current_iteration;
return bytes_copied;
}
/**
* Returns true if there are iterations left.
*/
bool has_more_copies() const { return current_iteration < num_iterations; }
rmm::device_uvector<dst_buf_info> d_batched_dst_buf_info; ///< dst_buf_info per 1MB batch
rmm::device_uvector<size_type> const d_batch_offsets; ///< Offset within a batch per dst_buf_info
std::size_t const total_size; ///< The aggregate size of all iterations
int const num_iterations; ///< The total number of iterations
int current_iteration; ///< Marks the current iteration being worked on
private:
std::size_t starting_batch; ///< Starting batch index for the current iteration
std::vector<std::size_t> const h_num_buffs_per_iteration; ///< The count of batches per iteration
std::vector<std::size_t> const
h_size_of_buffs_per_iteration; ///< The size in bytes per iteration
};
std::unique_ptr<chunk_iteration_state> chunk_iteration_state::create(
rmm::device_uvector<thrust::pair<std::size_t, std::size_t>> const& batches,
int num_bufs,
dst_buf_info* d_orig_dst_buf_info,
std::size_t const* const h_buf_sizes,
std::size_t num_partitions,
std::size_t user_buffer_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* temp_mr)
{
rmm::device_uvector<size_type> d_batch_offsets(num_bufs + 1, stream, temp_mr);
auto const buf_count_iter = cudf::detail::make_counting_transform_iterator(
0, [num_bufs, num_batches = num_batches_func{batches.begin()}] __device__(size_type i) {
return i == num_bufs ? 0 : num_batches(i);
});
thrust::exclusive_scan(rmm::exec_policy(stream, temp_mr),
buf_count_iter,
buf_count_iter + num_bufs + 1,
d_batch_offsets.begin(),
0);
auto const num_batches_iter =
cudf::detail::make_counting_transform_iterator(0, num_batches_func{batches.begin()});
size_type const num_batches = thrust::reduce(
rmm::exec_policy(stream, temp_mr), num_batches_iter, num_batches_iter + batches.size());
auto out_to_in_index = out_to_in_index_function{d_batch_offsets.begin(), num_bufs};
auto const iter = thrust::make_counting_iterator(0);
// load up the batches as d_dst_buf_info
rmm::device_uvector<dst_buf_info> d_batched_dst_buf_info(num_batches, stream, temp_mr);
thrust::for_each(
rmm::exec_policy(stream, temp_mr),
iter,
iter + num_batches,
[d_orig_dst_buf_info,
d_batched_dst_buf_info = d_batched_dst_buf_info.begin(),
batches = batches.begin(),
d_batch_offsets = d_batch_offsets.begin(),
out_to_in_index] __device__(size_type i) {
size_type const in_buf_index = out_to_in_index(i);
size_type const batch_index = i - d_batch_offsets[in_buf_index];
auto const batch_size = thrust::get<1>(batches[in_buf_index]);
dst_buf_info const& in = d_orig_dst_buf_info[in_buf_index];
// adjust info
dst_buf_info& out = d_batched_dst_buf_info[i];
out.element_size = in.element_size;
out.value_shift = in.value_shift;
out.bit_shift = in.bit_shift;
out.valid_count =
in.valid_count; // valid count will be set to 1 if this is a validity buffer
out.src_buf_index = in.src_buf_index;
out.dst_buf_index = in.dst_buf_index;
size_type const elements_per_batch =
out.element_size == 0 ? 0 : batch_size / out.element_size;
out.num_elements = ((batch_index + 1) * elements_per_batch) > in.num_elements
? in.num_elements - (batch_index * elements_per_batch)
: elements_per_batch;
size_type const rows_per_batch =
// if this is a validity buffer, each element is a bitmask_type, which
// corresponds to 32 rows.
out.valid_count > 0
? elements_per_batch * static_cast<size_type>(cudf::detail::size_in_bits<bitmask_type>())
: elements_per_batch;
out.num_rows = ((batch_index + 1) * rows_per_batch) > in.num_rows
? in.num_rows - (batch_index * rows_per_batch)
: rows_per_batch;
out.src_element_index = in.src_element_index + (batch_index * elements_per_batch);
out.dst_offset = in.dst_offset + (batch_index * batch_size);
// out.bytes and out.buf_size are unneeded here because they are only used to
// calculate real output buffer sizes. the data we are generating here is
// purely intermediate for the purposes of doing more uniform copying of data
// underneath the final structure of the output
});
/**
* In the chunked case, this is the code that fixes up the offsets of each batch
* and prepares each iteration. Given the batches computed before, it figures
* out the number of batches that will fit in an iteration of `user_buffer_size`.
*
* Specifically, offsets for batches are reset to the 0th byte when a new iteration
* of `user_buffer_size` bytes is needed.
*/
if (user_buffer_size != 0) {
// copy the batch offsets back to host
std::vector<std::size_t> h_offsets(num_batches + 1);
{
rmm::device_uvector<std::size_t> offsets(h_offsets.size(), stream, temp_mr);
auto const batch_byte_size_iter = cudf::detail::make_counting_transform_iterator(
0, batch_byte_size_function{num_batches, d_batched_dst_buf_info.begin()});
thrust::exclusive_scan(rmm::exec_policy(stream, temp_mr),
batch_byte_size_iter,
batch_byte_size_iter + num_batches + 1,
offsets.begin());
CUDF_CUDA_TRY(cudaMemcpyAsync(h_offsets.data(),
offsets.data(),
sizeof(std::size_t) * offsets.size(),
cudaMemcpyDefault,
stream.value()));
// the next part is working on the CPU, so we want to synchronize here
stream.synchronize();
}
std::vector<std::size_t> num_batches_per_iteration;
std::vector<std::size_t> size_of_batches_per_iteration;
std::vector<std::size_t> accum_size_per_iteration;
std::size_t accum_size = 0;
{
auto current_offset_it = h_offsets.begin();
// figure out how many iterations we need, while fitting batches to iterations
// with no more than user_buffer_size bytes worth of batches
while (current_offset_it != h_offsets.end()) {
// next_iteration_it points to the batch right above the boundary (the batch
// that didn't fit).
auto next_iteration_it =
std::lower_bound(current_offset_it,
h_offsets.end(),
// We add the cumulative size + 1 because we want to find what would fit
// within a buffer of user_buffer_size (up to user_buffer_size).
// Since h_offsets is a prefix scan, we add the size we accumulated so
// far so we are looking for the next user_buffer_sized boundary.
user_buffer_size + accum_size + 1);
// we subtract 1 from the number of batch here because next_iteration_it points
// to the batch that didn't fit, so it's one off.
auto batches_in_iter = std::distance(current_offset_it, next_iteration_it) - 1;
// to get the amount of bytes in this iteration we get the prefix scan size
// and subtract the cumulative size so far, leaving the bytes belonging to this
// iteration
auto iter_size_bytes = *(current_offset_it + batches_in_iter) - accum_size;
accum_size += iter_size_bytes;
num_batches_per_iteration.push_back(batches_in_iter);
size_of_batches_per_iteration.push_back(iter_size_bytes);
accum_size_per_iteration.push_back(accum_size);
if (next_iteration_it == h_offsets.end()) { break; }
current_offset_it += batches_in_iter;
}
}
// apply changed offset
{
auto d_accum_size_per_iteration =
cudf::detail::make_device_uvector_async(accum_size_per_iteration, stream, temp_mr);
// we want to update the offset of batches for every iteration, except the first one (because
// offsets in the first iteration are all 0 based)
auto num_batches_in_first_iteration = num_batches_per_iteration[0];
auto const iter = thrust::make_counting_iterator(num_batches_in_first_iteration);
auto num_iterations = accum_size_per_iteration.size();
thrust::for_each(
rmm::exec_policy(stream, temp_mr),
iter,
iter + num_batches - num_batches_in_first_iteration,
[num_iterations,
d_batched_dst_buf_info = d_batched_dst_buf_info.begin(),
d_accum_size_per_iteration = d_accum_size_per_iteration.begin()] __device__(size_type i) {
auto prior_iteration_size =
thrust::upper_bound(thrust::seq,
d_accum_size_per_iteration,
d_accum_size_per_iteration + num_iterations,
d_batched_dst_buf_info[i].dst_offset) -
1;
d_batched_dst_buf_info[i].dst_offset -= *prior_iteration_size;
});
}
return std::make_unique<chunk_iteration_state>(std::move(d_batched_dst_buf_info),
std::move(d_batch_offsets),
std::move(num_batches_per_iteration),
std::move(size_of_batches_per_iteration),
accum_size);
} else {
// we instantiate an "iteration state" for the regular single pass contiguous_split
// consisting of 1 iteration with all of the batches and totalling `total_size` bytes.
auto const total_size = std::reduce(h_buf_sizes, h_buf_sizes + num_partitions);
// 1 iteration with the whole size
return std::make_unique<chunk_iteration_state>(
std::move(d_batched_dst_buf_info),
std::move(d_batch_offsets),
std::move(std::vector<std::size_t>{static_cast<std::size_t>(num_batches)}),
std::move(std::vector<std::size_t>{total_size}),
total_size);
}
}
/**
* @brief Create an instance of `chunk_iteration_state` containing 1MB batches of work
* that are further grouped into chunks or iterations.
*
* This function handles both the `chunked_pack` case: when `user_buffer_size` is non-zero,
* and the single-shot `contiguous_split` case.
*
* @param num_bufs num_src_bufs times the number of partitions
* @param d_dst_buf_info dst_buf_info per partition produced in `compute_splits`
* @param h_buf_sizes size in bytes of a partition (accessible from host)
* @param num_partitions the number of partitions (1 meaning no splits)
* @param user_buffer_size if non-zero, it is the size in bytes that 1MB batches should be
* grouped in, as different iterations.
* @param stream Optional CUDA stream on which to execute kernels
* @param temp_mr A memory resource for temporary and scratch space
*
* @returns new unique pointer to `chunk_iteration_state`
*/
std::unique_ptr<chunk_iteration_state> compute_batches(int num_bufs,
dst_buf_info* const d_dst_buf_info,
std::size_t const* const h_buf_sizes,
std::size_t num_partitions,
std::size_t user_buffer_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* temp_mr)
{
// Since we parallelize at one block per copy, performance is vulnerable to situations where we
// have small numbers of copies to do (a combination of small numbers of splits and/or columns),
// so we will take the actual set of outgoing source/destination buffers and further partition
// them into much smaller batches in order to drive up the number of blocks and overall
// occupancy.
rmm::device_uvector<thrust::pair<std::size_t, std::size_t>> batches(num_bufs, stream, temp_mr);
thrust::transform(
rmm::exec_policy(stream, temp_mr),
d_dst_buf_info,
d_dst_buf_info + num_bufs,
batches.begin(),
[desired_batch_size = desired_batch_size] __device__(
dst_buf_info const& buf) -> thrust::pair<std::size_t, std::size_t> {
// Total bytes for this incoming partition
std::size_t const bytes =
static_cast<std::size_t>(buf.num_elements) * static_cast<std::size_t>(buf.element_size);
// This clause handles nested data types (e.g. list or string) that store no data in the row
// columns, only in their children.
if (bytes == 0) { return {1, 0}; }
// The number of batches we want to subdivide this buffer into
std::size_t const num_batches = std::max(
std::size_t{1}, util::round_up_unsafe(bytes, desired_batch_size) / desired_batch_size);
// NOTE: leaving batch size as a separate parameter for future tuning
// possibilities, even though in the current implementation it will be a
// constant.
return {num_batches, desired_batch_size};
});
return chunk_iteration_state::create(batches,
num_bufs,
d_dst_buf_info,
h_buf_sizes,
num_partitions,
user_buffer_size,
stream,
temp_mr);
}
void copy_data(int num_batches_to_copy,
int starting_batch,
uint8_t const** d_src_bufs,
uint8_t** d_dst_bufs,
rmm::device_uvector<dst_buf_info>& d_dst_buf_info,
uint8_t* user_buffer,
rmm::cuda_stream_view stream)
{
constexpr size_type block_size = 256;
if (user_buffer != nullptr) {
auto index_to_buffer = [user_buffer] __device__(unsigned int) { return user_buffer; };
copy_partitions<block_size><<<num_batches_to_copy, block_size, 0, stream.value()>>>(
index_to_buffer, d_src_bufs, d_dst_buf_info.data() + starting_batch);
} else {
auto index_to_buffer = [d_dst_bufs,
dst_buf_info = d_dst_buf_info.data(),
user_buffer] __device__(unsigned int buf_index) {
auto const dst_buf_index = dst_buf_info[buf_index].dst_buf_index;
return d_dst_bufs[dst_buf_index];
};
copy_partitions<block_size><<<num_batches_to_copy, block_size, 0, stream.value()>>>(
index_to_buffer, d_src_bufs, d_dst_buf_info.data() + starting_batch);
}
}
/**
* @brief Function that checks an input table_view and splits for specific edge cases.
*
* It will return true if the input is "empty" (no rows or columns), which means
* special handling has to happen in the calling code.
*
* @param input table_view of source table to be split
* @param splits the splits specified by the user, or an empty vector if no splits
* @returns true if the input is empty, false otherwise
*/
bool check_inputs(cudf::table_view const& input, std::vector<size_type> const& splits)
{
if (input.num_columns() == 0) { return true; }
if (splits.size() > 0) {
CUDF_EXPECTS(splits.back() <= input.column(0).size(),
"splits can't exceed size of input columns");
}
size_type begin = 0;
for (auto end : splits) {
CUDF_EXPECTS(begin >= 0, "Starting index cannot be negative.");
CUDF_EXPECTS(end >= begin, "End index cannot be smaller than the starting index.");
CUDF_EXPECTS(end <= input.column(0).size(), "Slice range out of bounds.");
begin = end;
}
return input.column(0).size() == 0;
}
}; // anonymous namespace
namespace detail {
/**
* @brief A helper struct containing the state of contiguous_split, whether the caller
* is using the single-pass contiguous_split or chunked_pack.
*
* It exposes an iterator-like pattern where contiguous_split_state::has_next()
* returns true when there is work to be done, and false otherwise.
*
* contiguous_split_state::contiguous_split() performs a single-pass contiguous_split
* and is valid iff contiguous_split_state is instantiated with 0 for the user_buffer_size.
*
* contiguous_split_state::contiguous_split_chunk(device_span) is only valid when
* user_buffer_size > 0. It should be called as long as has_next() returns true. The
* device_span passed to contiguous_split_chunk must be allocated in stream `stream` by
* the user.
*
* None of the methods are thread safe.
*/
struct contiguous_split_state {
contiguous_split_state(cudf::table_view const& input,
std::size_t user_buffer_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr,
rmm::mr::device_memory_resource* temp_mr)
: contiguous_split_state(input, {}, user_buffer_size, stream, mr, temp_mr)
{
}
contiguous_split_state(cudf::table_view const& input,
std::vector<size_type> const& splits,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr,
rmm::mr::device_memory_resource* temp_mr)
: contiguous_split_state(input, splits, 0, stream, mr, temp_mr)
{
}
bool has_next() const { return !is_empty && chunk_iter_state->has_more_copies(); }
std::size_t get_total_contiguous_size() const
{
return is_empty ? 0 : chunk_iter_state->total_size;
}
std::vector<packed_table> contiguous_split()
{
CUDF_EXPECTS(user_buffer_size == 0, "Cannot contiguous split with a user buffer");
if (is_empty || input.num_columns() == 0) { return make_packed_tables(); }
auto const num_batches_total =
std::get<1>(chunk_iter_state->get_current_starting_index_and_buff_count());
// perform the copy.
copy_data(num_batches_total,
0 /* starting at buffer for single-shot 0*/,
src_and_dst_pointers->d_src_bufs,
src_and_dst_pointers->d_dst_bufs,
chunk_iter_state->d_batched_dst_buf_info,
nullptr,
stream);
// these "orig" dst_buf_info pointers describe the prior-to-batching destination
// buffers per partition
auto d_orig_dst_buf_info = partition_buf_size_and_dst_buf_info->d_dst_buf_info;
auto h_orig_dst_buf_info = partition_buf_size_and_dst_buf_info->h_dst_buf_info;
// postprocess valid_counts: apply the valid counts computed by copy_data for each
// batch back to the original dst_buf_infos
auto const keys = cudf::detail::make_counting_transform_iterator(
0, out_to_in_index_function{chunk_iter_state->d_batch_offsets.begin(), (int)num_bufs});
auto values = thrust::make_transform_iterator(
chunk_iter_state->d_batched_dst_buf_info.begin(),
[] __device__(dst_buf_info const& info) { return info.valid_count; });
thrust::reduce_by_key(rmm::exec_policy(stream, temp_mr),
keys,
keys + num_batches_total,
values,
thrust::make_discard_iterator(),
dst_valid_count_output_iterator{d_orig_dst_buf_info});
CUDF_CUDA_TRY(cudaMemcpyAsync(h_orig_dst_buf_info,
d_orig_dst_buf_info,
partition_buf_size_and_dst_buf_info->dst_buf_info_size,
cudaMemcpyDefault,
stream.value()));
stream.synchronize();
// not necessary for the non-chunked case, but it makes it so further calls to has_next
// return false, just in case
chunk_iter_state->advance_iteration();
return make_packed_tables();
}
cudf::size_type contiguous_split_chunk(cudf::device_span<uint8_t> const& user_buffer)
{
CUDF_FUNC_RANGE();
CUDF_EXPECTS(
user_buffer.size() == user_buffer_size,
"Cannot use a device span smaller than the output buffer size configured at instantiation!");
CUDF_EXPECTS(has_next(), "Cannot call contiguous_split_chunk with has_next() == false!");
auto [starting_batch, num_batches_to_copy] =
chunk_iter_state->get_current_starting_index_and_buff_count();
// perform the copy.
copy_data(num_batches_to_copy,
starting_batch,
src_and_dst_pointers->d_src_bufs,
src_and_dst_pointers->d_dst_bufs,
chunk_iter_state->d_batched_dst_buf_info,
user_buffer.data(),
stream);
// We do not need to post-process null counts since the null count info is
// taken from the source table in the contiguous_split_chunk case (no splits)
return chunk_iter_state->advance_iteration();
}
std::unique_ptr<std::vector<uint8_t>> build_packed_column_metadata()
{
CUDF_EXPECTS(num_partitions == 1, "build_packed_column_metadata supported only without splits");
if (input.num_columns() == 0) { return std::unique_ptr<std::vector<uint8_t>>(); }
if (is_empty) {
// this is a bit ugly, but it was done to re-use make_empty_packed_table between the
// regular contiguous_split and chunked_pack cases.
auto empty_packed_tables = std::move(make_empty_packed_table().front());
return std::move(empty_packed_tables.data.metadata);
}
auto& h_dst_buf_info = partition_buf_size_and_dst_buf_info->h_dst_buf_info;
auto cur_dst_buf_info = h_dst_buf_info;
detail::metadata_builder mb{input.num_columns()};
populate_metadata(input.begin(), input.end(), cur_dst_buf_info, mb);
return std::make_unique<std::vector<uint8_t>>(std::move(mb.build()));
}
private:
contiguous_split_state(cudf::table_view const& input,
std::vector<size_type> const& splits,
std::size_t user_buffer_size,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr,
rmm::mr::device_memory_resource* temp_mr)
: input(input),
user_buffer_size(user_buffer_size),
stream(stream),
mr(mr),
temp_mr(temp_mr),
is_empty{check_inputs(input, splits)},
num_partitions{splits.size() + 1},
num_src_bufs{count_src_bufs(input.begin(), input.end())},
num_bufs{num_src_bufs * num_partitions}
{
// if the table we are about to contig split is empty, we have special
// handling where metadata is produced and a 0-byte contiguous buffer
// is the result.
if (is_empty) { return; }
// First pass over the source tables to generate a `dst_buf_info` per split and column buffer
// (`num_bufs`). After this, contiguous_split uses `dst_buf_info` to further subdivide the work
// into 1MB batches in `compute_batches`
partition_buf_size_and_dst_buf_info = std::move(
compute_splits(input, splits, num_partitions, num_src_bufs, num_bufs, stream, temp_mr));
// Second pass: uses `dst_buf_info` to break down the work into 1MB batches.
chunk_iter_state = compute_batches(num_bufs,
partition_buf_size_and_dst_buf_info->d_dst_buf_info,
partition_buf_size_and_dst_buf_info->h_buf_sizes,
num_partitions,
user_buffer_size,
stream,
temp_mr);
// allocate output partition buffers, in the non-chunked case
if (user_buffer_size == 0) {
out_buffers.reserve(num_partitions);
auto h_buf_sizes = partition_buf_size_and_dst_buf_info->h_buf_sizes;
std::transform(h_buf_sizes,
h_buf_sizes + num_partitions,
std::back_inserter(out_buffers),
[stream = stream, mr = mr](std::size_t bytes) {
return rmm::device_buffer{bytes, stream, mr};
});
}
src_and_dst_pointers = std::move(setup_src_and_dst_pointers(
input, num_partitions, num_src_bufs, out_buffers, stream, temp_mr));
}
std::vector<packed_table> make_packed_tables()
{
if (input.num_columns() == 0) { return std::vector<packed_table>(); }
if (is_empty) { return make_empty_packed_table(); }
std::vector<packed_table> result;
result.reserve(num_partitions);
std::vector<column_view> cols;
cols.reserve(input.num_columns());
auto& h_dst_buf_info = partition_buf_size_and_dst_buf_info->h_dst_buf_info;
auto& h_dst_bufs = src_and_dst_pointers->h_dst_bufs;
auto cur_dst_buf_info = h_dst_buf_info;
detail::metadata_builder mb(input.num_columns());
for (std::size_t idx = 0; idx < num_partitions; idx++) {
// traverse the buffers and build the columns.
cur_dst_buf_info = build_output_columns(input.begin(),
input.end(),
cur_dst_buf_info,
std::back_inserter(cols),
h_dst_bufs[idx],
mb);
// pack the columns
result.emplace_back(packed_table{
cudf::table_view{cols},
packed_columns{std::make_unique<std::vector<uint8_t>>(mb.build()),
std::make_unique<rmm::device_buffer>(std::move(out_buffers[idx]))}});
cols.clear();
mb.clear();
}
return result;
}
std::vector<packed_table> make_empty_packed_table()
{
// sanitize the inputs (to handle corner cases like sliced tables)
std::vector<cudf::column_view> empty_column_views;
empty_column_views.reserve(input.num_columns());
std::transform(input.begin(),
input.end(),
std::back_inserter(empty_column_views),
[](column_view const& col) { return cudf::empty_like(col)->view(); });
table_view empty_inputs(empty_column_views);
// build the empty results
std::vector<packed_table> result;
result.reserve(num_partitions);
auto const iter = thrust::make_counting_iterator(0);
std::transform(iter,
iter + num_partitions,
std::back_inserter(result),
[&empty_inputs](int partition_index) {
return packed_table{empty_inputs,
packed_columns{std::make_unique<std::vector<uint8_t>>(
pack_metadata(empty_inputs, nullptr, 0)),
std::make_unique<rmm::device_buffer>()}};
});
return result;
}
cudf::table_view const input; ///< The input table_view to operate on
std::size_t const user_buffer_size; ///< The size of the user buffer for the chunked_pack case
rmm::cuda_stream_view const stream;
rmm::mr::device_memory_resource* const mr; ///< The memory resource for any data returned
// this resource defaults to `mr` for the contiguous_split case, but it can be useful for the
// `chunked_pack` case to allocate scratch/temp memory in a pool
rmm::mr::device_memory_resource* const temp_mr; ///< The memory resource for scratch/temp space
// whether the table was empty to begin with (0 rows or 0 columns) and should be metadata-only
bool const is_empty; ///< True if the source table has 0 rows or 0 columns
// This can be 1 if `contiguous_split` is just packing and not splitting
std::size_t const num_partitions; ///< The number of partitions to produce
size_type const num_src_bufs; ///< Number of source buffers including children
std::size_t const num_bufs; ///< Number of source buffers including children * number of splits
std::unique_ptr<packed_partition_buf_size_and_dst_buf_info>
partition_buf_size_and_dst_buf_info; ///< Per-partition buffer size and destination buffer info
std::unique_ptr<packed_src_and_dst_pointers>
src_and_dst_pointers; ///< Src. and dst. pointers for `copy_partition`
//
// State around the chunked pattern
//
// chunked_pack will have 1 or more "chunks" to iterate on, defined in chunk_iter_state
// contiguous_split will have a single "chunk" in chunk_iter_state, so no iteration.
std::unique_ptr<chunk_iteration_state>
chunk_iter_state; ///< State object for chunk iteration state
// Two API usages are allowed:
// - `chunked_pack`: for this mode, the user will provide a buffer that must be at least 1MB.
// The behavior is "chunked" in that it will contiguously copy up until the user specified
// `user_buffer_size` limit, exposing a next() call for the user to invoke. Note that in this
// mode, no partitioning occurs, hence the name "pack".
//
// - `contiguous_split` (default): when the user doesn't provide their own buffer,
// `contiguous_split` will allocate a buffer per partition and will place contiguous results in
// each buffer.
//
std::vector<rmm::device_buffer>
out_buffers; ///< Buffers allocated for a regular `contiguous_split`
};
std::vector<packed_table> contiguous_split(cudf::table_view const& input,
std::vector<size_type> const& splits,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
// `temp_mr` is the same as `mr` for contiguous_split as it allocates all
// of its memory from the default memory resource in cuDF
auto temp_mr = mr;
auto state = contiguous_split_state(input, splits, stream, mr, temp_mr);
return state.contiguous_split();
}
}; // namespace detail
std::vector<packed_table> contiguous_split(cudf::table_view const& input,
std::vector<size_type> const& splits,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::contiguous_split(input, splits, cudf::get_default_stream(), mr);
}
chunked_pack::chunked_pack(cudf::table_view const& input,
std::size_t user_buffer_size,
rmm::mr::device_memory_resource* temp_mr)
{
CUDF_EXPECTS(user_buffer_size >= desired_batch_size,
"The output buffer size must be at least 1MB in size");
// We pass `nullptr` for the first `mr` in `contiguous_split_state` to indicate
// that it does not allocate any user-bound data for the `chunked_pack` case.
state = std::make_unique<detail::contiguous_split_state>(
input, user_buffer_size, cudf::get_default_stream(), nullptr, temp_mr);
}
// required for the unique_ptr to work with a incomplete type (contiguous_split_state)
chunked_pack::~chunked_pack() = default;
std::size_t chunked_pack::get_total_contiguous_size() const
{
return state->get_total_contiguous_size();
}
bool chunked_pack::has_next() const { return state->has_next(); }
std::size_t chunked_pack::next(cudf::device_span<uint8_t> const& user_buffer)
{
return state->contiguous_split_chunk(user_buffer);
}
std::unique_ptr<std::vector<uint8_t>> chunked_pack::build_metadata() const
{
return state->build_packed_column_metadata();
}
std::unique_ptr<chunked_pack> chunked_pack::create(cudf::table_view const& input,
std::size_t user_buffer_size,
rmm::mr::device_memory_resource* temp_mr)
{
return std::make_unique<chunked_pack>(input, user_buffer_size, temp_mr);
}
}; // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/copy.cpp
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/lists/lists_column_view.hpp>
#include <cudf/table/table.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/traits.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/iterator/transform_iterator.h>
#include <algorithm>
namespace cudf {
namespace detail {
namespace {
inline mask_state should_allocate_mask(mask_allocation_policy mask_alloc, bool mask_exists)
{
if ((mask_alloc == mask_allocation_policy::ALWAYS) ||
(mask_alloc == mask_allocation_policy::RETAIN && mask_exists)) {
return mask_state::UNINITIALIZED;
} else {
return mask_state::UNALLOCATED;
}
}
/**
* @brief Functor to produce an empty column of the same type as the
* input scalar.
*
* In the case of nested types, full column hierarchy is preserved.
*/
template <typename T>
struct scalar_empty_like_functor_impl {
std::unique_ptr<column> operator()(scalar const& input)
{
return cudf::make_empty_column(input.type());
}
};
template <>
struct scalar_empty_like_functor_impl<cudf::list_view> {
std::unique_ptr<column> operator()(scalar const& input)
{
auto ls = static_cast<list_scalar const*>(&input);
// TODO: add a manual constructor for lists_column_view.
column_view offsets{cudf::data_type{cudf::type_id::INT32}, 0, nullptr, nullptr, 0};
std::vector<column_view> children;
children.push_back(offsets);
children.push_back(ls->view());
column_view lcv{cudf::data_type{cudf::type_id::LIST}, 0, nullptr, nullptr, 0, 0, children};
return empty_like(lcv);
}
};
template <>
struct scalar_empty_like_functor_impl<cudf::struct_view> {
std::unique_ptr<column> operator()(scalar const& input)
{
auto ss = static_cast<struct_scalar const*>(&input);
// TODO: add a manual constructor for structs_column_view
// TODO: add cudf::get_element() support for structs
cudf::table_view tbl = ss->view();
std::vector<column_view> children(tbl.begin(), tbl.end());
column_view scv{cudf::data_type{cudf::type_id::STRUCT}, 0, nullptr, nullptr, 0, 0, children};
return empty_like(scv);
}
};
template <>
struct scalar_empty_like_functor_impl<cudf::dictionary32> {
std::unique_ptr<column> operator()(scalar const& input)
{
CUDF_FAIL("Dictionary scalars not supported");
}
};
struct scalar_empty_like_functor {
template <typename T>
std::unique_ptr<column> operator()(scalar const& input)
{
scalar_empty_like_functor_impl<T> func;
return func(input);
}
};
} // namespace
/*
* Creates an uninitialized new column of the specified size and same type as
* the `input`. Supports only fixed-width types.
*/
std::unique_ptr<column> allocate_like(column_view const& input,
size_type size,
mask_allocation_policy mask_alloc,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
CUDF_EXPECTS(is_fixed_width(input.type()), "Expects only fixed-width type column");
mask_state allocate_mask = should_allocate_mask(mask_alloc, input.nullable());
return std::make_unique<column>(input.type(),
size,
rmm::device_buffer(size * size_of(input.type()), stream, mr),
detail::create_null_mask(size, allocate_mask, stream, mr),
0);
}
} // namespace detail
/*
* Initializes and returns an empty column of the same type as the `input`.
*/
std::unique_ptr<column> empty_like(column_view const& input)
{
CUDF_FUNC_RANGE();
std::vector<std::unique_ptr<column>> children;
std::transform(input.child_begin(),
input.child_end(),
std::back_inserter(children),
[](column_view const& col) { return empty_like(col); });
return std::make_unique<cudf::column>(
input.type(), 0, rmm::device_buffer{}, rmm::device_buffer{}, 0, std::move(children));
}
/*
* Initializes and returns an empty column of the same type as the `input`.
*/
std::unique_ptr<column> empty_like(scalar const& input)
{
CUDF_FUNC_RANGE();
return type_dispatcher(input.type(), detail::scalar_empty_like_functor{}, input);
};
/*
* Creates a table of empty columns with the same types as the `input_table`
*/
std::unique_ptr<table> empty_like(table_view const& input_table)
{
CUDF_FUNC_RANGE();
std::vector<std::unique_ptr<column>> columns(input_table.num_columns());
std::transform(input_table.begin(), input_table.end(), columns.begin(), [&](column_view in_col) {
return empty_like(in_col);
});
return std::make_unique<table>(std::move(columns));
}
std::unique_ptr<column> allocate_like(column_view const& input,
mask_allocation_policy mask_alloc,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::allocate_like(input, input.size(), mask_alloc, stream, mr);
}
std::unique_ptr<column> allocate_like(column_view const& input,
size_type size,
mask_allocation_policy mask_alloc,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::allocate_like(input, size, mask_alloc, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/sample.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/gather.cuh>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/iterator.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/random.h>
#include <thrust/random/uniform_int_distribution.h>
#include <thrust/shuffle.h>
namespace cudf {
namespace detail {
std::unique_ptr<table> sample(table_view const& input,
size_type const n,
sample_with_replacement replacement,
int64_t const seed,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(n >= 0, "expected number of samples should be non-negative");
auto const num_rows = input.num_rows();
if ((n > num_rows) and (replacement == sample_with_replacement::FALSE)) {
CUDF_FAIL("If n > number of rows, then multiple sampling of the same row should be allowed");
}
if (n == 0) return cudf::empty_like(input);
if (replacement == sample_with_replacement::TRUE) {
auto RandomGen = [seed, num_rows] __device__(auto i) {
thrust::default_random_engine rng(seed);
thrust::uniform_int_distribution<size_type> dist{0, num_rows - 1};
rng.discard(i);
return dist(rng);
};
auto begin = cudf::detail::make_counting_transform_iterator(0, RandomGen);
return detail::gather(input, begin, begin + n, out_of_bounds_policy::DONT_CHECK, stream, mr);
} else {
auto gather_map =
make_numeric_column(data_type{type_id::INT32}, num_rows, mask_state::UNALLOCATED, stream);
auto gather_map_mutable_view = gather_map->mutable_view();
// Shuffle all the row indices
thrust::shuffle_copy(rmm::exec_policy(stream),
thrust::counting_iterator<size_type>(0),
thrust::counting_iterator<size_type>(num_rows),
gather_map_mutable_view.begin<size_type>(),
thrust::default_random_engine(seed));
auto gather_map_view = (n == num_rows)
? gather_map->view()
: cudf::detail::slice(gather_map->view(), {0, n}, stream)[0];
return detail::gather(input,
gather_map_view.begin<size_type>(),
gather_map_view.end<size_type>(),
out_of_bounds_policy::DONT_CHECK,
stream,
mr);
}
}
} // namespace detail
std::unique_ptr<table> sample(table_view const& input,
size_type const n,
sample_with_replacement replacement,
int64_t const seed,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::sample(input, n, replacement, seed, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/gather.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/gather.cuh>
#include <cudf/detail/gather.hpp>
#include <cudf/detail/indexalator.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/iterator/transform_iterator.h>
namespace cudf {
namespace detail {
std::unique_ptr<table> gather(table_view const& source_table,
column_view const& gather_map,
out_of_bounds_policy bounds_policy,
negative_index_policy neg_indices,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(not gather_map.has_nulls(), "gather_map contains nulls");
// create index type normalizing iterator for the gather_map
auto map_begin = indexalator_factory::make_input_iterator(gather_map);
auto map_end = map_begin + gather_map.size();
if (neg_indices == negative_index_policy::ALLOWED) {
cudf::size_type n_rows = source_table.num_rows();
auto idx_converter = [n_rows] __device__(size_type in) { return in < 0 ? in + n_rows : in; };
return gather(source_table,
thrust::make_transform_iterator(map_begin, idx_converter),
thrust::make_transform_iterator(map_end, idx_converter),
bounds_policy,
stream,
mr);
}
return gather(source_table, map_begin, map_end, bounds_policy, stream, mr);
}
std::unique_ptr<table> gather(table_view const& source_table,
device_span<size_type const> const gather_map,
out_of_bounds_policy bounds_policy,
negative_index_policy neg_indices,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(gather_map.size() <= static_cast<size_t>(std::numeric_limits<size_type>::max()),
"gather map size exceeds the column size limit",
std::overflow_error);
auto map_col = column_view(data_type{type_to_id<size_type>()},
static_cast<size_type>(gather_map.size()),
gather_map.data(),
nullptr,
0);
return gather(source_table, map_col, bounds_policy, neg_indices, stream, mr);
}
} // namespace detail
std::unique_ptr<table> gather(table_view const& source_table,
column_view const& gather_map,
out_of_bounds_policy bounds_policy,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
auto index_policy = is_unsigned(gather_map.type()) ? detail::negative_index_policy::NOT_ALLOWED
: detail::negative_index_policy::ALLOWED;
return detail::gather(source_table, gather_map, bounds_policy, index_policy, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/concatenate.cu
|
/*
* Copyright (c) 2020-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column.hpp>
#include <cudf/column/column_device_view.cuh>
#include <cudf/detail/concatenate_masks.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/get_value.cuh>
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/utilities/cuda.cuh>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/dictionary/detail/concatenate.hpp>
#include <cudf/lists/detail/concatenate.hpp>
#include <cudf/strings/detail/concatenate.hpp>
#include <cudf/structs/detail/concatenate.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_device_view.cuh>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/advance.h>
#include <thrust/binary_search.h>
#include <thrust/copy.h>
#include <thrust/execution_policy.h>
#include <thrust/functional.h>
#include <thrust/host_vector.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/transform_scan.h>
#include <algorithm>
#include <numeric>
#include <utility>
namespace cudf {
namespace detail {
namespace {
// From benchmark data, the fused kernel optimization appears to perform better
// when there are more than a trivial number of columns, or when the null mask
// can also be computed at the same time
constexpr bool use_fused_kernel_heuristic(bool const has_nulls, size_t const num_columns)
{
return has_nulls || num_columns > 4;
}
auto create_device_views(host_span<column_view const> views, rmm::cuda_stream_view stream)
{
// Create device views for each input view
using CDViewPtr = decltype(column_device_view::create(std::declval<column_view>(),
std::declval<rmm::cuda_stream_view>()));
auto device_view_owners = std::vector<CDViewPtr>(views.size());
std::transform(views.begin(), views.end(), device_view_owners.begin(), [stream](auto const& col) {
return column_device_view::create(col, stream);
});
// Assemble contiguous array of device views
auto device_views = thrust::host_vector<column_device_view>();
device_views.reserve(views.size());
std::transform(device_view_owners.cbegin(),
device_view_owners.cend(),
std::back_inserter(device_views),
[](auto const& col) { return *col; });
auto d_views =
make_device_uvector_async(device_views, stream, rmm::mr::get_current_device_resource());
// Compute the partition offsets
auto offsets = thrust::host_vector<size_t>(views.size() + 1);
thrust::transform_inclusive_scan(
thrust::host,
device_views.cbegin(),
device_views.cend(),
std::next(offsets.begin()),
[](auto const& col) { return col.size(); },
thrust::plus{});
auto d_offsets =
make_device_uvector_async(offsets, stream, rmm::mr::get_current_device_resource());
auto const output_size = offsets.back();
return std::make_tuple(
std::move(device_view_owners), std::move(d_views), std::move(d_offsets), output_size);
}
/**
* @brief Concatenates the null mask bits of all the column device views in the
* `views` array to the destination bitmask.
*
* @tparam block_size Block size for using with single_lane_block_sum_reduce
*
* @param views Array of column_device_view
* @param output_offsets Prefix sum of sizes of elements of `views`
* @param number_of_views Size of `views` array
* @param dest_mask The output buffer to copy null masks into
* @param number_of_mask_bits The total number of null masks bits that are being copied
* @param out_valid_count To hold the total number of valid bits set
*/
template <size_type block_size>
__global__ void concatenate_masks_kernel(column_device_view const* views,
size_t const* output_offsets,
size_type number_of_views,
bitmask_type* dest_mask,
size_type number_of_mask_bits,
size_type* out_valid_count)
{
auto tidx = cudf::detail::grid_1d::global_thread_id();
auto const stride = cudf::detail::grid_1d::grid_stride();
auto active_mask = __ballot_sync(0xFFFF'FFFFu, tidx < number_of_mask_bits);
size_type warp_valid_count = 0;
while (tidx < number_of_mask_bits) {
auto const mask_index = static_cast<cudf::size_type>(tidx);
size_type const source_view_index =
thrust::upper_bound(
thrust::seq, output_offsets, output_offsets + number_of_views, mask_index) -
output_offsets - 1;
bool bit_is_set = true;
if (source_view_index < number_of_views) {
size_type const column_element_index = mask_index - output_offsets[source_view_index];
bit_is_set = views[source_view_index].is_valid(column_element_index);
}
bitmask_type const new_word = __ballot_sync(active_mask, bit_is_set);
if (threadIdx.x % detail::warp_size == 0) {
dest_mask[word_index(mask_index)] = new_word;
warp_valid_count += __popc(new_word);
}
tidx += stride;
active_mask = __ballot_sync(active_mask, tidx < number_of_mask_bits);
}
using detail::single_lane_block_sum_reduce;
auto const block_valid_count = single_lane_block_sum_reduce<block_size, 0>(warp_valid_count);
if (threadIdx.x == 0) { atomicAdd(out_valid_count, block_valid_count); }
}
} // namespace
size_type concatenate_masks(device_span<column_device_view const> d_views,
device_span<size_t const> d_offsets,
bitmask_type* dest_mask,
size_type output_size,
rmm::cuda_stream_view stream)
{
rmm::device_scalar<size_type> d_valid_count(0, stream);
constexpr size_type block_size{256};
cudf::detail::grid_1d config(output_size, block_size);
concatenate_masks_kernel<block_size>
<<<config.num_blocks, config.num_threads_per_block, 0, stream.value()>>>(
d_views.data(),
d_offsets.data(),
static_cast<size_type>(d_views.size()),
dest_mask,
output_size,
d_valid_count.data());
return output_size - d_valid_count.value(stream);
}
size_type concatenate_masks(host_span<column_view const> views,
bitmask_type* dest_mask,
rmm::cuda_stream_view stream)
{
// Preprocess and upload inputs to device memory
auto const device_views = create_device_views(views, stream);
auto const& d_views = std::get<1>(device_views);
auto const& d_offsets = std::get<2>(device_views);
auto const output_size = std::get<3>(device_views);
return concatenate_masks(d_views, d_offsets, dest_mask, output_size, stream);
}
namespace {
template <typename T, size_type block_size, bool Nullable>
__global__ void fused_concatenate_kernel(column_device_view const* input_views,
size_t const* input_offsets,
size_type num_input_views,
mutable_column_device_view output_view,
size_type* out_valid_count)
{
auto const output_size = output_view.size();
auto* output_data = output_view.data<T>();
auto output_index = cudf::detail::grid_1d::global_thread_id();
auto const stride = cudf::detail::grid_1d::grid_stride();
size_type warp_valid_count = 0;
unsigned active_mask;
if (Nullable) { active_mask = __ballot_sync(0xFFFF'FFFFu, output_index < output_size); }
while (output_index < output_size) {
// Lookup input index by searching for output index in offsets
auto const offset_it = thrust::prev(thrust::upper_bound(
thrust::seq, input_offsets, input_offsets + num_input_views, output_index));
size_type const partition_index = offset_it - input_offsets;
// Copy input data to output
auto const offset_index = output_index - *offset_it;
auto const& input_view = input_views[partition_index];
auto const* input_data = input_view.data<T>();
output_data[output_index] = input_data[offset_index];
if (Nullable) {
bool const bit_is_set = input_view.is_valid(offset_index);
bitmask_type const new_word = __ballot_sync(active_mask, bit_is_set);
// First thread writes bitmask word
if (threadIdx.x % detail::warp_size == 0) {
output_view.null_mask()[word_index(output_index)] = new_word;
}
warp_valid_count += __popc(new_word);
}
output_index += stride;
if (Nullable) { active_mask = __ballot_sync(active_mask, output_index < output_size); }
}
if (Nullable) {
using detail::single_lane_block_sum_reduce;
auto block_valid_count = single_lane_block_sum_reduce<block_size, 0>(warp_valid_count);
if (threadIdx.x == 0) { atomicAdd(out_valid_count, block_valid_count); }
}
}
template <typename T>
std::unique_ptr<column> fused_concatenate(host_span<column_view const> views,
bool const has_nulls,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using mask_policy = cudf::mask_allocation_policy;
// Preprocess and upload inputs to device memory
auto const device_views = create_device_views(views, stream);
auto const& d_views = std::get<1>(device_views);
auto const& d_offsets = std::get<2>(device_views);
auto const output_size = std::get<3>(device_views);
CUDF_EXPECTS(output_size <= static_cast<std::size_t>(std::numeric_limits<size_type>::max()),
"Total number of concatenated rows exceeds the column size limit",
std::overflow_error);
// Allocate output
auto const policy = has_nulls ? mask_policy::ALWAYS : mask_policy::NEVER;
auto out_col = detail::allocate_like(views.front(), output_size, policy, stream, mr);
auto out_view = out_col->mutable_view();
auto d_out_view = mutable_column_device_view::create(out_view, stream);
rmm::device_scalar<size_type> d_valid_count(0, stream);
// Launch kernel
constexpr size_type block_size{256};
cudf::detail::grid_1d config(output_size, block_size);
auto const kernel = has_nulls ? fused_concatenate_kernel<T, block_size, true>
: fused_concatenate_kernel<T, block_size, false>;
kernel<<<config.num_blocks, config.num_threads_per_block, 0, stream.value()>>>(
d_views.data(),
d_offsets.data(),
static_cast<size_type>(d_views.size()),
*d_out_view,
d_valid_count.data());
if (has_nulls) {
out_col->set_null_count(output_size - d_valid_count.value(stream));
} else {
out_col->set_null_count(0); // prevent null count from being materialized
}
return out_col;
}
template <typename T>
std::unique_ptr<column> for_each_concatenate(host_span<column_view const> views,
bool const has_nulls,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
size_type const total_element_count =
std::accumulate(views.begin(), views.end(), 0, [](auto accumulator, auto const& v) {
return accumulator + v.size();
});
using mask_policy = cudf::mask_allocation_policy;
auto const policy = has_nulls ? mask_policy::ALWAYS : mask_policy::NEVER;
auto col = cudf::detail::allocate_like(views.front(), total_element_count, policy, stream, mr);
auto m_view = col->mutable_view();
auto count = 0;
for (auto& v : views) {
thrust::copy(rmm::exec_policy(stream), v.begin<T>(), v.end<T>(), m_view.begin<T>() + count);
count += v.size();
}
// If concatenated column is nullable, proceed to calculate it
if (has_nulls) {
col->set_null_count(
cudf::detail::concatenate_masks(views, (col->mutable_view()).null_mask(), stream));
} else {
col->set_null_count(0); // prevent null count from being materialized
}
return col;
}
struct concatenate_dispatch {
host_span<column_view const> views;
rmm::cuda_stream_view stream;
rmm::mr::device_memory_resource* mr;
// fixed width
template <typename T>
std::unique_ptr<column> operator()()
{
bool const has_nulls =
std::any_of(views.begin(), views.end(), [](auto const& col) { return col.has_nulls(); });
// Use a heuristic to guess when the fused kernel will be faster
if (use_fused_kernel_heuristic(has_nulls, views.size())) {
return fused_concatenate<T>(views, has_nulls, stream, mr);
} else {
return for_each_concatenate<T>(views, has_nulls, stream, mr);
}
}
};
template <>
std::unique_ptr<column> concatenate_dispatch::operator()<cudf::dictionary32>()
{
return cudf::dictionary::detail::concatenate(views, stream, mr);
}
template <>
std::unique_ptr<column> concatenate_dispatch::operator()<cudf::string_view>()
{
return cudf::strings::detail::concatenate(views, stream, mr);
}
template <>
std::unique_ptr<column> concatenate_dispatch::operator()<cudf::list_view>()
{
return cudf::lists::detail::concatenate(views, stream, mr);
}
template <>
std::unique_ptr<column> concatenate_dispatch::operator()<cudf::struct_view>()
{
return cudf::structs::detail::concatenate(views, stream, mr);
}
void bounds_and_type_check(host_span<column_view const> cols, rmm::cuda_stream_view stream);
/**
* @brief Functor for traversing child columns and recursively verifying concatenation
* bounds and types.
*/
class traverse_children {
public:
// nothing to do for simple types.
template <typename T>
void operator()(host_span<column_view const>, rmm::cuda_stream_view)
{
}
private:
// verify length of concatenated offsets.
void check_offsets_size(host_span<column_view const> cols)
{
// offsets. we can't just add up the total sizes of all offset child columns because each one
// has an extra value, regardless of the # of parent rows. So we have to add up the total # of
// rows in the base column and add 1 at the end
size_t const total_offset_count =
std::accumulate(cols.begin(),
cols.end(),
std::size_t{},
[](size_t a, auto const& b) -> size_t { return a + b.size(); }) +
1;
CUDF_EXPECTS(total_offset_count <= static_cast<size_t>(std::numeric_limits<size_type>::max()),
"Total number of concatenated offsets exceeds the column size limit",
std::overflow_error);
}
};
template <>
void traverse_children::operator()<cudf::string_view>(host_span<column_view const> cols,
rmm::cuda_stream_view stream)
{
// verify offsets
check_offsets_size(cols);
// chars
size_t const total_char_count = std::accumulate(
cols.begin(), cols.end(), std::size_t{}, [stream](size_t a, auto const& b) -> size_t {
strings_column_view scv(b);
return a + (scv.is_empty() ? 0
// if the column is unsliced, skip the offset retrieval.
: scv.offset() > 0
? cudf::detail::get_value<size_type>(
scv.offsets(), scv.offset() + scv.size(), stream) -
cudf::detail::get_value<size_type>(scv.offsets(), scv.offset(), stream)
// if the offset() is 0, it can still be sliced to a shorter length. in this case
// we only need to read a single offset. otherwise just return the full length
// (chars_size())
: scv.size() + 1 == scv.offsets().size()
? scv.chars_size()
: cudf::detail::get_value<size_type>(scv.offsets(), scv.size(), stream));
});
CUDF_EXPECTS(total_char_count <= static_cast<size_t>(std::numeric_limits<size_type>::max()),
"Total number of concatenated chars exceeds the column size limit",
std::overflow_error);
}
template <>
void traverse_children::operator()<cudf::struct_view>(host_span<column_view const> cols,
rmm::cuda_stream_view stream)
{
// march each child
auto child_iter = thrust::make_counting_iterator(0);
auto const num_children = cols.front().num_children();
std::vector<column_view> nth_children;
nth_children.reserve(cols.size());
std::for_each(child_iter, child_iter + num_children, [&](auto child_index) {
std::transform(cols.begin(),
cols.end(),
std::back_inserter(nth_children),
[child_index, stream](column_view const& col) {
structs_column_view scv(col);
return scv.get_sliced_child(child_index, stream);
});
bounds_and_type_check(nth_children, stream);
nth_children.clear();
});
}
template <>
void traverse_children::operator()<cudf::list_view>(host_span<column_view const> cols,
rmm::cuda_stream_view stream)
{
// verify offsets
check_offsets_size(cols);
// recurse into the child columns
std::vector<column_view> nth_children;
nth_children.reserve(cols.size());
std::transform(
cols.begin(), cols.end(), std::back_inserter(nth_children), [stream](column_view const& col) {
lists_column_view lcv(col);
return lcv.get_sliced_child(stream);
});
bounds_and_type_check(nth_children, stream);
}
/**
* @brief Verifies that the sum of the sizes of all the columns to be concatenated
* will not exceed the max value of size_type, and verifies all column types match
*
* @param columns_to_concat Span of columns to check
*
* @throws cudf::logic_error if the total length of the concatenated columns would
* exceed the max value of size_type
*
* @throws cudf::logic_error if all of the input column types don't match
*/
void bounds_and_type_check(host_span<column_view const> cols, rmm::cuda_stream_view stream)
{
CUDF_EXPECTS(std::all_of(cols.begin(),
cols.end(),
[expected_type = cols.front().type()](auto const& c) {
return c.type() == expected_type;
}),
"Type mismatch in columns to concatenate.");
// total size of all concatenated rows
size_t const total_row_count =
std::accumulate(cols.begin(), cols.end(), std::size_t{}, [](size_t a, auto const& b) {
return a + static_cast<size_t>(b.size());
});
CUDF_EXPECTS(total_row_count <= static_cast<size_t>(std::numeric_limits<size_type>::max()),
"Total number of concatenated rows exceeds the column size limit",
std::overflow_error);
// traverse children
cudf::type_dispatcher(cols.front().type(), traverse_children{}, cols, stream);
}
} // anonymous namespace
// Concatenates the elements from a vector of column_views
std::unique_ptr<column> concatenate(host_span<column_view const> columns_to_concat,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(not columns_to_concat.empty(), "Unexpected empty list of columns to concatenate.");
// verify all types match and that we won't overflow size_type in output size
bounds_and_type_check(columns_to_concat, stream);
if (std::all_of(columns_to_concat.begin(), columns_to_concat.end(), [](column_view const& c) {
return c.is_empty();
})) {
return empty_like(columns_to_concat.front());
}
return type_dispatcher<dispatch_storage_type>(
columns_to_concat.front().type(), concatenate_dispatch{columns_to_concat, stream, mr});
}
std::unique_ptr<table> concatenate(host_span<table_view const> tables_to_concat,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
if (tables_to_concat.empty()) { return std::make_unique<table>(); }
table_view const first_table = tables_to_concat.front();
CUDF_EXPECTS(std::all_of(tables_to_concat.begin(),
tables_to_concat.end(),
[&first_table](auto const& t) {
return t.num_columns() == first_table.num_columns();
}),
"Mismatch in table columns to concatenate.");
std::vector<std::unique_ptr<column>> concat_columns;
for (size_type i = 0; i < first_table.num_columns(); ++i) {
std::vector<column_view> cols;
std::transform(tables_to_concat.begin(),
tables_to_concat.end(),
std::back_inserter(cols),
[i](auto const& t) { return t.column(i); });
// verify all types match and that we won't overflow size_type in output size
bounds_and_type_check(cols, stream);
concat_columns.emplace_back(detail::concatenate(cols, stream, mr));
}
return std::make_unique<table>(std::move(concat_columns));
}
rmm::device_buffer concatenate_masks(host_span<column_view const> views,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
bool const has_nulls =
std::any_of(views.begin(), views.end(), [](column_view const col) { return col.has_nulls(); });
if (has_nulls) {
size_type const total_element_count =
std::accumulate(views.begin(), views.end(), 0, [](auto accumulator, auto const& v) {
return accumulator + v.size();
});
rmm::device_buffer null_mask =
cudf::detail::create_null_mask(total_element_count, mask_state::UNINITIALIZED, stream, mr);
detail::concatenate_masks(views, static_cast<bitmask_type*>(null_mask.data()), stream);
return null_mask;
}
// no nulls, so return an empty device buffer
return rmm::device_buffer{0, stream, mr};
}
} // namespace detail
rmm::device_buffer concatenate_masks(host_span<column_view const> views,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::concatenate_masks(views, stream, mr);
}
// Concatenates the elements from a vector of column_views
std::unique_ptr<column> concatenate(host_span<column_view const> columns_to_concat,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::concatenate(columns_to_concat, stream, mr);
}
std::unique_ptr<table> concatenate(host_span<table_view const> tables_to_concat,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::concatenate(tables_to_concat, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/shift.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_device_view.cuh>
#include <cudf/copying.hpp>
#include <cudf/detail/copy.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/valid_if.cuh>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/detail/copying.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <cudf/utilities/error.hpp>
#include <cudf/utilities/traits.hpp>
#include <cudf/utilities/type_dispatcher.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/copy.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/transform.h>
#include <algorithm>
#include <iterator>
#include <memory>
namespace cudf {
namespace {
inline bool __device__ out_of_bounds(size_type size, size_type idx)
{
return idx < 0 || idx >= size;
}
std::pair<rmm::device_buffer, size_type> create_null_mask(column_device_view const& input,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto const size = input.size();
auto func_validity =
[size, offset, fill = fill_value.validity_data(), input] __device__(size_type idx) {
auto src_idx = idx - offset;
return out_of_bounds(size, src_idx) ? *fill : input.is_valid(src_idx);
};
return detail::valid_if(thrust::make_counting_iterator<size_type>(0),
thrust::make_counting_iterator<size_type>(size),
func_validity,
stream,
mr);
}
struct shift_functor {
template <typename T, typename... Args>
std::enable_if_t<not cudf::is_fixed_width<T>() and not std::is_same_v<cudf::string_view, T>,
std::unique_ptr<column>>
operator()(Args&&...)
{
CUDF_FAIL("shift only supports fixed-width or string types.");
}
template <typename T, typename... Args>
std::enable_if_t<std::is_same_v<cudf::string_view, T>, std::unique_ptr<column>> operator()(
column_view const& input,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto output = cudf::strings::detail::shift(
cudf::strings_column_view(input), offset, fill_value, stream, mr);
if (input.nullable() || not fill_value.is_valid(stream)) {
auto const d_input = column_device_view::create(input, stream);
auto [null_mask, null_count] = create_null_mask(*d_input, offset, fill_value, stream, mr);
output->set_null_mask(std::move(null_mask), null_count);
}
return output;
}
template <typename T>
std::enable_if_t<cudf::is_fixed_width<T>(), std::unique_ptr<column>> operator()(
column_view const& input,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
using ScalarType = cudf::scalar_type_t<T>;
auto& scalar = static_cast<ScalarType const&>(fill_value);
auto device_input = column_device_view::create(input, stream);
auto output =
detail::allocate_like(input, input.size(), mask_allocation_policy::NEVER, stream, mr);
auto device_output = mutable_column_device_view::create(*output, stream);
auto const scalar_is_valid = scalar.is_valid(stream);
if (input.nullable() || not scalar_is_valid) {
auto [null_mask, null_count] =
create_null_mask(*device_input, offset, fill_value, stream, mr);
output->set_null_mask(std::move(null_mask), null_count);
}
auto const size = input.size();
auto index_begin = thrust::make_counting_iterator<size_type>(0);
auto index_end = thrust::make_counting_iterator<size_type>(size);
auto data = device_output->data<T>();
// avoid assigning elements we know to be invalid.
if (not scalar_is_valid) {
if (std::abs(offset) > size) { return output; }
if (offset > 0) {
index_begin = thrust::make_counting_iterator<size_type>(offset);
data = data + offset;
} else if (offset < 0) {
index_end = thrust::make_counting_iterator<size_type>(size + offset);
}
}
auto func_value =
[size, offset, fill = scalar.data(), input = *device_input] __device__(size_type idx) {
auto src_idx = idx - offset;
return out_of_bounds(size, src_idx) ? *fill : input.element<T>(src_idx);
};
thrust::transform(rmm::exec_policy(stream), index_begin, index_end, data, func_value);
return output;
}
};
} // anonymous namespace
namespace detail {
std::unique_ptr<column> shift(column_view const& input,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(input.type() == fill_value.type(),
"shift requires each fill value type to match the corresponding column type.");
if (input.is_empty()) { return empty_like(input); }
return type_dispatcher<dispatch_storage_type>(
input.type(), shift_functor{}, input, offset, fill_value, stream, mr);
}
} // namespace detail
std::unique_ptr<column> shift(column_view const& input,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::shift(input, offset, fill_value, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/reverse.cu
|
/*
* Copyright (c) 2021-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_view.hpp>
#include <cudf/copying.hpp>
#include <cudf/detail/gather.cuh>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/table/table.hpp>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/device_uvector.hpp>
#include <rmm/exec_policy.hpp>
#include <rmm/mr/device/per_device_resource.hpp>
#include <thrust/iterator/constant_iterator.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/transform_output_iterator.h>
#include <thrust/scan.h>
namespace cudf {
namespace detail {
std::unique_ptr<table> reverse(table_view const& source_table,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
size_type num_rows = source_table.num_rows();
auto elements =
make_counting_transform_iterator(0, [num_rows] __device__(auto i) { return num_rows - i - 1; });
auto elements_end = elements + source_table.num_rows();
return gather(source_table, elements, elements_end, out_of_bounds_policy::DONT_CHECK, stream, mr);
}
std::unique_ptr<column> reverse(column_view const& source_column,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return std::move(
cudf::detail::reverse(table_view({source_column}), stream, mr)->release().front());
}
} // namespace detail
std::unique_ptr<table> reverse(table_view const& source_table,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::reverse(source_table, stream, mr);
}
std::unique_ptr<column> reverse(column_view const& source_column,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::reverse(source_column, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/copying/segmented_shift.cu
|
/*
* Copyright (c) 2021-2022, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/copy.hpp>
#include <cudf/detail/copy_if_else.cuh>
#include <cudf/detail/iterator.cuh>
#include <cudf/scalar/scalar.hpp>
#include <cudf/strings/detail/copy_if_else.cuh>
#include <cudf/strings/string_view.cuh>
#include <cudf/types.hpp>
#include <cudf/utilities/traits.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <thrust/binary_search.h>
#include <thrust/execution_policy.h>
#include <thrust/iterator/transform_iterator.h>
namespace cudf {
namespace detail {
namespace {
/**
* @brief Common filter function to convert index values into copy-if-else left/right result.
*
* The offset position is used to identify which segment to copy from.
*/
struct segmented_shift_filter {
device_span<size_type const> const segment_offsets;
size_type const offset;
__device__ bool operator()(size_type const i) const
{
auto const segment_bound_idx =
thrust::upper_bound(thrust::seq, segment_offsets.begin(), segment_offsets.end(), i) -
(offset > 0);
auto const left_idx = *segment_bound_idx + (offset < 0 ? offset : 0);
auto const right_idx = *segment_bound_idx + (offset > 0 ? offset : 0);
return not(left_idx <= i and i < right_idx);
};
};
template <typename T, typename Enable = void>
struct segmented_shift_functor {
template <typename... Args>
std::unique_ptr<column> operator()(Args&&...)
{
CUDF_FAIL("Unsupported type for segmented_shift.");
}
};
/**
* @brief Segmented shift specialization for representation layout compatible types.
*/
template <typename T>
struct segmented_shift_functor<T, std::enable_if_t<is_rep_layout_compatible<T>()>> {
std::unique_ptr<column> operator()(column_view const& segmented_values,
device_span<size_type const> segment_offsets,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_device_view = column_device_view::create(segmented_values, stream);
bool nullable = not fill_value.is_valid(stream) or segmented_values.nullable();
auto input_iterator = cudf::detail::make_optional_iterator<T>(
*values_device_view, nullate::DYNAMIC{segmented_values.has_nulls()}) -
offset;
auto fill_iterator = cudf::detail::make_optional_iterator<T>(fill_value, nullate::YES{});
return copy_if_else(nullable,
input_iterator,
input_iterator + segmented_values.size(),
fill_iterator,
segmented_shift_filter{segment_offsets, offset},
segmented_values.type(),
stream,
mr);
}
};
/**
* @brief Segmented shift specialization for `string_view`.
*/
template <>
struct segmented_shift_functor<string_view> {
std::unique_ptr<column> operator()(column_view const& segmented_values,
device_span<size_type const> segment_offsets,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
auto values_device_view = column_device_view::create(segmented_values, stream);
auto input_iterator = make_optional_iterator<cudf::string_view>(
*values_device_view, nullate::DYNAMIC{segmented_values.has_nulls()}) -
offset;
auto fill_iterator = make_optional_iterator<cudf::string_view>(fill_value, nullate::YES{});
return strings::detail::copy_if_else(input_iterator,
input_iterator + segmented_values.size(),
fill_iterator,
segmented_shift_filter{segment_offsets, offset},
stream,
mr);
}
};
/**
* @brief Functor to instantiate the specializations for segmented shift and
* forward arguments.
*/
struct segmented_shift_functor_forwarder {
template <typename T>
std::unique_ptr<column> operator()(column_view const& segmented_values,
device_span<size_type const> segment_offsets,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
segmented_shift_functor<T> shifter;
return shifter(segmented_values, segment_offsets, offset, fill_value, stream, mr);
}
};
} // namespace
std::unique_ptr<column> segmented_shift(column_view const& segmented_values,
device_span<size_type const> segment_offsets,
size_type offset,
scalar const& fill_value,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
if (segmented_values.is_empty()) { return empty_like(segmented_values); }
if (offset == 0) { return std::make_unique<column>(segmented_values, stream, mr); };
return type_dispatcher<dispatch_storage_type>(segmented_values.type(),
segmented_shift_functor_forwarder{},
segmented_values,
segment_offsets,
offset,
fill_value,
stream,
mr);
}
} // namespace detail
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/search/contains_column.cu
|
/*
* Copyright (c) 2019-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/detail/null_mask.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/search.hpp>
#include <cudf/dictionary/detail/search.hpp>
#include <cudf/dictionary/detail/update_keys.hpp>
#include <cudf/table/table_view.hpp>
#include <rmm/cuda_stream_view.hpp>
namespace cudf {
namespace detail {
namespace {
struct contains_column_dispatch {
template <typename Element>
std::unique_ptr<column> operator()(column_view const& haystack,
column_view const& needles,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
auto result_v = detail::contains(table_view{{haystack}},
table_view{{needles}},
null_equality::EQUAL,
nan_equality::ALL_EQUAL,
stream,
mr);
return std::make_unique<column>(
std::move(result_v), detail::copy_bitmask(needles, stream, mr), needles.null_count());
}
};
template <>
std::unique_ptr<column> contains_column_dispatch::operator()<dictionary32>(
column_view const& haystack_in,
column_view const& needles_in,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr) const
{
dictionary_column_view const haystack(haystack_in);
dictionary_column_view const needles(needles_in);
// first combine keys so both dictionaries have the same set
auto needles_matched = dictionary::detail::add_keys(
needles, haystack.keys(), stream, rmm::mr::get_current_device_resource());
auto const needles_view = dictionary_column_view(needles_matched->view());
auto haystack_matched = dictionary::detail::set_keys(
haystack, needles_view.keys(), stream, rmm::mr::get_current_device_resource());
auto const haystack_view = dictionary_column_view(haystack_matched->view());
// now just use the indices for the contains
column_view const haystack_indices = haystack_view.get_indices_annotated();
column_view const needles_indices = needles_view.get_indices_annotated();
return cudf::type_dispatcher(haystack_indices.type(),
contains_column_dispatch{},
haystack_indices,
needles_indices,
stream,
mr);
}
} // namespace
std::unique_ptr<column> contains(column_view const& haystack,
column_view const& needles,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return cudf::type_dispatcher(
haystack.type(), contains_column_dispatch{}, haystack, needles, stream, mr);
}
} // namespace detail
std::unique_ptr<column> contains(column_view const& haystack,
column_view const& needles,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::contains(haystack, needles, stream, mr);
}
} // namespace cudf
| 0 |
rapidsai_public_repos/cudf/cpp/src
|
rapidsai_public_repos/cudf/cpp/src/search/search_ordered.cu
|
/*
* Copyright (c) 2022-2023, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <cudf/column/column_factories.hpp>
#include <cudf/detail/nvtx/ranges.hpp>
#include <cudf/detail/utilities/vector_factories.hpp>
#include <cudf/dictionary/detail/update_keys.hpp>
#include <cudf/table/experimental/row_operators.cuh>
#include <cudf/table/table_device_view.cuh>
#include <cudf/table/table_view.hpp>
#include <cudf/utilities/default_stream.hpp>
#include <rmm/cuda_stream_view.hpp>
#include <rmm/exec_policy.hpp>
#include <thrust/binary_search.h>
namespace cudf {
namespace detail {
namespace {
std::unique_ptr<column> search_ordered(table_view const& haystack,
table_view const& needles,
bool find_first,
std::vector<order> const& column_order,
std::vector<null_order> const& null_precedence,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_EXPECTS(
column_order.empty() or static_cast<std::size_t>(haystack.num_columns()) == column_order.size(),
"Mismatch between number of columns and column order.");
CUDF_EXPECTS(null_precedence.empty() or
static_cast<std::size_t>(haystack.num_columns()) == null_precedence.size(),
"Mismatch between number of columns and null precedence.");
// Allocate result column
auto result = make_numeric_column(
data_type{type_to_id<size_type>()}, needles.num_rows(), mask_state::UNALLOCATED, stream, mr);
auto const out_it = result->mutable_view().data<size_type>();
// Handle empty inputs
if (haystack.num_rows() == 0) {
CUDF_CUDA_TRY(
cudaMemsetAsync(out_it, 0, needles.num_rows() * sizeof(size_type), stream.value()));
return result;
}
// This utility will ensure all corresponding dictionary columns have matching keys.
// It will return any new dictionary columns created as well as updated table_views.
auto const matched = dictionary::detail::match_dictionaries(
{haystack, needles}, stream, rmm::mr::get_current_device_resource());
auto const& matched_haystack = matched.second.front();
auto const& matched_needles = matched.second.back();
auto const comparator = cudf::experimental::row::lexicographic::two_table_comparator(
matched_haystack, matched_needles, column_order, null_precedence, stream);
auto const has_nulls = has_nested_nulls(matched_haystack) or has_nested_nulls(matched_needles);
auto const haystack_it = cudf::experimental::row::lhs_iterator(0);
auto const needles_it = cudf::experimental::row::rhs_iterator(0);
if (cudf::detail::has_nested_columns(haystack) || cudf::detail::has_nested_columns(needles)) {
auto const d_comparator = comparator.less<true>(nullate::DYNAMIC{has_nulls});
if (find_first) {
thrust::lower_bound(rmm::exec_policy(stream),
haystack_it,
haystack_it + haystack.num_rows(),
needles_it,
needles_it + needles.num_rows(),
out_it,
d_comparator);
} else {
thrust::upper_bound(rmm::exec_policy(stream),
haystack_it,
haystack_it + haystack.num_rows(),
needles_it,
needles_it + needles.num_rows(),
out_it,
d_comparator);
}
} else {
auto const d_comparator = comparator.less<false>(nullate::DYNAMIC{has_nulls});
if (find_first) {
thrust::lower_bound(rmm::exec_policy(stream),
haystack_it,
haystack_it + haystack.num_rows(),
needles_it,
needles_it + needles.num_rows(),
out_it,
d_comparator);
} else {
thrust::upper_bound(rmm::exec_policy(stream),
haystack_it,
haystack_it + haystack.num_rows(),
needles_it,
needles_it + needles.num_rows(),
out_it,
d_comparator);
}
}
return result;
}
} // namespace
std::unique_ptr<column> lower_bound(table_view const& haystack,
table_view const& needles,
std::vector<order> const& column_order,
std::vector<null_order> const& null_precedence,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return search_ordered(haystack, needles, true, column_order, null_precedence, stream, mr);
}
std::unique_ptr<column> upper_bound(table_view const& haystack,
table_view const& needles,
std::vector<order> const& column_order,
std::vector<null_order> const& null_precedence,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
return search_ordered(haystack, needles, false, column_order, null_precedence, stream, mr);
}
} // namespace detail
// external APIs
std::unique_ptr<column> lower_bound(table_view const& haystack,
table_view const& needles,
std::vector<order> const& column_order,
std::vector<null_order> const& null_precedence,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::lower_bound(haystack, needles, column_order, null_precedence, stream, mr);
}
std::unique_ptr<column> upper_bound(table_view const& haystack,
table_view const& needles,
std::vector<order> const& column_order,
std::vector<null_order> const& null_precedence,
rmm::cuda_stream_view stream,
rmm::mr::device_memory_resource* mr)
{
CUDF_FUNC_RANGE();
return detail::upper_bound(haystack, needles, column_order, null_precedence, stream, mr);
}
} // namespace cudf
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.