Elamur Research

Generating Custom Code for Efficient Query Execution on Heterogeneous Processors

Paper · 2017 · Sebastian Breß, Bastian Kocher, Henning Funke et al.

Summary

A database can run the same SQL query on a CPU and a graphics processor and get the same answer, yet get very different performance from the same implementation. A CPU may do well if each worker scans a block of rows and writes its results immediately. A graphics processor may be faster if many more workers first find the matching rows, calculate where each result belongs, and then write the results in a separate pass. The paper presents Hawk, a query compiler that can generate either implementation from the same query plan. Its aim is to replace some of the work of tuning a database engine by hand for each processor with a search over generated code.

Hawk starts by dividing the query into pipelines, each of which carries out a sequence of operations such as scanning, filtering, joining, or aggregating rows. It records those operations in a form that keeps the query’s requirements distinct from choices about how to execute it. The compiler can then change the way workers share the input, the layout and implementation of a hash table, or whether generated code uses a branch to handle a filter. It assembles code for each variant into OpenCL kernels, the functions that run on the target device. To choose settings for a processor, Hawk compiles and times variants on a representative workload before ordinary query processing. It searches one setting at a time and revisits choices as their surroundings change.

The experiments cover a CPU, an integrated GPU, a dedicated GPU, and a Many Integrated Core accelerator, which the paper calls a MIC. The clearest result is that the device for which code was tuned can matter even when the device running it stays fixed. On the dedicated GPU, the CPU-tuned implementation of Projection Query 2 was slower than the locally optimized implementation by a reported factor of 345. The search also saved time during tuning. On the CPU, exploring Star Schema Benchmark Q4.1 at scale factor 1 took 479 seconds with the feature-wise search, compared with 197,139 seconds for the backtracking search.

The authors found that a configuration learned across queries was often a good starting point, especially on the CPU. The accelerators sometimes benefited much more from settings chosen for an individual query. For TPC-H Q5 at scale factor 10, the dedicated GPU ran Hawk’s workload-tuned variant in 7.091 seconds and its query-tuned variant in 0.261 seconds, with compilation excluded. Those results distinguish what can be learned once about a processor from what still depends on the particular work it is asked to do.

Deep dive: Generating Custom Code for Efficient Query Execution on Heterogeneous Processors

Hawk generates and times alternative SQL implementations to find fast query code for CPUs, GPUs, and other processors without manual tuning. · about 36 minutes to read

The problem and its context

Why portable code still needs tuning

The paper starts from a constraint on processor design. A chip has a limited energy budget, and vendors respond by building processors that devote different kinds of hardware to different tasks. A machine can either house CPU and GPU cores on a single chip or use a CPU alongside a distinct accelerator. More computational capacity and memory bandwidth give a database engine room to improve, provided its implementation gives the device useful work in a form it can carry out efficiently.

Consider a query that finds qualifying rows and copies some of their columns into an output. If a few workers each handle a large block, each can advance through its own rows with relatively little coordination. If a device needs many lightweight workers to keep its execution resources occupied, a shared decision about where to write each row can become expensive. A worker may have to wait for others even though it has already determined that its row belongs in the result. A different algorithm can remove that competition by calculating output positions ahead of time. It then has to do extra work to compute those positions, and it may have to revisit the data. Which cost matters more depends on the processor and on what the query does.

The paper distinguishes functional portability from the performance of a particular implementation. OpenCL supplies the first. It gives the compiler a common way to express work and compile it for a supported device. A kernel that runs on a GPU can also be compiled for a CPU through the same interface. The interface leaves decisions such as how many workers to launch, which rows they should access together, and where they should combine partial results to the program and its execution setup. These are some of the central choices in GPU and parallel computing.

This creates a problem for a database engine that expects to run on several kinds of hardware. It can maintain and tune different operator implementations for different processors, which the authors describe as costly and prone to errors. It can also standardize on a shared implementation, gaining reach while leaving some performance available through specialization. The paper asks how much of the specialization can move into a common compiler. That compiler needs a representation in which the permitted changes are explicit, and a way to find out which changes pay off together on a particular machine.

What query compilation already offered

In the authors’ account, compiling queries has a history that reaches back to System R. Interest returned as main-memory databases made memory traffic and the number of executed CPU instructions especially important. The related work includes query-specific code generated through Java’s just-in-time facilities and systems that fill templates to produce C source for a separate compiler. The authors also describe Neumann’s use of LLVM intermediate representation, which sought to reduce compilation cost by giving the next compiler stage a lower-level input.

A major idea Hawk inherits from Neumann is to fuse operations within a pipeline. Think of a scan whose rows first pass through a filter and then supply values for an arithmetic expression. A compiled pipeline can test a row, compute the expression when the row qualifies, and use the result while the data are still close to the processor. The loop then advances to the next row. The important unit of compilation is the chain of work carried out together. The paper also discusses morsel-driven parallelism, which distributes work on compiled pipelines with awareness of where memory resides. It cites a comparison of vectorized and compiled execution that found reasons to combine compilation with processing data in blocks.

The work on GPU query execution supplied additional parts of the picture. Kernel Weaver could fuse kernels, including those for relational operators. The authors treat this kind of fusion as complementary to choosing an execution strategy that determines how many kernels a pipeline needs. They also describe a GPU approach that divides compilation into local computation, local accumulation, and global accumulation. For grouped aggregation, Hawk’s use of hash tables draws on prior analysis of grouping and aggregation on GPUs. These lines of work supplied concrete algorithms whose costs could differ once they ran on other devices.

