Skip to content

[SPARK-2054][SQL] Code Generation for Expression Evaluation - #993

Closed
marmbrus wants to merge 36 commits into
apache:masterfrom
marmbrus:newCodeGen
Closed

marmbrus wants to merge 36 commits into
apache:masterfrom
marmbrus:newCodeGen

Conversation

@marmbrus

@marmbrus marmbrus commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

Adds a new method for evaluating expressions using code that is generated though Scala reflection. This functionality is configured by the SQLConf option spark.sql.codegen and is currently turned off by default.

Evaluation can be done in several specialized ways:

  • Projection - Given an input row, produce a new row from a set of expressions that define each column in terms of the input row. This can either produce a new Row object or perform the projection in-place on an existing Row (MutableProjection).
  • Ordering - Compares two rows based on a list of SortOrder expressions
  • Condition - Returns true or false given an input row.

For each of the above operations there is both a Generated and Interpreted version. When generation for a given expression type is undefined, the code generator falls back on calling the eval function of the expression class. Even without custom code, there is still a potential speed up, as loops are unrolled and code can still be inlined by JIT.

This PR also contains a new type of Aggregation operator, GeneratedAggregate, that performs aggregation by using generated Projection code. Currently the required expression rewriting only works for simple aggregations like SUM and COUNT. This functionality will be extended in a future PR.

This PR also performs several clean ups that simplified the implementation:

  • The notion of Binding all expressions in a tree automatically before query execution has been removed. Instead it is the responsibly of an operator to provide the input schema when creating one of the specialized evaluators defined above. In cases when the standard eval method is going to be called, binding can still be done manually using BindReferences. There are a few reasons for this change: First, there were many operators where it just didn't work before. For example, operators with more than one child, and operators like aggregation that do significant rewriting of the expression. Second, the semantics of equality with BoundReferences are broken. Specifically, we have had a few bugs where partitioning breaks because of the binding.
  • A copy of the current SQLContext is automatically propagated to all SparkPlan nodes by the query planner. Before this was done ad-hoc for the nodes that needed this. However, this required a lot of boilerplate as one had to always remember to make it @transient and also had to modify the otherCopyArgs.

@AmplabJenkins

Copy link
Copy Markdown

Merged build triggered.

@rxin

rxin commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

One more to do is maven build ...

@concretevitamin

Copy link
Copy Markdown
Contributor

Another TODO might be to beef up IN's code gen semantics (recall "NULL in NULL" and the alike cases).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe add some scaladoc to explain how this is used?

@AmplabJenkins

Copy link
Copy Markdown

Merged build started.

@AmplabJenkins

Copy link
Copy Markdown

Merged build finished.

@AmplabJenkins

Copy link
Copy Markdown

Refer to this link for build results: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/15499/

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be filled in?

@hsaputra

hsaputra commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

HI @marmbrus, one general comment about the PR, could you kindly add object or class header comment to describe why each of them needed and the context why they are used.
It should be very useful for people trying to use and help to improve and fix issues in the module later.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be helpful to add class header comment to describe the usage of this class in bigger context.

@AmplabJenkins

Copy link
Copy Markdown

Build triggered.

@AmplabJenkins

Copy link
Copy Markdown

Merged build triggered.

@AmplabJenkins

Copy link
Copy Markdown

Merged build started.

@SparkQA

SparkQA commented Jul 27, 2014

Copy link
Copy Markdown

QA tests have started for PR 993. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17252/consoleFull

@SparkQA

SparkQA commented Jul 27, 2014

Copy link
Copy Markdown

QA results for PR 993:
- This patch PASSES unit tests.

For more information see test ouptut:
https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17251/consoleFull

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Collected all Spark SQL configurations properties in object SQLConf in the JDBC Thrift server PR. We can put this one there too.

Conflicts:
	sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/commands.scala
@SparkQA

SparkQA commented Jul 28, 2014

Copy link
Copy Markdown

