≈ The Lake

Part 9 · Query execution · Chapter 32

Vectorized execution: from X100 to Photon

Why processing vectors of values beats tuple-at-a-time interpretation, how data-centric code generation does the same job differently, what the comparison between them found, and where Spark's whole-stage codegen and Databricks' Photon sit.

complete ~25 min

After this chapter you should be able to:
  • Explain where a Volcano-style interpreter spends its time.
  • Describe X100's vectors, primitives and selection vectors, and why vector size matters.
  • Describe produce/consume code generation and compare it with vectorization.
  • Place Spark's execution engine, and Photon's, on that map.

Chapter 31 put a Parquet column into memory as a batch. This chapter is about what an engine does next, and why there are two answers. One is to interpret over vectors of values. The other is to compile the query into a single loop. Spark took the second. Photon, in chapter 36, took the first.

The simulator in src/sim/spark/engines.ts runs SELECT sum(b) FROM t WHERE a < k three ways and counts the calls each one makes. The lab also times them in your browser.

The Volcano model and its costs

The classic execution model is the iterator, or Volcano, model. Each operator has open, next and close, and next() returns one tuple. A Filter calls its child’s next() until a row passes. An aggregate calls the Filter’s next() until it returns nothing. Expressions are trees evaluated per row. Spark’s non-codegen path has this shape. FilterExec.doExecute maps each partition’s row iterator through iter.filter(row => predicate.eval(row)), where the predicate comes from Predicate.create.[Spark FilterExec]

The model is clean and composable, but the CPU spends little of its time on the query’s actual work. Boncz, Zukowski and Nes profiled MySQL running TPC-H Q1. The five operations that do the work “correspond to only 10% of total execution time”. One addition through Item_func_plus::val cost 38 instructions, and “28% of execution time is taken up by creation and lookup in the hash-table used for aggregation”.[Boncz et al., CIDR 2005, Section 3] The rest is calls, interpretation and branches that the CPU cannot pipeline. The paper sums up the iterator model: it “leads to tuple-at-a-time execution, which causes both high interpretation overhead” and hides the parallelism a modern CPU could exploit.

Quiz Check: VolcanoAnswers are scheduled for spaced review on the Review page.

Q1. Where does a tuple-at-a-time interpreter spend its time on a simple filter-and-sum?

How sure are you?

MonetDB/X100

X100 keeps the iterator, but next() returns a vector: “Small (e.g. 1000 values) vertical chunks of cache-resident data items”. Vectors “are the unit of operation for X100 execution primitives”.[Boncz et al., CIDR 2005, Section 4] A primitive is a small function specialized for one operation and type, a tight loop over arrays with no per-value calls:

// select_lt_int_col_int_val: positions of values < val
int sel_lt(int n, int* res, int* col, int val) {
  int j = 0;
  for (int i = 0; i < n; i++) if (col[i] < val) res[j++] = i;
  return j;
}
// aggr_sum_dbl_col: sum over the selected positions
double sum_sel(int m, double* col, int* sel) {
  double s = 0;
  for (int j = 0; j < m; j++) s += col[sel[j]];
  return s;
}

A filter does not copy columns. The Select operator “creates a selection-vector, filled with positions of tuples”, and later primitives compute only at those positions.[Boncz et al., CIDR 2005, Section 4.1] The interpreter’s overhead is now one call per vector per primitive instead of several calls per row. The loops are simple enough for the compiler to unroll and pipeline.

Vector size is the trade-off. At size 1 the engine is a Volcano interpreter again. At very large sizes, the vectors and selection vectors no longer fit in the CPU caches between one primitive and the next, and every primitive streams from memory. In their later study, Kersten et al. used 1,000, “also the default in VectorWise”. They found that sizes under 64 and over 64K “decrease performance significantly”, and that “a vector size of 1,000 seems to be a good setting for all queries”.[Kersten et al., PVLDB 2018, Section 4.3] X100’s TPC-H Q1 ran in 0.50 s per CPU per scale factor on an AthlonMP, against 26.6 for MySQL 4.1. A hand-written C program took 0.22, and X100 “is able to get within a factor 2 of this hand-coded implementation”.[Boncz et al., CIDR 2005, Table 1]

Quiz Check: X100Answers are scheduled for spaced review on the Review page.

Q1. In X100, what does a Select primitive output?