Other systems already used abstractions to reach multiple targets. In the paper’s account, Voodoo uses a vector-based intermediate algebra and generates OpenCL for processors including CPUs and GPUs. Hawk’s pipeline programs describe work at a different level. The authors say that it would be possible to generate Voodoo algebra from a pipeline program. They distinguish Hawk by its explicit space of code variants and its search over that space. Ocelot provides another close comparison. It shares OpenCL operator implementations across devices and makes memory access configurable. Hawk can also change how a whole pipeline executes, which may alter the number and purpose of its kernels.

What had already been proposed for adaptation

The authors place their search alongside earlier ways to adapt execution. Micro Adaptivity provides alternative implementations of functions and can switch between them during vector-at-a-time processing. Its decisions can respond to the query and the characteristics of the data being processed. The paper also discusses work by Rosenfeld and colleagues that generated alternatives for selection and aggregation and examined which transformations suited different processors. Hawk builds its search around the compiled pipeline, where choices about several operations and about the pipeline’s overall execution can be expressed together.

A further precedent comes from progressive optimization using processor performance counters. In the work the authors cite, observations about cache accesses, branch mispredictions, and how many rows pass a predicate can inform changes to the order of predicate evaluation as a query runs. Hawk’s evaluated search instead measures candidate implementations ahead of ordinary processing. The authors see room for runtime adaptation alongside their compiler. The immediate question they set out to answer is whether a database can generate and test a fast implementation for a device whose performance preferences have yet to be measured.

The method, step by step

From a query plan to pipeline programs

A query plan gives the database an order in which to carry out relational operations. A pipeline is a stretch of that plan along which a row can continue through several operations as soon as it is available. Some operations impose a boundary. A hash join, for example, may first read an input and build a hash table. A later part of the query looks up keys in that table to find matching rows. The lookups depend on a structure that the earlier part has prepared. Building that structure therefore gives the compiler a reason to end one pipeline and begin another.

Hawk uses the produce and consume routines of the underlying compilation scheme to find these boundaries and gather operations. Produce routines work down the plan from its root. When traversal arrives at a scan, consume routines work back up through the operations that can accept its rows. Each adds work to the current pipeline until the compiler reaches a boundary. In the paper’s join example, filtered inputs from separate tables build their respective hash tables. Another pipeline scans the remaining table, checks its filter, probes the built tables, and groups the joined rows to calculate a sum. The build and probe pipelines depend on one another even though each has its own program.

Hawk records what the consume routines have gathered as a pipeline program, an ordered intermediate representation between the query plan and the generated source. Scanning a table becomes a loop operation. Checking which rows qualify becomes a filter operation. The record may also contain operations for building or probing a hash table, performing arithmetic, computing a cross product, aggregating rows, and copying selected attributes to output columns. Some entries describe actions below the level of a relational operator. A build and a probe can appear in different pipelines even though both serve the same join.

Each operation carries information about the answer it must help produce. A filter needs a predicate, which is a condition that decides whether a row qualifies. A projection needs the attributes it should write. A grouped aggregation needs the attributes that define the groups and the expressions to compute within them. Other parameters control code generation, such as the implementation of a hash table or the way a filter passes its outcome to the rest of the pipeline. Recording both types of information gives the compiler a place to change execution details while preserving the meaning of the query.

The architecture has a search component that chooses a configuration and a generation component that realizes it. During calibration, the compiler generates and runs candidates so search can use the observed times. After calibration, the chosen configuration supplies the settings for compiling a query on the target device.

How Hawk generates and selects pipeline code

The steps in order.

How Hawk generates and selects pipeline codeStep 1: Divide the query plan into operator pipelines1. Divide the query plan into operator pipelinesStep 2: Record operations and parameters as pipeline programs2. Record operations and parameters as pipeline programsStep 3: Select a candidate configuration for the target processor3. Select a candidate configuration for the target processorStep 4: Set parameters and transform the pipeline program4. Set parameters and transform the pipeline programStep 5: Generate code fragments for each operation5. Generate code fragments for each operationStep 6: Assemble the fragments into OpenCL kernels6. Assemble the fragments into OpenCL kernelsStep 7: Compile and time candidates during workload calibration7. Compile and time candidates during workload calibrationStep 8: Use the learned configuration for later queries8. Use the learned configuration for later queries

How the representation expresses a choice

A scan illustrates the difference between the table being read and the way the read is scheduled. The paper describes the loop operation with this notation.

LOOP(T; step, s, e)

LOOP is the operation that visits input tuples, or rows. T names the input table. The semicolon marks the boundary between the regular parameter and the code generation settings. step is the amount by which the position advances, s is the starting index, and e is the ending index of the loop. When Hawk redistributes the work across threads, those settings help determine the rows each thread visits. The operation still refers to the same input table.

Arithmetic gives another example. The paper writes the computation carried out by an arithmetic operation as a mapping between attributes.

f : A × B → C

f is the computation. A and B denote its input attributes, × denotes the pairing of those inputs, and → points to the result attribute C. The operation also has a code generation setting for an element offset. That offset becomes useful when one iteration of the generated loop handles more than the current row. The arithmetic expression remains the same for each row to which it applies.

For an aggregation, the list of expressions is written as follows.

F = (f₁, f₂, …, fₙ)