QA tests have started for PR 993. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17295/consoleFull

marmbrus added 2 commits July 29, 2014 13:26
Conflicts:
	project/SparkBuild.scala
	sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/commands.scala
@SparkQA

SparkQA commented Jul 29, 2014

Copy link
Copy Markdown

QA tests have started for PR 993. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17376/consoleFull

marmbrus added 2 commits July 29, 2014 18:13
Conflicts:
	sql/core/src/main/scala/org/apache/spark/sql/SQLConf.scala
	sql/core/src/main/scala/org/apache/spark/sql/SQLContext.scala
	sql/core/src/main/scala/org/apache/spark/sql/execution/SparkPlan.scala
	sql/core/src/main/scala/org/apache/spark/sql/execution/SparkStrategies.scala
	sql/hive/src/test/scala/org/apache/spark/sql/hive/execution/HiveQuerySuite.scala
Conflicts:
	sql/hive/src/test/scala/org/apache/spark/sql/hive/execution/HiveQuerySuite.scala
@marmbrus

Copy link
Copy Markdown
Contributor Author

test this please

@SparkQA

SparkQA commented Jul 30, 2014

Copy link
Copy Markdown

QA tests have started for PR 993. This patch merges cleanly.
View progress: https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/17402/consoleFull

@marmbrus

Copy link
Copy Markdown
Contributor Author

Thanks for looking at this everyone. I've merged it into master!

@asfgit asfgit closed this in 8446746 Jul 30, 2014
@ueshin

ueshin commented Jul 30, 2014

Copy link
Copy Markdown
Member

Hi @marmbrus, thanks for great work!
But it seems to break build.

I got the following result when I run sbt assembly or sbt publish-local:

[error] (catalyst/compile:doc) Scaladoc generation failed

and I found a lot of error messages in the build log saying value q is not a member of StringContext.

@marmbrus

Copy link
Copy Markdown
Contributor Author

@ueshin thanks for reporting. I've opened #1653 to fix this.

@marmbrus

Copy link
Copy Markdown
Contributor Author

@ueshin this should be fixed in master. Please let me know if you have any other problems.

@marmbrus
marmbrus deleted the newCodeGen branch August 27, 2014 20:46
xiliu82 pushed a commit to xiliu82/spark that referenced this pull request Sep 4, 2014
Adds a new method for evaluating expressions using code that is generated though Scala reflection.  This functionality is configured by the SQLConf option `spark.sql.codegen` and is currently turned off by default.

Evaluation can be done in several specialized ways:
 - *Projection* - Given an input row, produce a new row from a set of expressions that define each column in terms of the input row.  This can either produce a new Row object or perform the projection in-place on an existing Row (MutableProjection).
 - *Ordering* - Compares two rows based on a list of `SortOrder` expressions
 - *Condition* - Returns `true` or `false` given an input row.

For each of the above operations there is both a Generated and Interpreted version.  When generation for a given expression type is undefined, the code generator falls back on calling the `eval` function of the expression class.  Even without custom code, there is still a potential speed up, as loops are unrolled and code can still be inlined by JIT.

This PR also contains a new type of Aggregation operator, `GeneratedAggregate`, that performs aggregation by using generated `Projection` code.  Currently the required expression rewriting only works for simple aggregations like `SUM` and `COUNT`.  This functionality will be extended in a future PR.

This PR also performs several clean ups that simplified the implementation:
 - The notion of `Binding` all expressions in a tree automatically before query execution has been removed.  Instead it is the responsibly of an operator to provide the input schema when creating one of the specialized evaluators defined above.  In cases when the standard eval method is going to be called, binding can still be done manually using `BindReferences`.  There are a few reasons for this change:  First, there were many operators where it just didn't work before.  For example, operators with more than one child, and operators like aggregation that do significant rewriting of the expression. Second, the semantics of equality with `BoundReferences` are broken.  Specifically, we have had a few bugs where partitioning breaks because of the binding.
 - A copy of the current `SQLContext` is automatically propagated to all `SparkPlan` nodes by the query planner.  Before this was done ad-hoc for the nodes that needed this.  However, this required a lot of boilerplate as one had to always remember to make it `transient` and also had to modify the `otherCopyArgs`.