How sure are you?

Q2. Why is a vector size around 1,000 a good default, rather than 1 or 1,000,000?

How sure are you?

Data-centric code generation

The other answer removes the interpreter altogether. Neumann’s HyPer compiles each pipeline into one loop. “Conceptually each operator offers two functions: produce() and consume(attributes, source)”. Produce asks an operator for its tuples, “which are then pushed towards the consuming operator by calling their consume functions”. The functions exist only during code generation.[Neumann, PVLDB 2011] The goal: “During query processing, all data should be kept in CPU registers as long as possible”. A pipeline runs from one pipeline breaker, an operator that takes tuples out of registers (to build a hash table, say), to the next. “Data is not pulled by operators but pushed towards the operators.”

For the filter-and-sum, the generated code is the loop you would write by hand:

for (int i = 0; i < n; i++) {
  if (a[i] < k) { sum += b[i]; }     // Filter.consume inlined into Scan.produce's loop,
}                                    // HashAggregate.consume inlined into Filter's

Spark’s WholeStageCodegenExec is this design. Its doc comment draws the same produce/consume call graph, CodegenSupport has produce, doProduce, consume and doConsume, and an operator that does not support codegen ends the stage through an InputAdapter.[Spark WholeStageCodegenExec][Spark CodegenSupport] Chapter 29 showed where the stage boundaries fall.

Quiz Check: code generationAnswers are scheduled for spaced review on the Review page.

Q1. In data-centric code generation (produce/consume), how does data move between operators in a pipeline?

How sure are you?

Codegen vs vectorization

Kersten, Leis, Kemper, Neumann, Pavlo and Boncz built two engines that differed only in this choice: Typer (compiled) and Tectorwise (vectorized). They ran both on TPC-H queries. Their abstract states the finding: “Vectorization is better at hiding cache miss latency, whereas data-centric compilation requires fewer CPU instructions, which benefits cache-resident workloads.”[Kersten et al., PVLDB 2018]

  • On Q1, an aggregation over computed expressions, Typer executed 68 instructions per tuple to Tectorwise’s 162, and was 74% faster. “Typer is more efficient for computational queries that can hold intermediate results in CPU registers”.
  • On the join-heavy Q3 and Q9, Tectorwise was faster, by 4% and 32%. A vectorized hash probe issues many independent memory accesses in one tight loop, so the CPU overlaps their cache misses. A fused loop interleaves each probe with the rest of the pipeline’s work.
  • The differences were moderate in both directions. The choice depends on more than speed: compile time, how easy the engine is to profile and debug, and how easily it can adapt at runtime.
Two ways to run the same filter and aggregation
Vectorized operators
  1. Filter a batch A tight loop builds a selection of matching positions.
  2. Aggregate selected values The next operator can process many independent values in one loop.
Fused code generation
  1. Compile filter and aggregate together One loop tests and aggregates each row.
  2. Keep intermediates close The fused loop can keep temporary values in registers.
Vectorized loops can overlap memory accesses. Fused code can reduce total instructions when the working set is cache-resident.[PVLDB 2018]
Quiz Check: the comparisonAnswers are scheduled for spaced review on the Review page.

Q1. What did Kersten et al. find when comparing a compiled engine (Typer) with a vectorized one (Tectorwise)? (Select all.) (select all that apply)

How sure are you?

SIMD

A primitive like sel_lt or a sum over an array is exactly what a compiler’s auto-vectorizer looks for: a counted loop over arrays with no calls. Kersten et al. measured what explicit SIMD adds. A selection micro-benchmark sped up 8.4×, but on a whole query (Q6) they “only observe a speedup of 1.4×”, because most time goes to memory access and other work.[Kersten et al., PVLDB 2018, Section 5.1] SIMD multiplies arithmetic throughput. It does not help much when the loop waits on memory.

Branches matter as much as SIMD. In sel_lt the if depends on data. At 1% or 99% selectivity the branch predictor is nearly always right. At 50% it is wrong about half the time, and each miss costs a pipeline flush. A branch-free version always writes the position and advances the output index by the comparison result (res[j] = i; j += (col[i] < val)). That does more work, but its cost does not depend on the data. The lab measures both across selectivities. Vectorized engines can keep both versions and choose between them at runtime from observed selectivity. A compiled engine has to decide when it generates code.

Quiz Check: branchesAnswers are scheduled for spaced review on the Review page.

Q1. Why can a branch-free selection primitive beat the branching one at 50% selectivity?

How sure are you?

Where Spark sits

Spark 4.0 is a data-centric compiler over a columnar scan. The vectorized Parquet reader fills ColumnarBatches (chapter 31). The first codegen stage starts with ColumnarToRowExec, whose generated loop reads one row index at a time through ColumnVector getters. Filter, Project and the partial aggregate are inlined into that loop. The generated Java is compiled with Janino and then JIT-compiled by the JVM. Spark does not use vectorized primitives in its own operators.

Two guards keep codegen from making things worse. If compilation fails and spark.sql.codegen.fallback is true (the default), the stage runs on the iterator path. If a generated method’s bytecode exceeds spark.sql.codegen.hugeMethodLimit (65535), Spark also falls back. The default is the largest valid Java method, and the setting’s documentation suggests a lower value on HotSpot to match HotSpot’s own limit for JIT compilation.[Spark WholeStageCodegenExec.doExecute][Spark SQLConf codegen]

Quiz Check: SparkAnswers are scheduled for spaced review on the Review page.

Q1. How does Spark 4.0 execute Filter → HashAggregate over a vectorized Parquet scan?

How sure are you?

Try it

The table has a, an int uniform in 0–99, and b, a double. The counters (calls per row, row objects, selection-vector bytes) come from the simulator and are exact. Press Run in this browser to time each engine and sweep the vector size. The times come from your browser’s JavaScript JIT, not from a database engine, so look at the shape, not the numbers.

  • Volcano makes 4 to 6 calls per row, more as selectivity rises, and one row object per row. The vectorized engine makes 3 calls per vector, and the fused loop makes none.
  • Sweep the vector size: size 1 is slow (one call triple per row), and the time flattens out once each call covers hundreds of values.
  • Compare branching and branch-free selection at a selectivity of 50% and then 1% or 99%.
SELECT sum(b) FROM t WHERE a < 50
Enginecalls / rowrow objectsselection vector writestime (median of 5)
Volcano (row at a time, interpreted)5.001,000,0000 KB–
Vectorized primitives0.002901955 KB–
Vectorized, branch-free select0.002901955 KB–
Fused loop (codegen)0.000000 KB–

All four return sum = 2499735.70 over 500,375 rows. Working set per vector: 1K × (4 B of a + 8 B of b + 4 B of selection) = 16 KB.

History

The iterator model is the Volcano model, which the X100 paper cites as the common way to pipeline execution. Peter Boncz, Marcin Zukowski and Niels Nes, at CWI Amsterdam, published “MonetDB/X100: Hyper-Pipelining Query Execution” at CIDR 2005.[CIDR 2005] Thomas Neumann published “Efficiently Compiling Efficient Query Plans for Modern Hardware” in PVLDB volume 4, issue 9, presented at VLDB 2011.[PVLDB 4(9)] Timo Kersten, Viktor Leis, Alfons Kemper, Thomas Neumann, Andrew Pavlo and Peter Boncz compared the two in PVLDB 11(13), 2018, pages 2209–2222.[PVLDB 11(13)]

Summary

  • Volcano’s next() per row and per-row expression trees make calls and branches dominate. In X100’s MySQL profile, the real work was 10% of Q1’s time.
  • X100 interprets over vectors of about 1,000 values. Primitives are tight, type-specialized loops, filters produce selection vectors, and overhead is per vector. Vectors must stay in cache, so sizes far below 64 or above 64K lose.
  • Data-centric compilation pushes tuples through the inlined code of a whole pipeline, keeping values in registers between pipeline breakers. Spark’s whole-stage codegen is this.
  • Compilation needs fewer instructions and wins on computation. Vectorization hides cache misses better and wins on large joins. Neither dominates.
  • SIMD helps arithmetic-bound loops much more than whole queries. At middling selectivities, branch mispredictions can cost more than the comparisons themselves.
  • Spark 4.0 compiles over columnar input and falls back to iterators when codegen fails or a method passes 64KB. Photon (chapter 36) is the vectorized alternative inside Databricks.

Concepts in this chapter

Explained here

See how the book's concepts connect →

Primary sources

Review this chapter

This chapter has 7 quiz questions.

Review this chapter's cards → Review all due cards