F is the ordered list of aggregation expressions. Each fᵢ is an expression at position i in that list, and n is the number of expressions. The subscripts ₁ and ₂ mark the initial positions, ₙ marks the final one, and the ellipsis stands for intervening entries. The equals sign assigns the list to F. In a grouped aggregation, the program separately stores the attributes that identify the groups. One set of grouping attributes can therefore be used with several expressions, such as computations that maintain different aggregate values.

A configuration can set properties that apply to the whole program, including its execution strategy, memory access pattern, and thread count. Other changes reach inside individual operations. Choosing a hash table affects the operations that insert data and look it up. Loop unrolling can change the structure of the sequence itself. Hawk applies transformation passes to make those changes before generating source code. In implementation terms, the parameters and the order of applied transformations determine which version will be emitted.

Projection and the cost of writing results

The paper calls pipelines that produce output rows without performing aggregation projection pipelines. A row that survives the pipeline’s filters and join lookups is written to output buffers holding the requested columns. The paper’s Projection Query 1 provides a simple example. It reads lineorder, selects rows whose lo_quantity is below 25, and returns the line number, quantity, and revenue. The logical work fits in a straightforward loop. The execution strategy determines how many copies of that work run in parallel and how those workers place their results.

For coarse-grained parallelism, Hawk generates a serial loop for a pipeline and runs copies on different chunks of the input. Each copy walks through its assigned rows, evaluates the filter, and writes qualifying results as it goes. The paper describes using an OpenCL device’s compute-unit count to set the number of parallel copies in the evaluated single-pass projection strategy. A compute unit is a subdivision of the device that OpenCL exposes to the program. In this setup, each worker has enough of a chunk to carry out a substantial piece of the scan.

The fine-grained version organizes output placement ahead of time. Hawk first generates a filter kernel that marks the input positions that produce results. This kernel contains operations that affect qualification, including hash probes where a join determines which rows survive. The flags then go through an exclusive prefix sum. At each position, this operation counts the flags set at earlier positions. A qualified row can use that count as its output position. Two qualified rows get distinct positions because the count seen by the later row includes the earlier one.

A projection kernel then writes the results in parallel. Where a join supplies values from an associated row, the projection kernel repeats the hash probe to obtain the payload, meaning the values stored with its lookup key. It also performs the arithmetic needed for the output. A simple filter-and-project query can use the flags directly to tell which inputs need an output. The extra pass and the intermediate arrays have a cost. Their purpose is to let many workers write to predetermined positions without competing for a shared counter as they produce results.

The difference is visible even before the device compiler makes its own decisions. The single-pass strategy asks it to compile a kernel that brings the work together inside one loop. The multi-pass strategy requires separate kernels for qualification and output and a prefix-sum phase between them. Choosing the strategy changes which intermediate data exist and when parts of the query execute. That is a wider decision than choosing a different expression for the same inner loop.

Grouped aggregation and contention

An aggregation pipeline ends by accumulating values. For a grouped sum, each qualifying row identifies a group, and its value updates the sum for that group. Hawk places the groups and their aggregate values in a hash table. The table gives a worker a place to look up or create a group’s entry. Workers can still interfere with one another when several want to update the same entry. Hawk’s implementations use OpenCL atomic operations to coordinate concurrent updates where needed.

If the query is expected to produce few groups, many workers may repeatedly target the same entries. In the local strategy, Hawk distributes work across several hash tables, each maintained by a group of threads. Each table holds partial aggregates. A later phase merges them into a global result table. This reduces the number of workers competing over each partial table and gives the compiler separate choices for the number of tables and the number of threads assigned to each one. The cost is maintaining the separate tables and combining their results.

For many groups, the paper describes a global strategy. Workers update a shared table directly. As updates spread across group keys, the expected savings from local copies can shrink, while merging many partial entries can become expensive. In Hawk’s design, global aggregation is the limiting case of the local scheme with a single table. It retains a choice about how many threads work on the table. The expected group count motivates including both strategies in the search. The measured performance still depends on the rest of the implementation.

The compiler also uses the local scheme to express different degrees of parallelism. For coarse-grained aggregation, the design assigns one thread to a table and uses as many tables as there are OpenCL compute units. Giving a work group more threads increases parallelism within a table. The same program can therefore express a shift in both the amount of work done concurrently and the amount of coordination required. The paper’s experimental search specifies its own candidate work-group sizes within this design.

Changing the data structure and the inner loop

Hawk can choose among hash table implementations by changing the settings of the affected operations. The paper illustrates replacing linear probing with Cuckoo hashing in both the build and probe pipeline. Linear probing generates access code using a single hash function. The Cuckoo version can generate code for a configurable number of hash functions. In each case, the choice determines how key insertions and lookups are performed, so the generator emits the code appropriate to that choice.

The join imposes a consistency rule. A table built by one pipeline has to be read by another pipeline that understands the same table implementation and parameter values. Selecting the build and probe settings independently could produce code that disagrees on where a key would be stored. Hawk’s variation mechanism makes it possible to combine a table choice with different pipeline execution strategies or memory access patterns, while the query processor must coordinate the table choice across the operations that share it. The authors also describe specializing a table to leave out payload values the query does not need, reducing the space occupied by each entry.

The memory access transformation changes how loop indexes are assigned to workers. In sequential access, each worker receives a contiguous range and moves through it in order. Hawk generates code to obtain the start and end of that worker’s range. In coalesced access, a thread starts at the input index corresponding to its identifier and advances by the total number of threads. Each thread’s own positions are spaced out. At a given step, neighboring threads read neighboring positions. For column data, this changes which elements of the same column are requested together.

Software predication changes how the effect of a condition is represented in the code. In branched mode, the filter opens a conditional block, and succeeding operations inside that block execute for a qualifying row. In predicated mode, the filter produces a numeric indicator. In the paper’s projection example, code writes at the current output position and uses the indicator to decide whether to advance that position. If the row fails, the position stays available for another write and the logical result size does not increase. A row that passes advances the position.

The paper illustrates the approach for a sum with an update equivalent to the following.

aggregate ← aggregate + attr[id] × result_increment

aggregate is the running total. The arrow assigns the expression on its right to that total. attr is the input column, id is the current row index, and brackets select the value at that index. result_increment is the indicator produced by the filter, with a value of one for a qualifying row and zero for a rejected row. The multiplication sign applies the indicator to the value, and the plus sign adds the resulting contribution. A failed predicate therefore supplies a zero contribution in this example.

The pipeline has to use its predication mode consistently. If a filter only produces an indicator, later operations must respect that indicator when deciding which work changes the result. A projection or aggregate emitted on the assumption that an enclosing branch filtered out rejected rows would otherwise receive rows it was never meant to include. This is a case where the representation lets the compiler change settings on individual operations, but the transformation has to carry through all the affected operations as a unit.

Loop unrolling shows why Hawk also supports structural changes. The paper illustrates a loop that handles successive rows in the same iteration by making copies of the filter and aggregation operations. Each copy gets the offset of the row it handles, and the loop advances by the amount of input covered by an iteration. The emitted example has a bound for the full iterations and leaves the remaining rows to be handled afterwards. The authors also discuss vectorization as a possible transformation. Their example of extending a scan with SIMD, or single-instruction, multiple-data processing, would require a mode and a template that test several rows together.

Generating and assembling the code

Once the pipeline program has been transformed, Hawk asks every operation to generate a fragment of code. A fragment has places for host-side declarations, initialization, and cleanup. It also has places for device-side declarations and for code to be inserted at the top or bottom of the kernel body. In OpenCL, the host is the CPU running the API calls, while a device is the processor selected to run a kernel. Including both sides in a fragment lets an operation describe setup or cleanup work as well as the computation it needs in the kernel.

The top and bottom parts make it possible to nest one operation within another. A scan fragment can open a loop near the top and close it at the bottom. A branched filter opens a conditional within the loop. The projection’s writes sit inside the conditional, with the scopes closed in the appropriate order. Hawk assembles the emitted source segments into a complete kernel. The compiler can thus express the structure of generated code through the placement of fragments, even when a single operation contributes pieces to several locations.

The execution strategy controls routing. The authors illustrate this with a query that reads column b from table t for rows where a is less than 5. A single-pass interpreter puts the loop, filter, and output writes in one kernel. A multi-pass interpreter places the predicate in a filter kernel and places the output in a projection kernel that uses positions produced from the flags. Loop code can be needed on both sides of that division. In a join pipeline, a probe can likewise contribute to multiple kernels because qualification and retrieval of output values may require it at different stages.

This arrangement gives an operation’s generator responsibility for its implementation and gives the strategy’s interpreter responsibility for organizing the kernels. The authors describe adding another hash table by supplying code for initialization, access, and modification and exposing the new choice to the affected operations. An algorithm that requires a new operation can be added to the representation and registered for variant generation. The implemented target is OpenCL. The paper raises CUDA as a possible alternative backend for the design, without reporting a CUDA implementation of Hawk.

Learning a configuration from timings

Hawk’s learning procedure is an offline search over implementation settings. Its input is a set of settings and a workload of representative SQL queries. The paper denotes the variation dimensions and workload as follows.

D = {D₁, …, Dₙ}

D is the collection of variation dimensions. Each Dᵢ is a set of allowable values for one choice, indexed by i. The subscripts run from the first dimension D₁ to the final dimension Dₙ, where n counts the dimensions. The braces enclose the collection, the ellipsis omits the intervening dimensions, and the equals sign defines D.

W = {Q₁, …, Qₖ}

W is the calibration workload. Each Qᵢ is a query in it, Q₁ is the first query, and Qₖ is the last. Here k is the number of workload queries. The braces and ellipsis denote the collection of queries, and the equals sign defines the name W.

v = (v₁, …, vₙ) ∈ D₁ × … × Dₙ

v is the configuration. Each coordinate vᵢ is the selected value from its corresponding dimension Dᵢ. Parentheses group those selected values into an ordered tuple. The sign ∈ means the tuple belongs to the space on its right, and × denotes the Cartesian product, the set of possible combinations of one value from each dimension. The endpoints and ellipses show that the construction extends through all n dimensions. Where a strategy exposes specific settings of its own, such as the number of local aggregation tables, the tested combinations reflect that strategy’s applicable choices.

The search starts with the first allowed value in each dimension. It copies that configuration, changes the value along the current dimension, and compiles and executes the workload for the candidate. It tries each value of the dimension, retaining the one with the best measured execution time. The retained value then forms part of the configuration used to test the next dimension. The paper’s pseudocode initializes the best time for a dimension to ∞, meaning an unbounded starting time, so the first measured candidate supplies a finite time to beat.

One sweep through the settings can leave an earlier decision worth revisiting. A layout that worked well with the original number of workers may perform differently after the search has changed the number of workers. Hawk repeats the sweep until a sweep leaves the configuration unchanged or it reaches q, the cap on the number of iterations. The paper suggests examining execution strategy, thread count, and memory access early because they tend to have a large effect. Reaching a stable configuration allows an early stop. A coordinated change in several dimensions could still yield a better choice than the search can discover by moving along one dimension at a time.

The learned settings supply a heuristic to the query optimizer. Calibration uses recorded execution behavior on the target device and the chosen test workload. Ordinary query processing can then use the settings to generate an executable variant without rerunning that search. This is the sense in which Hawk learns a processor configuration. The timings guide a sequence of concrete compiler decisions, and the configuration it returns is conditioned on the queries used to obtain them.

Experiments and results

Hardware, workloads, and measurements

The authors integrated Hawk with CoGaDB, an in-memory database with column-major storage. They evaluated it on machines providing an AMD A10-7850K CPU and integrated GPU, an Nvidia Tesla K40M dedicated GPU, and an Intel Xeon Phi 7120 MIC. The results distinguish the integrated GPU, or iGPU, from the dedicated GPU, or dGPU. Device vendors supplied the OpenCL SDKs and drivers used to compile and execute kernels.

The evaluation uses the Star Schema Benchmark, abbreviated SSB, and TPC-H. Tests involving full variant exploration used scale factor 1, and the paper reports scale factor 10 for the other main experiments. A scale factor sets the size of the benchmark data. Larger inputs would make the weakest variants too expensive to wait for in the exploration. The authors also report that OpenCL could use only 2.2GB of the integrated GPU’s main memory, which limited how far they could increase the scale factor.

For processors with dedicated memory, the authors cached the inputs before running variants. The measured executions therefore address the performance of processing resident data. The design removes the time to bring those inputs over PCIe from those runs. The paper reports that each variant of a pipeline program was executed 5 times and that the authors calculated mean and standard deviation. They took the fastest average among the tested variants as the device-specific result of the full search. They also pruned exploration after detecting very slow variants, using an execution time greater than one second as their criterion. OpenCL did not let them interrupt a kernel already running.

The representative projection queries differ in how much result data they produce. The paper reports 50 % selectivity for Projection Query 1, where the desired columns include line number, quantity, and revenue. This query places demands on both reads and writes. Projection Query 2 returns the same columns, adding conditions on discount and revenue to the quantity condition. It writes far fewer results, so the authors use it to study a case dominated by reading and checking the input. The aggregation examples also use lineorder. Aggregation Query 1 sums quantity by shipping mode and gives relatively few groups. Aggregation Query 2 sums quantity by part key, giving many groups and a greater dependence on access latency according to the authors.

TPC-H Q1 adds multiple computations and aggregate expressions to a single pipeline. The full-search SSB join example takes the experiment across pipeline boundaries. SSB Q4.1 uses build pipelines for four joins and an aggregation pipeline that probes the resulting hash tables. For the broader workload the paper describes using SSB Q1.1–Q1.3, Q3.2–Q3.4, and Q4.1–Q4.3, as well as TPC-H Q5, Q6, and Q7. The full-query timing table presents results for the selected SSB queries and TPC-H Q5 and Q6. The broader measurements let the authors compare per-workload settings with choices specific to a query after investigating what happens within simpler pipelines.

The variant space and the baselines

Both projection and aggregation vary how threads access memory and whether predicates are branched or predicated. Projection combines these settings with a choice of single-pass or multi-pass execution. The single-pass case uses the device’s compute-unit count, while the multi-pass case tests different multipliers of that count. The paper lists the multipliers as 1, 8, 64, 256, 1024, 16,384, and 65,536. The design specifies 4 single-pass variants and 28 multi-pass variants, for a reported total of 32 projection variants.

The aggregation search includes linear probing and Cuckoo hashing. It also tests Murmur hashing and Multiply-Shift hashing as choices of hash function, a separate choice from the table implementation. For local aggregation, the set of compute-unit multipliers determines how many local tables the program can use. The paper tests 16, 32, 64, 128, 256, 512, and 1024 threads per table. Global aggregation uses the same choices of threads per table with only the shared table. The paper reports a total space of 896 aggregation variants.

The main baseline for tuning quality is the result of the full variant exploration. For each query and device, that exploration identifies the fastest tested variant on average, subject to the exploration procedure. The authors then take variants selected for one processor and run them on others. This holds the device fixed within each comparison and changes which configuration goes into the generated code. Another comparison uses the configuration learned by the feature-wise search, so the authors can ask whether it approaches the results of the more expensive search.

For the calibration cost comparison, the baseline is backtracking through variants for SSB Q4.1. For the scale factor 10 workload comparison, the baselines include configurations learned for other processors and code tuned for an individual query. HyPer provides an additional reference for CPU execution and for the compilation time of a simple projection. These comparisons answer different questions. A search timing concerns getting to a configuration. A kernel compilation timing concerns turning that configuration into executable code. An execution timing concerns the code once compiled.

Compilation time

For the simple projection comparison against HyPer, the authors report that compiling OpenCL using the CPU SDKs took two to three times as long as HyPer’s compilation of LLVM intermediate representation. For the GPU and MIC comparisons the reported factors run from 4.3 to 7.4. Even with those relative differences, the times in that simple comparison were below 100ms. This matters because query-specific code needs to be produced close enough to the time of use for its runtime improvement to be of practical interest.

The compilation distributions from the variant experiments add a more detailed view. For the plotted projection kernels, the authors report times below 70ms for the CPU, integrated GPU, and dedicated GPU, and below 100 ms for the MIC. Aggregation kernels require more generated code and generally take longer. The box plots summarize the middle 50 % of observations in each box and use whiskers that the paper describes as a 99 % confidence interval. These values summarize kernel compilation measurements, including the spread across variants.

TPC-H Q1 is a clearer test of a larger single pipeline. The authors report compilation times of 66ms on the CPU, 113ms on the integrated GPU, 216ms on the dedicated GPU, and 4.9s on the MIC. With multiple pipelines, compilation also has to produce code for separate stages of the query. The authors point out that different pipelines can be compiled in parallel. The MIC was the only processor in these experiments where even a single pipeline could take more than a second to compile. The authors suspect the SDK implementation, an explanation they treat as a hypothesis.

Running code tuned for another device

For Projection Query 1, the CPU-tuned variant was faster on the CPU than the integrated-GPU, dedicated-GPU, and MIC variants by reported factors of 25, 30, and 3.5, respectively. On the dedicated GPU, using the CPU’s variant incurred a reported slowdown of up to a factor of 237 compared with the locally optimized variant. The results expose a mismatch in execution strategy. The CPU variant uses a single pass and coarse-grained parallelism, while the accelerators’ tuned versions use fine-grained, multi-pass execution. Among the accelerator variants, the authors identify the number of threads as an important difference. The MIC also favored sequential access for this query, whereas the GPU variants used coalesced access.

The read-intensive Projection Query 2 preserves the broad pattern. The CPU-tuned variant on the integrated GPU and dedicated GPU was slower than the respective tuned variants by factors of 118 and 345. On the MIC the reported factor was 2.4. The authors judged the feature-wise search to have found configurations close to the full-search results on all the tested devices for this query. For Projection Query 1 they report similarly close learned results on the CPU and GPUs, with a gap on the MIC. The learned MIC variant there was slower than the full-search choice by a factor of 1.8.

Aggregation Query 1, the few-group case, produced substantial penalties for the CPU-tuned code running on accelerators. The reported slowdowns compared with variants tuned for the respective devices reached factors of 606 on the integrated GPU, 861 on the dedicated GPU, and 24 on the MIC. The paper also reports deltas between the accelerator-specific choices, so the comparison concerns more than a distinction between CPU code and all accelerator code taken together. On this query the learned MIC variant was slower than its full-search counterpart by a factor of 3.4. On the CPU and GPUs, the authors describe the learned results as close to the full-search choices.

With Aggregation Query 2, the many-group case, the fastest variants for the integrated and dedicated GPUs had the same configuration. On the MIC, the MIC-tuned and GPU-tuned variants reached the same performance as reported by the authors. Even here, the CPU variant on the accelerators lagged the locally optimized variants by reported factors of up to 94 for each GPU and 23 on the MIC. Thus the amount of overlap between the accelerators’ preferences depends on the aggregation being compiled. On the more complex TPC-H Q1 and SSB Q4.1, the authors again observed substantial differences when moving variants across processors, with some MIC timings showing considerable variation.

How much work the search saves

The calibration comparison times the whole exploration for SSB Q4.1 at scale factor 1. The chart shows the CPU comparison. The backtracking run measures the cost of traversing the space with the exhaustive procedure. The feature-wise result includes the search that tests settings in turn and stops when its algorithm has met its termination condition.

CPU variant search for SSB Q4.1 at scale factor 1

The feature-wise search finishes much sooner than backtracking on the same processor and query.

CPU variant search for SSB Q4.1 at scale factor 1Backtracking: 197,139Backtracking197,139Hawk feature-wise search (this paper): 479Hawk feature-wise search (this paper)479
The numbers
System or settingseconds of variant exploration
Backtracking197,139
Hawk feature-wise search (this paper)479

For the integrated GPU, the paper reports 78,388 seconds for backtracking and 1,219 seconds for the feature-wise search. On the dedicated GPU, the corresponding search times are 52,897 and 1,036 seconds. On the MIC they are 177,914 and 3,390 seconds. The authors report their largest improvement on the CPU as a factor of 411. This is the comparison that supports their proposal to run calibration offline, for example around installation. The elapsed time includes trying alternatives because that is an essential cost of the selection procedure.

What workload tuning achieves on full queries

At scale factor 10, Hawk learns configurations from benchmark workloads for the CPU, dedicated GPU, and MIC. The learned CPU projection strategy uses a single pass, while the dedicated GPU and MIC use multiple passes. All the learned workload configurations shown use local hash table aggregation. The CPU uses sequential access and linear probing. The dedicated GPU and MIC use coalesced access and Cuckoo hashing. The learned settings use branched predicate evaluation for this workload.

The thread settings indicate how different the generated execution can be even when some of those choices agree. For projection, the CPU uses a multiplier of 1, the dedicated GPU 16,384, and the MIC 65,536. These values are multiplied by the target’s compute-unit count to specify the parallel work. For aggregation, the work-group sizes are 256 for the CPU, 1024 for the dedicated GPU, and 64 for the MIC. A shared preference for local aggregation therefore leaves considerable room for distinct implementations.

The reported full-query times exclude compilation. For SSB Q4.1 running on the CPU at scale factor 10, HyPer took 0.654 seconds, while Hawk’s CPU workload configuration took 0.567 seconds. Hawk variants drawn from the dedicated GPU and MIC workloads took 2.186 and 1.559 seconds, respectively, on that same CPU. On TPC-H Q6, the CPU-side measurement was 0.147 seconds for HyPer and 0.185 seconds for Hawk with its CPU workload variant. The authors describe Hawk’s CPU execution as broadly comparable in magnitude to HyPer’s, which is the scope of this CPU reference.