Author: Michael Armbrust <michael@databricks.com>

Closes apache#993 from marmbrus/newCodeGen and squashes the following commits:

96ef82c [Michael Armbrust] Merge remote-tracking branch 'apache/master' into newCodeGen
f34122d [Michael Armbrust] Merge remote-tracking branch 'apache/master' into newCodeGen
67b1c48 [Michael Armbrust] Use conf variable in SQLConf object
4bdc42c [Michael Armbrust] Merge remote-tracking branch 'origin/master' into newCodeGen
41a40c9 [Michael Armbrust] Merge remote-tracking branch 'origin/master' into newCodeGen
de22aac [Michael Armbrust] Merge remote-tracking branch 'origin/master' into newCodeGen
fed3634 [Michael Armbrust] Inspectors are not serializable.
ef8d42b [Michael Armbrust] comments
533fdfd [Michael Armbrust] More logging of expression rewriting for GeneratedAggregate.
3cd773e [Michael Armbrust] Allow codegen for Generate.
64b2ee1 [Michael Armbrust] Implement copy
3587460 [Michael Armbrust] Drop unused string builder function.
9cce346 [Michael Armbrust] Merge remote-tracking branch 'origin/master' into newCodeGen
1a61293 [Michael Armbrust] Address review comments.
0672e8a [Michael Armbrust] Address comments.
1ec2d6e [Michael Armbrust] Address comments
033abc6 [Michael Armbrust] off by default
4771fab [Michael Armbrust] Docs, more test coverage.
d30fee2 [Michael Armbrust] Merge remote-tracking branch 'origin/master' into newCodeGen
d2ad5c5 [Michael Armbrust] Refactor putting SQLContext into SparkPlan. Fix ordering, other test cases.
be2cd6b [Michael Armbrust] WIP: Remove old method for reference binding, more work on configuration.
bc88ecd [Michael Armbrust] Style
6cc97ca [Michael Armbrust] Merge remote-tracking branch 'origin/master' into newCodeGen
4220f1e [Michael Armbrust] Better config, docs, etc.
ca6cc6b [Michael Armbrust] WIP
9d67d85 [Michael Armbrust] Fix hive planner
fc522d5 [Michael Armbrust] Hook generated aggregation in to the planner.
e742640 [Michael Armbrust] Remove unneeded changes and code.
675e679 [Michael Armbrust] Upgrade paradise.
0093376 [Michael Armbrust] Comment / indenting cleanup.
d81f998 [Michael Armbrust] include schema for binding.
0e889e8 [Michael Armbrust] Use typeOf instead tq
f623ffd [Michael Armbrust] Quiet logging from test suite.
efad14f [Michael Armbrust] Remove some half finished functions.
92e74a4 [Michael Armbrust] add overrides
a2b5408 [Michael Armbrust] WIP: Code generation with scala reflection.
wangyum pushed a commit that referenced this pull request May 26, 2023
…hole plan exchange and subquery reuse (#993)

* [CARMEL-6055] Backport [SPARK-29375][SPARK-35855][SPARK-28940][SPARK-32041][SQL] Whole plan exchange and subquery reuse

* fix ut

* fix ut

* fix ut

* fix ut

* fix ut
udaynpusa pushed a commit to mapr/spark that referenced this pull request Jan 30, 2024
…mory from config to overwrite the SPARK_DAEMON_MEMORY (apache#993)

Co-authored-by: Tetiana Fioshkina <tetiana.fioshkina@hpe.com>
mapr-devops pushed a commit to mapr/spark that referenced this pull request May 8, 2025
…mory from config to overwrite the SPARK_DAEMON_MEMORY (apache#993)

Co-authored-by: Tetiana Fioshkina <tetiana.fioshkina@hpe.com>
MaxGekk added a commit to MaxGekk/spark that referenced this pull request Oct 23, 2026
…he narrow checks exhaustive (apache#993)

Stacked on apache#992: until that merges, this diff includes its commit (`48ef48c3e79`). The changes of this pull request are `aac6aa92680`, `de8cc490d35` and `d49f1d98ed9`.

### What changes were proposed in this pull request?

Two maximum-effort code reviews of the `TINYINT`/`SMALLINT` pull requests (apache#987, the narrow lanes, and apache#989, their arithmetic) found the narrow lanes' bookkeeping resting on rules nothing enforced. apache#992 fixed the findings in the test harness and the option matrix. This pull request fixes the ones in the engine that move no existing emitted byte. The ones that do move bytes come next, together with making the native narrow arm the default, so the generated files move once.

- **The warm-up now covers the species widened kernels actually run at.** On the default (widened) arm, a narrow column is not loaded at the preferred byte or short species. It is loaded at the species `Lane.widenLanes` names for the int width, for example a 64-bit byte vector where the preferred one is 256 bits, and converted to int in parts. The template warm-up only exercised the preferred species, so the per-class methods of the widened ones went unwarmed until the first real query hit them. The reach gate missed it because it modelled every narrow receiver as the preferred class. The gate now also models the widened species, and the warm-up has one block per narrow type at that species: masked and unmasked loads, conversion of every part, narrowing back, stores, compare, blend and mask calls. The `neg()` and `abs()` calls no kernel makes are removed, and the narrow `VectorMask.fromLong` that a masked guard collect calls is now warmed.
- **Switches over the IR are exhaustive.** `isNarrowRing`, the two walks that decide whether a kernel needs a narrow species and what refuses it, and the guard oracle's lane bounds used a `default` arm or an `instanceof` ladder over the sealed IR. A new narrow node would have fallen silently into the wrong answer in each. They are now exhaustive switches with no default, and the two walks sit side by side in `VarkaVectorIR`.
- **An output's width is checked where a projection is built.** The width the emitter stores and the Spark type's width came from two sources nobody compared; a mismatch would write past a narrower Arrow vector with no error. `CompiledVarkaProjection` now rejects it.
- **A false proof is removed.** `narrow_range.smt2` proved a checked byte multiply in a 16-bit lane, which the emitter never uses: a checked narrow multiply is computed in the int lane on both arms, which the file's other checks already prove. The lane width is now read from `Lane.INT`.
- **`CAST(tinyint AS INT)` is a relabel.** The cast the type coercion inserts emits nothing (the narrow column's widening load already produces the int), so it no longer counts as a use of the int-arithmetic family switch, as a `TIME` precision cast doesn't. `VarkaFamily`'s text names it. Four coverage rows compare the cast with Spark, and the census marks byte and short to int as fused.
- **Better fixtures.** The differential fixtures gain a narrow pair that is null on the left only. The fixture meant to have no nulls loses the narrow NULLs it had. `SMALLINT` values are adjusted so the equality rows (`s1 = 5S`, `s1 = i`) match at least one row, where before they compared false on every row.
- **Small cleanups.** `runAndCompareMixedStatus` moves back to where it was, two unused Scala forwarders go, and `WALKTHROUGH.md` shows the IR and shape hash the current tree prints.

Not fixed here: when a kernel at four int lanes reads a byte and a short column together, the short column is loaded at 128 bits and converted in two parts, and the warm-up converts only the first part. That matters only on 128-bit hosts (Apple Silicon, Neoverse), and only for branches inside the conversion that C2 may fold anyway. The reach gate counts methods, not branches, so it cannot see this.

### Why are the changes needed?

On the default arm, every narrow kernel's first queries ran through Vector API methods the warm-up never compiled, which is the cold start the warm-up exists to prevent. The rest makes mistakes that would have been silent loud instead: a new IR node now fails to compile until each switch says what it does, a width mismatch fails when the projection is built instead of corrupting memory, the proof file proves only what the emitter does, and the fixtures can now catch a kernel that returns the wrong constant.

### Does this PR introduce _any_ user-facing change?

No. Emitted kernels are byte-for-byte unchanged except for the four new coverage rows; the warm-up does more work at startup.

### How was this patch tested?

- **Narrow and oracle suites:** `VarkaEmitterNarrowSuite`, `VarkaEmitterNarrowArithSuite`, `VarkaEmittedBytesSuite`, `VarkaWidthAuditSuite`, `VarkaWarmupReachSuite` and `VarkaVectorTemplateWarmupSuite` pass.
- **Coverage and differential suites:** `VarkaCoverageSuite` and `VarkaCoverageDifferentialSuite` pass; all 799 differential tests pass.
- **Regenerated files:** `coverage.json`, `width_audit.json`, `emitted_bytes.json` and `docs/sql-varka.md` were regenerated. In `emitted_bytes.json` only the four new rows and the aggregate option-arm digests moved.
- **Option matrix:** the four new rows read a narrow column beside an int value, so they run at the int lane and widen the narrow column at its load, which needs a baked int lane count. Under `validityByWidth=false` there is none and the compiler declines them, as it declines the other narrow rows there. Their nine differential tests get `fails` skip lines; the differential suite then passes in the matrix at the defaults (799 ok) and under `validityByWidth=false` (720 ok, 79 cancelled as expected, none failed).
- **Proofs:** every proof holds under z3 and cvc5.
- **Linters:** Error Prone, `lint-java`, `lint-scala` and the pre-commit hook pass.
- **Review:** an independent reviewer read the diff. Its finding (the `s1 = i` row matched nothing) is fixed, and its performance note is listed above.

### Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code (Opus 5.5)
MaxGekk added a commit to MaxGekk/spark that referenced this pull request Oct 23, 2026
…on and abs as one op (apache#995)

apache#992 and apache#993, which this was stacked on, have merged; master is merged in, and the diff against master is exactly the change (`03862a58f27`, plus the record of the owner's decision to keep the SMALLINT slices always on).

### What changes were proposed in this pull request?

`TINYINT` and `SMALLINT` kernels can be emitted two ways. The widened arm loads a narrow column into the int lane and computes in ints; the native arm computes in `ByteVector`/`ShortVector` directly. The native arm was faster on every measured all-narrow shape, 2x to 16x depending on vector width, but the widened arm was the default. This pull request makes the native arm the default, and fixes the emission findings of the reviews of apache#987 and apache#989 that change emitted bytes, so the generated files move once.

- **The lane is decided once per kernel.** The compiler, the budget check, the emitter and the compiled projection each read a kernel's lane from its first output. Under the native default that would have split `SELECT y1 + y2, i + 1`: the first entry native at the byte lane, the second at the int lane, so the second went back to Spark's row engine. `VarkaVectorIR.kernelLane` now gives one lane for all the roots: their own where they agree, the int lane where they differ and none is bigint (every narrow tree also has the widened lowering), and none where a bigint root meets another. All four consumers read it. If joining an entry would move a native kernel to the int lane at a width that cannot widen, that entry is demoted with a reason that says so.
- **The native arm is the default.** `narrowLanes` ships true. The widened arm stays as an option the option matrix runs, as `narrowLanes=false`.
- **Narrow negation is one `NEG`.** It was a multiply by -1, and x86 has no byte multiply, so it became an eight-instruction sequence. The int and long lanes keep the multiply until it is measured (row 482).
- **Narrow `abs` is one `ABS`.** It was compiled as `IfElse(x < 0, -x, x)`: a compare, a negation and a blend, and the root lost the all-null shortcut. It is now the negation node with an `abs` flag, since the two have the same single overflowing input and the same check. At the int lane a wrapping `abs` reduces its own result, because `abs` does not commute with the narrow wrap (`abs(-128)` and `abs(128)` differ).
- **A narrow `CASE` reduces once.** On the int lane, a wrapping narrow chain is reduced to its width only where a reader needs the exact value. A blend only picks lanes, so a narrow pick now passes its arms' unreduced values through and reduces once, instead of once in each arm.
- **One truncation helper.** Narrowing an int value to `TINYINT`/`SMALLINT` away from a store now uses the same shift pair as the wrap, not a round trip through the narrow species.
- **Grouping weights** count the shift pair a wrapping narrow node may emit.

### Why are the changes needed?

The native arm is the faster one on every measured all-narrow shape, but nothing used it unless a test asked for it. Making it the default without the per-kernel lane would have sent mixed projections back to the row engine. The negation and `abs` changes remove an emulated byte multiply and a three-op composition from every narrow negation and `abs`. The narrow `CASE` and truncation changes remove duplicate reductions and a second lowering of one operation.

### Does this PR introduce _any_ user-facing change?

Faster queries over `TINYINT` and `SMALLINT` columns where every value is narrow. Answers are unchanged.

### How was this patch tested?

- **Emitted bytes:** `emitted_bytes.json` moved only for the 34 narrow coverage rows at each width and the aggregate option-arm digests that include them. No non-narrow row moved.
- **New tests:**
  - A kernel of a byte sum, a short `abs` and an int sum runs on both arms against the reference.
  - The `kernelLane` answers are pinned.
  - The LEGACY chain test gains two pick shapes, a chain picked by a `CASE` and the same under `abs`. They are LEGACY only, since Spark evaluates a `CASE` branch only on the rows the condition picks.
- **Tests pinned to the widened arm:** `VarkaEmitterNarrowArithSuite`'s width-rule test took the defaults to mean the widened arm, and now pins it.
- **Suites:** all `Varka*` suites in `catalyst` and `sql` pass (`sql`: 1281 ok, 0 failed).
- **Option matrix,** ok / cancelled, nothing failed or unfused:

  | configuration | catalyst (narrow, arithmetic, family, coverage, width audit, bytes) | `VarkaCoverageDifferentialSuite` |
  | :-- | --: | --: |
  | defaults (now native) | 63 / 20 | 799 / 0 |
  | `narrowLanes=false` | 63 / 20 | 799 / 0 |
  | `lanesOverride=4` | 63 / 20 | 799 / 0 |
  | `validityByWidth=false` | 32 / 51 | 772 / 27 |

  Under `validityByWidth=false` the native arm needs no baked lane count, so 52 skip lines went stale and are removed. The rows still declining there are the checked multiplies, which always run at the int lane, and rows that read a narrow column beside an int value.
- **Benchmark** (`results/VARKA-329-negabs.txt`, laptop, before and after, with two new shapes in `VarkaNarrowEmitBenchmark`):
  - On the native arm, a byte negation and `abs` run 3.0x to 3.4x faster in L1 at 512 and 256 bits, 2.1x to 2.4x at 512 KB, and 1.15x to 1.26x at 2 MB, where the store is memory bound.
  - On the widened arm, `abs` gains 1.43x to 1.48x and negation 1.06x to 1.13x.
  - The control shape is unchanged, and no cell is slower.
- **Warm-up:** the reach gate passes with `NEG` and `ABS` warmed at the native and widened species.
- **Linters:** Error Prone, `lint-java`, `lint-scala`, the plan linter and the pre-commit hook pass.
- **Review:** an independent reviewer found no correctness bug. It noted three things that are by design or belong to rows:
  - an entry demoted for joining is not retried in a kernel of its own (row 480);
  - an int entry moves the kernel's native narrow entries to the widened lowering, the mixed shape the two arms tie on;
  - the IR fuzzers draw no narrow arithmetic, narrow `CASE` or `abs` (row 352).

### Was this patch authored or co-authored using generative AI tooling?

Generated-by: Claude Code (Opus 5.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants