Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions cpp/benchmarks/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -553,3 +553,30 @@ add_custom_target(
DEPENDS CUDF_BENCHMARKS
COMMENT "Custom command for running cudf benchmarks."
)

rtcx_add_embed(cudf_reduce_lto_benchmark_fragments)
foreach(fragment IN ITEMS tpcds_q13 segmented_sum_max)
add_fragment(
cudf_reduce_lto_benchmark_fragments FRAGMENT ${fragment} SOURCE reduction/udfs/${fragment}.cu
)
endforeach()
rtcx_embed(
cudf_reduce_lto_benchmark_fragments COMPRESSION none OUTPUT_DIRECTORY
"${CMAKE_CURRENT_BINARY_DIR}/reduce_lto_embed"
)
add_executable(
REDUCE_LTO_BENCH
reduction/reduce_lto.cpp reduction/tpcds_q13.cpp reduction/segmented_lto.cpp
${cudf_reduce_lto_benchmark_fragments_SOURCE_DIR}/cudf_reduce_lto_benchmark_fragments.s
)
target_link_libraries(
REDUCE_LTO_BENCH PRIVATE cudf_datagen cudf::cudftestutil_objects
$<TARGET_NAME_IF_EXISTS:conda_env>
)
target_include_directories(
REDUCE_LTO_BENCH PRIVATE ${cudf_reduce_lto_benchmark_fragments_SOURCE_DIR}
)
add_dependencies(REDUCE_LTO_BENCH cudf_reduce_lto_benchmark_fragments)
set_target_properties(
REDUCE_LTO_BENCH PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CUDF_BINARY_DIR}/benchmarks"
)
43 changes: 43 additions & 0 deletions cpp/benchmarks/reduction/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# LTO reduction benchmarks

Build and run the fixed-loop C++ driver:

cmake --build <build> --target REDUCE_LTO_BENCH
<build>/benchmarks/REDUCE_LTO_BENCH --smoke --csv smoke.csv
<build>/benchmarks/REDUCE_LTO_BENCH --csv results.csv
python plot_lto.py results.csv --output-dir figures --subtitle 'GPU | CUDA version'

Q13 measures its post-join predicate and four aggregates on resident synthetic
inputs. Demographic/address branch codes represent completed dimension joins;
joins and their preparation are excluded. Compare LTO with cuDF AST JIT and
non-JIT predicate evaluation, retention-mask filtering and separate reductions.
Use --rows N to select a Q13 row count. The measured expression is:

SELECT AVG(ss_quantity), AVG(ss_ext_sales_price),
AVG(ss_ext_wholesale_cost), SUM(ss_ext_wholesale_cost)
FROM post_join_rows
WHERE d_year = 2001
AND ((demographic_branch = 1 AND ss_sales_price BETWEEN 100 AND 150)
OR (demographic_branch = 2 AND ss_sales_price BETWEEN 50 AND 100)
OR (demographic_branch = 3 AND ss_sales_price BETWEEN 150 AND 200))
AND ((address_branch = 1 AND ss_net_profit BETWEEN 100 AND 200)
OR (address_branch = 2 AND ss_net_profit BETWEEN 150 AND 300)
OR (address_branch = 3 AND ss_net_profit BETWEEN 50 AND 250));

Segmented SUM and fused SUM/MAX cover short segments, long segments and a skewed
distribution with empty segments. Compare public cuDF APIs with LTO using known
and unknown maximum-length hints. LTO returns independent single-row columns;
cuDF returns packed columns. Allocation/finalization costs remain in the timings.

Default Q13 sizes are 1,000, 100,000, 1 million and 10 million rows. Segmented
shapes are 4,096 × 16, 32 × 1,048,576 and 256 × 65,536 rows; the skewed shape
puts 90% of rows in its first segment.

Each case has four warmups and five synchronized steady-clock measurements.
Generation, reference calculations, compilation warmup, validation and output
destruction are outside timing. The driver uses a common 90% device-memory cap.
Smoke mode also checks empty Q13 inputs and all-null aggregates.

GB/s counts unique logical input values, validity bits and segment offsets,
including unselected rows. It is not measured DRAM bandwidth. SVG plots show
medians and observed minimum/maximum ranges, not confidence intervals.
125 changes: 125 additions & 0 deletions cpp/benchmarks/reduction/lto_benchmark.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once

#include <cudf_test/column_utilities.hpp>

#include <cudf/types.hpp>
#include <cudf/utilities/error.hpp>

#include <cuda/stream>

#include <algorithm>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstdint>
#include <functional>
#include <iterator>
#include <optional>
#include <ostream>
#include <stdexcept>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>

namespace reduction_benchmark {
constexpr int32_t warmups = 4;
constexpr int32_t measurements = 5;

struct options {
bool smoke = false;
std::optional<cudf::size_type> rows;
std::string csv = "reduce_lto.csv";
};

struct workload {
std::string name;
std::string shape;
cudf::size_type rows;
cudf::size_type segments;
int32_t null_percent;
std::string hint;
double logical_bytes;
};

template <typename T>
std::vector<std::optional<T>> host_values(cudf::column_view view, cuda::stream_ref stream)
{
auto [values, mask] = cudf::test::to_host<T>(view, stream);
constexpr auto word_bits = sizeof(cudf::bitmask_type) * CHAR_BIT;
std::vector<std::optional<T>> result(view.size());
for (cudf::size_type row = 0; row < view.size(); ++row) {
if (mask.empty() || ((mask[row / word_bits] >> (row % word_bits)) & 1U)) {
result[row] = values[row];
}
}
return result;
}

template <typename T>
void expect_equal(std::vector<std::optional<T>> const& actual,
std::vector<std::optional<T>> const& expected)
{
if (actual.size() != expected.size()) { throw std::runtime_error{"Output size mismatch"}; }
for (size_t index = 0; index < actual.size(); ++index) {
if (actual[index].has_value() != expected[index].has_value()) {
throw std::runtime_error{"Output validity mismatch"};
}
if (!actual[index]) { continue; }
if constexpr (std::is_floating_point_v<T>) {
auto const tolerance = T{1e-9} * std::max(T{1}, std::abs(*expected[index]));
if (!std::isfinite(*actual[index]) ||
std::abs(*actual[index] - *expected[index]) > tolerance) {
throw std::runtime_error{"Output value mismatch"};
}
} else if (*actual[index] != *expected[index]) {
throw std::runtime_error{"Output value mismatch"};
}
}
}

template <typename Execute, typename Validate>
void measure(std::ostream& output,
workload const& work,
std::string_view engine,
std::string_view layout,
cuda::stream_ref stream,
Execute&& execute,
Validate&& validate)
{
for (int32_t iteration = 0; iteration < warmups; ++iteration) {
auto result = std::invoke(execute);
stream.sync();
if (iteration == warmups - 1) { std::invoke(validate, result); }
}
double samples[measurements]{};
for (int32_t iteration = 0; iteration < measurements; ++iteration) {
stream.sync();
auto const start = std::chrono::steady_clock::now();
auto result = std::invoke(execute);
stream.sync();
samples[iteration] =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start).count();
if (iteration == measurements - 1) { std::invoke(validate, result); }
}
std::vector<double> sorted(std::begin(samples), std::end(samples));
std::sort(sorted.begin(), sorted.end());
auto const median = sorted[measurements / 2];
output << work.name << ',' << work.shape << ',' << engine << ',' << work.rows << ','
<< work.segments << ',' << work.null_percent << ',' << work.hint << ',' << layout << ','
<< work.logical_bytes << ',' << median << ',' << sorted.front() << ',' << sorted.back()
<< ',' << work.logical_bytes / (median * 1e6);
for (auto sample : samples) {
output << ',' << sample;
}
output << '\n';
output.flush();
}

void run_q13(options const& settings, std::ostream& output);
void run_segmented(options const& settings, std::ostream& output);
} // namespace reduction_benchmark
86 changes: 86 additions & 0 deletions cpp/benchmarks/reduction/plot_lto.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Plot fixed-loop C++ reduction results as SVG."""
import argparse
import csv
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt


LABELS = {"cudf_ast": "cuDF AST", "cudf_ast_jit": "cuDF AST JIT", "lto": "LTO"}


def plot(records, destination, subtitle):
destination.mkdir(parents=True, exist_ok=True)
q13 = [row for row in records if row["workload"] == "tpcds_q13_post_join" and int(row["rows"]) > 0]
for nulls in sorted({row["null_percent"] for row in q13}, key=int):
points = [row for row in q13 if row["null_percent"] == nulls]
for throughput in (False, True):
fig, ax = plt.subplots(figsize=(10, 5), layout="constrained")
for engine, label in LABELS.items():
group = sorted((row for row in points if row["engine"] == engine),
key=lambda row: int(row["rows"]))
x, y, lower, upper = [], [], [], []
for row in group:
median, minimum, maximum = (float(row[key]) for key in
("median_ms", "min_ms", "max_ms"))
value = float(row["logical_bytes"]) / (median * 1e6) if throughput else median
low = float(row["logical_bytes"]) / (maximum * 1e6) if throughput else minimum
high = float(row["logical_bytes"]) / (minimum * 1e6) if throughput else maximum
x.append(int(row["rows"]))
y.append(value)
lower.append(value-low)
upper.append(high-value)
ax.errorbar(x, y, yerr=[lower, upper], marker="o", capsize=3, label=label)
metric = "Throughput" if throughput else "Latency"
ax.set(xscale="log", xlabel="Input rows",
ylabel="Logical GB/s" if throughput else "Milliseconds",
title=f"TPC-DS Q13 Aggregation {metric}\n{subtitle}")
ax.legend(title=f"{nulls}% null aggregate inputs")
fig.savefig(destination / f"q13_{metric.lower()}_null{nulls}.svg")
plt.close(fig)

for workload in ("segmented_sum", "segmented_sum_max"):
for nulls in sorted({row["null_percent"] for row in records
if row["workload"] == workload}, key=int):
points = [row for row in records if row["workload"] == workload
and row["null_percent"] == nulls]
shapes = ("small", "large", "uneven")
methods = (("cudf", "none"), ("lto", "unknown"), ("lto", "known"))
fig, ax = plt.subplots(figsize=(10, 5), layout="constrained")
width = 0.25
for index, (engine, hint) in enumerate(methods):
group = [next(row for row in points
if row["shape"] == shape and row["engine"] == engine
and row["hint"] == hint) for shape in shapes]
medians = [float(row["median_ms"]) for row in group]
ranges = [[float(row["median_ms"])-float(row["min_ms"]) for row in group],
[float(row["max_ms"])-float(row["median_ms"]) for row in group]]
label = "cuDF" if engine == "cudf" else f"LTO ({hint} length)"
ax.bar([pos+(index-1)*width for pos in range(len(shapes))], medians,
width, yerr=ranges, capsize=3, label=label)
labels = []
for shape in shapes:
row = next(row for row in points if row["shape"] == shape)
labels.append(f"{shape}\n{int(row['rows']):,} rows / {row['segments']} segments")
ax.set_xticks(range(len(shapes)), labels)
ax.set(yscale="log", ylabel="Milliseconds (log scale)",
title=f"{workload.replace('_', ' ').title()} Latency\n{subtitle}\n{nulls}% null inputs")
ax.legend()
fig.savefig(destination / f"{workload}_latency_null{nulls}.svg")
plt.close(fig)


if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("csv", type=Path)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--subtitle", default="")
args = parser.parse_args()
with args.csv.open() as source:
plot(list(csv.DictReader(source)), args.output_dir, args.subtitle)
72 changes: 72 additions & 0 deletions cpp/benchmarks/reduction/reduce_lto.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "lto_benchmark.hpp"

#include <cudf/utilities/memory_resource.hpp>

#include <rmm/mr/cuda_memory_resource.hpp>
#include <rmm/mr/pool_memory_resource.hpp>
#include <rmm/mr/statistics_resource_adaptor.hpp>

#include <cuda_runtime_api.h>

#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <utility>

int main(int argc, char** argv)
{
try {
reduction_benchmark::options settings;
for (int32_t index = 1; index < argc; ++index) {
std::string_view argument{argv[index]};
if (argument == "--smoke") {
settings.smoke = true;
} else if (argument == "--csv" && index + 1 < argc) {
settings.csv = argv[++index];
} else if (argument == "--rows" && index + 1 < argc) {
auto const rows = std::stoll(argv[++index]);
if (rows < 0 || rows > std::numeric_limits<cudf::size_type>::max()) {
throw std::invalid_argument{"Row count is outside the cuDF range"};
}
settings.rows = static_cast<cudf::size_type>(rows);
} else {
throw std::invalid_argument{"Usage: REDUCE_LTO_BENCH [--smoke] [--rows N] [--csv PATH]"};
}
}
::setenv("LIBCUDF_JIT_ENABLED", "1", 1);
size_t free_bytes, total_bytes;
CUDF_CUDA_TRY(cudaMemGetInfo(&free_bytes, &total_bytes));
auto const budget = (total_bytes / 100 * 90) & ~size_t{255};
rmm::mr::cuda_memory_resource upstream;
rmm::mr::pool_memory_resource pool{
rmm::device_async_resource_ref{upstream}, std::min<size_t>(256 << 20, budget), budget};
rmm::mr::statistics_resource_adaptor statistics{rmm::device_async_resource_ref{pool}};
using resource = cuda::mr::any_resource<cuda::mr::device_accessible>;
auto previous =
cudf::set_current_device_resource(resource{rmm::device_async_resource_ref{statistics}});
struct restore_resource {
resource previous;
~restore_resource() { cudf::set_current_device_resource(std::move(previous)); }
} restore{std::move(previous)};
std::ofstream output{settings.csv};
if (!output) { throw std::runtime_error{"Cannot open benchmark CSV output"}; }
output << std::setprecision(12)
<< "workload,shape,engine,rows,segments,null_percent,hint,output_layout,logical_bytes,"
"median_ms,min_ms,max_ms,logical_GBps,sample0_ms,sample1_ms,sample2_ms,sample3_ms,"
"sample4_ms\n";
reduction_benchmark::run_q13(settings, output);
reduction_benchmark::run_segmented(settings, output);
std::cout << "Validated all cases; four warmups and five timed executions per case. CSV: "
<< settings.csv
<< "\nPeak tracked device bytes: " << statistics.get_bytes_counter().peak << '\n';
} catch (std::exception const& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
Loading
Loading