The most pronounced reported benefit from tuning to a query was on the dedicated GPU for TPC-H Q5. The chart compares the workload-derived settings and the per-query setting on that same device. The CPU and MIC labels in the chart identify where the settings came from. The timings all come from the dedicated GPU at scale factor 10.

TPC-H Q5 execution on the dedicated GPU at scale factor 10

Tuning for the individual query substantially reduces execution time past the dedicated GPU workload configuration.

TPC-H Q5 execution on the dedicated GPU at scale factor 10Hawk CPU workload settings: 73.572Hawk CPU workload settings73.572Hawk dedicated GPU workload settings: 7.091Hawk dedicated GPU workload settings7.091Hawk MIC workload settings: 10.605Hawk MIC workload settings10.605Hawk per-query settings (this paper): 0.261Hawk per-query settings (this paper)0.261
The numbers
System or settingseconds of query execution
Hawk CPU workload settings73.572
Hawk dedicated GPU workload settings7.091
Hawk MIC workload settings10.605
Hawk per-query settings (this paper)0.261

The authors report the maximum gain from per-query tuning over the corresponding workload configuration as a factor of 1.02 on the CPU, 27 on the dedicated GPU for TPC-H Q5, and 1.43 on the MIC for SSB Q3.2. Query-specific variants mainly differed in the thread multipliers, according to the paper. It also reports cases that benefited from software predication or from global aggregation, including the preference for global aggregation for TPC-H Q5 on the GPU and MIC. The full-query experiment shows how much the device-wide heuristic can accomplish and where the behavior of a particular query can justify a different setting.

What the ablations show

Changing the execution strategy on a fixed query

The controlled comparisons are most informative when they change a specific feature and keep the query fixed. The execution-strategy experiment uses Projection Query 2, whose filters leave relatively little output. The authors compare coarse-grained and fine-grained parallelism on the CPU, dedicated GPU, and MIC. Coarse-grained execution is faster by a factor of 2.8 on the CPU. Fine-grained execution is faster by a factor of 148 on the GPU and 3.19 on the MIC. These are the factors the authors report for that strategy comparison.

This intervention changes more than the number of workers. It changes how they collectively discover the output positions, how many passes they make, and which work occurs together in a kernel. On the CPU, the extra phases of fine-grained execution carry overhead that the single-pass strategy can avoid. On the accelerators, the fine-grained variant creates enough parallel work to make much better use of the device in this comparison. Its method of assigning output positions also avoids coordination over a shared output counter. The experiment measures the net effect of these changes together.

The transfer tests put that strategy result in context. A configuration selected for another device comes with its thread settings, access pattern, and other choices as well as its strategy. The authors attribute the broad CPU-versus-accelerator result on Projection Query 1 mainly to the difference between single-pass and multi-pass execution. Transferring entire variants can reveal the practical cost of carrying all those choices over. The isolated strategy comparison helps identify a contributor without requiring the assumption that it explains every transfer result.

Changing access order while preserving the result

The memory access comparison also uses Projection Query 2. On the CPU, the paper reports a factor of 1.6 in favor of sequential over coalesced access. The dedicated GPU favors coalesced access by a factor of 1.8. The authors report no significant difference on the MIC in that measurement. Each version still visits the required rows. The difference is the relationship between a worker’s current position and the positions visited by its neighbors.

The access result is narrower than a rule about the hardware alone. The tuned MIC variant for Projection Query 1 used sequential access, while the MIC configuration learned on the broader workload used coalesced access. Those observations apply to different queries and differently selected configurations. A memory pattern can have little visible effect in one controlled comparison and still be chosen in a workload search with different settings. The two observations give a reason to record the circumstances under which the setting was selected.

Comparing aggregation shapes and search outcomes

The two simple aggregation queries offer a comparison of grouping workloads. Summing by shipping mode drives updates into a relatively small set of groups. Summing by part key distributes updates across many more entries. Local aggregation addresses competition for hot entries by providing several partial tables, while global aggregation avoids a merge of the partial results. The timing comparisons across these queries show that accelerator-specific settings can be worth more for one aggregation workload than the other. The results also show that the integrated and dedicated GPUs can settle on the same configuration for the many-group case.

The grouping comparison changes the grouping attribute and its resulting distribution of keys. It therefore speaks to the behavior of those complete workloads. The paper does not report a controlled sweep of group count alone that would identify where local aggregation becomes less attractive. Nor do the learned configurations assign an independent speed contribution to Cuckoo hashing, linear probing, or the chosen hash function. Learning picks them in combination with the other decisions. The reported choice of local aggregation across the calibration workload and the per-query preference for global aggregation in some cases can coexist because they optimize for different scopes.

The branch results have a similar interpretation. The workload search selected branched execution across the shown device configurations, but the authors found that certain individual queries ran faster with predication. The branch choice changes both the conditional control flow and the way a failed row is prevented from contributing to the output. The generated predicated code gives a concrete account of why that can help when avoiding a branch matters. The workload comparison gives evidence about when Hawk chose it. It supplies no isolated timing series that would quantify the causal effect of predication across different filter selectivities. Loop unrolling likewise illustrates what the representation can express, without a separate speed measurement in these experiments.

