Skip to content

Partially reimplement Parquet encoder to make it faster and parallelizable#49367

Merged
Avogar merged 4 commits intomasterfrom
enc
Jul 26, 2023
Merged

Partially reimplement Parquet encoder to make it faster and parallelizable#49367
Avogar merged 4 commits intomasterfrom
enc

Conversation

@al13n321
Copy link
Copy Markdown
Member

@al13n321 al13n321 commented May 1, 2023

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Writing parquet files is 10x faster, it's multi-threaded now. Almost the same speed as reading.

@robot-ch-test-poll3
Copy link
Copy Markdown
Contributor

robot-ch-test-poll3 commented May 1, 2023

This is an automated comment for commit 5ee71bd with description of existing statuses. It's updated for the latest CI running
The full report is available here
The overall status of the commit is 🟢 success

Check nameDescriptionStatus
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help🟢 success
CI runningA meta-check that indicates the running CI. Normally, it's in success or pending state. The failed status indicates some problems with the PR🟢 success
ClickHouse build checkBuilds ClickHouse in various configurations for use in further steps. You have to fix the builds that fail. Build logs often has enough information to fix the error, but you might have to reproduce the failure locally. The cmake options can be found in the build log, grepping for cmake. Use these options and follow the general build process🟢 success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help🟢 success
Docker image for serversThe check to build and optionally push the mentioned image to docker hub🟢 success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here🟢 success
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integrational tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc🟢 success
Install packagesChecks that the built packages are installable in a clear environment🟢 success
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests🟢 success
Mergeable CheckChecks if all other necessary checks are successful🟢 success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests🟢 success
Push to DockerhubThe check for building and pushing the CI related docker images to docker hub🟢 success
SQLancerFuzzing tests that detect logical bugs with SQLancer tool🟢 success
SqllogicRun clickhouse on the sqllogic test set against sqlite and checks that all statements are passed🟢 success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc🟢 success
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc🟢 success
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors🟢 success
Style CheckRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report🟢 success
Unit testsRuns the unit tests for different release types🟢 success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts🟢 success

@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-performance Pull request with some performance improvements label May 1, 2023
@qoega
Copy link
Copy Markdown
Member

qoega commented May 1, 2023

generate random arbitrarily nested array/tuple/nullable

generaterandom table function should be enough to generate them

@al13n321 al13n321 force-pushed the enc branch 2 times, most recently from baf4741 to d6f82fa Compare May 2, 2023 07:42
@al13n321 al13n321 force-pushed the enc branch 4 times, most recently from cc32954 to c56fab3 Compare May 9, 2023 08:17
@robot-ch-test-poll4 robot-ch-test-poll4 added the submodule changed At least one submodule changed in this PR. label May 9, 2023
@al13n321 al13n321 marked this pull request as ready for review May 9, 2023 08:19
@robot-ch-test-poll2 robot-ch-test-poll2 removed the submodule changed At least one submodule changed in this PR. label May 9, 2023
@Avogar
Copy link
Copy Markdown
Member

Avogar commented May 11, 2023

generaterandom table function should be enough to generate them

In combination with generateRandomStructure from my PR will be even better (this PR is actually ready for review and hope will be merged soon)

@Avogar Avogar self-assigned this May 11, 2023
@al13n321
Copy link
Copy Markdown
Member Author

generaterandom table function should be enough to generate them

In combination with generateRandomStructure from my PR will be even better (this PR is actually ready for review and hope will be merged soon)

Would require #48625 too. (Otherwise Array(Nullable()) breaks without a temporary table (like arrays_out_02735), but wide integers (Int128 etc) break with temporary table (because parquet reinterprets them as FixedString, which the INSERT then tries to parse as text).)

@binmahone
Copy link
Copy Markdown
Contributor

binmahone commented May 16, 2023

hello @al13n321 , I'm testing single thread + custom encoding from this PR, but only to find that custom encoding turns out to be a little slower under single thread case. is it expected? here're my steps:

Firstly I guarantee single thread by commenting out the following code

        if (format_settings.parquet.parallel_encoding && format_settings.max_threads > 1)
            pool = std::make_unique<ThreadPool>(
                CurrentMetrics::ParquetEncoderThreads, CurrentMetrics::ParquetEncoderThreadsActive,
                format_settings.max_threads);

Then I use clickhouse-local to test custom encoding and arrow encoding respectively:

ws2 :) INSERT INTO TABLE Function file('/tmp/test_write8.parquet') select * from file('/data0/tpch100_zhichao/parquet/customer/part-00000-f36cbfed-be1f-4add-8033-cdf6240fb67a-c000.snappy.parquet') settings output_format_parquet_use_custom_encoder=1

INSERT INTO FUNCTION file('/tmp/test_write8.parquet')
SETTINGS output_format_parquet_use_custom_encoder = 1
SELECT *
FROM file('/data0/tpch100_zhichao/parquet/customer/part-00000-f36cbfed-be1f-4add-8033-cdf6240fb67a-c000.snappy.parquet')
SETTINGS output_format_parquet_use_custom_encoder = 1

Query id: e94b6ae5-b19b-40d5-9671-868bd88f3461

Ok.

0 rows in set. Elapsed: 1.019 sec. Processed 1.50 million rows, 324.30 MB (1.47 million rows/s., 318.13 MB/s.)

ws2 :) 
INSERT INTO TABLE Function file('/tmp/test_write9.parquet') select * from file('/data0/tpch100_zhichao/parquet/customer/part-00000-f36cbfed-be1f-4add-8033-cdf6240fb67a-c000.snappy.parquet') settings output_format_parquet_use_custom_encoder=0

INSERT INTO FUNCTION file('/tmp/test_write9.parquet')
SETTINGS output_format_parquet_use_custom_encoder = 0
SELECT *
FROM file('/data0/tpch100_zhichao/parquet/customer/part-00000-f36cbfed-be1f-4add-8033-cdf6240fb67a-c000.snappy.parquet')
SETTINGS output_format_parquet_use_custom_encoder = 0

Query id: 8ed9ecce-3935-47a4-9dc0-e343719e1d7f

Ok.

0 rows in set. Elapsed: 0.969 sec. Processed 1.50 million rows, 324.30 MB (1.55 million rows/s., 334.61 MB/s.)

The dataset I'm using is customer table from TPCH 100.

@al13n321 al13n321 force-pushed the enc branch 2 times, most recently from 320177b to 9b4deda Compare May 17, 2023 01:05
@al13n321
Copy link
Copy Markdown
Member Author

al13n321 commented May 17, 2023

Thanks for reporting!

Reproduced it, got a ~10% difference as well. Interestingly, file size was also ~7% bigger!

Turns out there was a difference in dictionary size limit logic between arrow and this PR: arrow re-checks the dictionary size every 1024 rows, while this PR only re-checked on every data page (~1 MB). So it would dictionary-encode more data before falling back to non-dictionary encoding.

Fixed. Now I'm getting a ~10% speed difference the other way around (custom faster than arrow), and file size is nearly identical.


If this makes a 7% difference in file size, would it get even better if the dictionary -> non-dictionary fallback discards dictionary-encoded data and starts over, instead of writing it out? I tried it and got 1.3% smaller file here, and 3.7% smaller hits.parquet, with little speed difference. Made the change.


Btw, CPU profiles: arrow encoder http://ec2-35-167-7-127.us-west-2.compute.amazonaws.com:8080/pr49367-arrow-encoder.svg , custom encoder http://ec2-35-167-7-127.us-west-2.compute.amazonaws.com:8080/pr49367-custom-encoder.svg

@binmahone
Copy link
Copy Markdown
Contributor

thank you @al13n321 for the quick and detailed response!

Can we conclude that, by eliminating the extra cost of arrow conversion, we can get a 10% performance improvement (in single thread scenario)? Can we expect a more significant improvement in the final version?

And, do you believe the performance gain will be bigger for "read parquet by custom decoder"?

@al13n321
Copy link
Copy Markdown
Member Author

al13n321 commented May 17, 2023

Can we conclude that, by eliminating the extra cost of arrow conversion, we can get a 10% performance improvement (in single thread scenario)?

I didn't particularly investigate where the savings come from and how big they are. But yeah, it would be my guess that the 10% is mostly from avoiding copying/conversion. Another suspect is statistics calculation: the arrow code for that looks less efficient than this PR. There's probably some insight to be gained from the CPU profiles in previous comment, if we were to optimize it more.