The full-search comparisons reveal a different kind of gap. Feature-wise search can produce a relatively fast variant much sooner than backtracking, but it can leave a measurable distance to the fastest tested code, as the MIC results on Projection Query 1 and Aggregation Query 1 show. The per-query comparisons then show another source of distance. Even a configuration that serves its calibration workload well can be a poor fit for one query. Those are distinct questions for the optimizer. One concerns how thoroughly the space is searched for a given objective. The other concerns what the search is being asked to optimize.

Limitations

Limits identified by the authors

Hawk is a prototype for column-major, in-memory database engines. Its implemented operations cover the selections, projections, joins, and aggregations used in the evaluation, with restrictions. The paper gives the missing LIKE operator as a reason for selecting a subset of benchmark queries. Aggregation support is limited to distributive and algebraic functions, which can be combined from partial results or represented using a fixed set of component aggregates. The authors give median as an example of a holistic function outside the prototype’s support. The paper discusses applying the design to other column stores, with its implementation and evaluation based on CoGaDB.

The authors explicitly describe the learned configuration as a heuristic for a workload. The settings can depend on the query, including its useful degree of parallelism, branch mode, and hash table. The search can also stop at a local optimum, where none of the single-dimension changes it tests improves the configuration. A different combination could run faster. Because compiling and running each candidate is costly, exhaustive search is itself difficult to use as the routine decision procedure. The timing comparison measures the practical value of accepting a smaller search, with the quality of the selected configuration examined separately.

The MIC posed two problems in the evaluation. Its compilation could be much slower than that of the other devices, and execution times of some variants varied by up to a factor of four. The authors could not identify the exact cause of the execution variability. They suggest an artifact of Intel’s OpenCL SDK, based on seeing the behavior on the MIC and observing different behavior with other vendor and processor combinations. They used outlier detection to mitigate its effect on timing. As performance becomes less repeatable, a search based on measured execution has more difficulty distinguishing nearby candidates, even if its strategy for proposing them stays the same.

Limits of the experimental setup

The execution experiments isolate code performance with input data already on devices that have dedicated memory. They therefore give evidence for cases where data are resident and where an application can benefit from the measured kernel throughput. A query path that must bring inputs across PCIe, move intermediate data, or include compilation in response time has additional costs. The full-query comparison with HyPer is also explicitly scoped to execution timings on the CPU. The paper gives separate compilation results, which helps explain the sources of cost but does not establish an end-to-end latency comparison between the database systems.

Scale and selection affect how the results can be generalized. Full exploration uses scale factor 1, whereas the workload-tuned results are reported at scale factor 10. The evaluation uses pruning to keep extremely slow candidates from dominating exploration time. A full-search winner is consequently best understood as the fastest measured variant under that procedure, for that workload, device, and candidate space. It says nothing by itself about implementations outside that space. In particular, the discussion of loop unrolling and SIMD shows possible extensions of the compiler representation, with the main timing comparisons centered on the settings explicitly listed in the experimental design.

The workload experiment uses benchmark query groups to derive its configurations and then reports timings for selected queries from those benchmarks. It does not establish the accuracy of those settings on a separately described held-out workload. It also does not measure how stable a configuration would be across a change in data distributions, SDK behavior, or hardware generations. The generality shown by the experiments is the capacity to generate and calibrate code for different kinds of processors. The evidence for any particular choice of parameters applies to the measured setups.

There are also inconsistencies in how some measurements are identified. The design and the full-search plots identify the SSB join example as Q4.1, while the compilation discussion labels the complex SSB query Q4.3. The paper gives the very selective Projection Query 2 as below 0.01 % in the design and below 0.001 % in the results discussion. Both descriptions support treating it as a query with very little output, while the exact threshold is reported inconsistently. These ambiguities matter if selecting a value for an exact replication. The directly labeled TPC-H Q1 compilation measurements and the scale factor 10 execution table provide clearer grounds for comparisons involving those queries.

What came after

The paper leaves runtime selection as future work. Its proposed extension is an optimizer that can refine the workload configuration for the query being executed. The measured gap for TPC-H Q5 on the dedicated GPU supplies a concrete reason to investigate that extension. A device-wide choice had already captured the broad advantage of tailoring code to the GPU, while a query-specific choice still changed the execution time substantially. The authors point to earlier work on micro-adaptivity and progressive optimization as precedents for making decisions during execution.

There is no documented follow-up to attribute to a later paper here. The direction established by Hawk itself is a compiler that can generate compatible alternatives before any runtime selector is added. Its workload search demonstrates how those alternatives can be calibrated in advance. The open question it identifies is when a query’s behavior warrants paying for a more specific decision and how to make that decision while the query is running.

Cite

Cite as Sebastian Breß, Bastian Kocher, Henning Funke, Tilmann Rabl and Volker Markl. 2017. Generating Custom Code for Efficient Query Execution on Heterogeneous Processors. arXiv:1709.00700.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.48550/arxiv.1709.00700 · arXiv 1709.00700

@misc{bress2017generating,
  title = {{Generating Custom Code for Efficient Query Execution on Heterogeneous Processors}},
  author = {Sebastian Bress, Bastian Kocher, Henning Funke, Tilmann Rabl and Volker Markl},
  year = {2017},
  doi = {10.48550/arxiv.1709.00700},
  eprint = {1709.00700},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.1709.00700}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/bre-2017-ss-generating-custom-code-efficient-query/