On hits.parquet (14 GB file downloaded from https://clickhouse-public-datasets.s3.amazonaws.com/hits_compatible/hits.parquet), I'm getting 14% improvement (still single-threaded): 570s -> 497s.

(Also, the 10%-14% is for total query time, some of which is spent on decoding the input file. On the TPCH file, decoding takes 1/3 of the total time, so encoding speed difference is more like 15%. Decoding is so slow there because the input file has only 2 row groups. On hits.parquet, presumably decoding is a much smaller fraction of the time, but I didn't check.)

Can we expect a more significant improvement in the final version?

I don't plan to optimize this further, unless it turns out someone actually needs it to go faster. I'd guess it's possible to gain maybe another 20%.

And, do you believe the performance gain will be bigger for "read parquet by custom decoder"?

Good question. Here's CPU profile for select sum(cityHash64(*)) from file('hits.parquet'): http://ec2-35-167-7-127.us-west-2.compute.amazonaws.com:8080/pr49367-read-hits.svg

  • Parquet takes 65% CPU time, the rest is mostly cityHash64.
  • Converting from arrow to CH takes 27% of that!
  • Strangely much time (>10%?) is spent on memcpy in buffer resizing. I wonder if it can be easily avoided.

So, seems that there's > 30% to be gained there!


(Here are some more CPU profiles, in case anyone just likes looking at them or something: http://ec2-35-167-7-127.us-west-2.compute.amazonaws.com:8080/pr49367-read-hits-1thread.svg , http://ec2-35-167-7-127.us-west-2.compute.amazonaws.com:8080/pr49367-read-tpch.svg , http://ec2-35-167-7-127.us-west-2.compute.amazonaws.com:8080/pr49367-read-tpch-1thread.svg )

@binmahone
Copy link
Copy Markdown
Contributor

thanks for the reply, really helps a lot.

we're working on "read parquet by custom decoder" and will come back to the community once we have some progress to share with you.

@al13n321
Copy link
Copy Markdown
Member Author

thanks for the reply, really helps a lot.

we're working on "read parquet by custom decoder" and will come back to the community once we have some progress to share with you.

@liuneng1994 said the same in #49539 (comment) . You guys are working together, right? If not, make sure to coordinate :)

@al13n321 al13n321 force-pushed the enc branch 2 times, most recently from b5b423f to af1c9ee Compare May 19, 2023 04:03
@binmahone
Copy link
Copy Markdown
Contributor

thanks for the reply, really helps a lot.
we're working on "read parquet by custom decoder" and will come back to the community once we have some progress to share with you.

@liuneng1994 said the same in #49539 (comment) . You guys are working together, right? If not, make sure to coordinate :)

we do work together 👍

@robot-ch-test-poll3 robot-ch-test-poll3 added the submodule changed At least one submodule changed in this PR. label May 30, 2023
@al13n321
Copy link
Copy Markdown
Member Author

al13n321 commented Jun 2, 2023

Compiler crash in CI, doesn't reproduce locally (although maybe my flags are slightly off, have to try some more), oh boy this is going to take some investigating.

@alexey-milovidov
Copy link
Copy Markdown
Member

This is a very good change, we need it!

@al13n321
Copy link
Copy Markdown
Member Author

Sent LLVM bug report: llvm/llvm-project#63630

@alexey-milovidov
Copy link
Copy Markdown
Member

The compiler does not crash anymore, but the fuzzer has found bugs.

@al13n321 al13n321 force-pushed the enc branch 2 times, most recently from b680870 to dc23d5c Compare July 18, 2023 09:27
@alexey-milovidov
Copy link
Copy Markdown
Member

The compiler continued crashing. Let's workaround it.

@al13n321
Copy link
Copy Markdown
Member Author

From the LLVM IR dump (that people in llvm/llvm-project#63630 taught me to obtain), looks like the problem is in vectorization of this loop (for Int8 type):

for (size_t i = 0; i < data_count; ++i)
    page_statistics.add(converted[i]);

Added a pragma to disable vectorization for it if MSAN is enabled.

Copy link
Copy Markdown
Member

@Avogar Avogar left a comment

Choose a reason for hiding this comment

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

Looks great, let's merge! Although I didn't get into all internals (otherwise it will require a lot of time for me to understand).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-performance Pull request with some performance improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants