Skip to content

ZUNIONSTORE performance change - #1786

Closed
kjmph wants to merge 4 commits into
redis:unstablefrom
Simulmedia:unstable
Closed

kjmph wants to merge 4 commits into
redis:unstablefrom
Simulmedia:unstable

Conversation

@kjmph

@kjmph kjmph commented May 30, 2014

Copy link
Copy Markdown

When attempting to union many keys, ZUNIONSTORE was taking 14s. With these modifications, it is down to ~200ms. However, I guarantee I don't understand how refcnts are used in Redis. The reason I need refcnts is because when aggregating, I use the destination ZSET as the accumulated aggregate. Then, because ZSETs sort on insert, I need to sort the destination. I did so by creating a new ZSET and inserting all the values/scores into it. The method described here is more cache friendly by iterating through each key, rather than scanning forward through all keys for the aggregate. It also visits each value once, rather than multiple times.

kjmph added 2 commits May 30, 2014 14:16
This is an experimental commit. Likely it causes a memory
leak. However, ZUNIONSTORE benefits from performance
improvements. Initial tests on ~70k keys went from 14s to ~200ms.
Attempt to document some of my thinking in comments. I'm sure this
should be fixed before the pull request goes through.
@kjmph

kjmph commented May 30, 2014

Copy link
Copy Markdown
Author

Our use case is centered around unique keys, I misunderstood the use case for listing the same key multiple times. I'll fix that and reissue the pull request.

kjmph added 2 commits May 30, 2014 21:50
When passing in duplicate keys to ZUNIONSTORE, it is expected their
aggregates count as many times as they are present.
zunionCloneAndFree is a new function which does as it says. It will
clone a ZSET and free the old copy. This is good for resorting a ZSET
in case it's values were directly modified.
@mattsta

mattsta commented Jun 4, 2014

Copy link
Copy Markdown
Contributor

Some quick notes:

  • I squashed your commits for easier reading at mattsta@60550c0
  • If I remove the call to zunionCloneAndFree(), everything still tests okay.
    • potential optimization: If we never enter the if (de) case, we don't need to zunionCloneAndFree()
    • we need better test cases to cover replacing elements versus adding elements
  • For clarity, I'd recommend replacing the if (de)/continue with if/else.
  • Your comment about Note, incrementing refcnts on a struct in the stack? is correct — you should be incrRefCount(tmp), not your locally allocated struct since you're inserting tmp into tdstzset->zsl and tdstzset->dict.

Add some tests to tests/unit/type/zset.tcl to catch usage of zunionCloneAndFree() and we can check again! You can run just that test module with:

./runtest --single unit/type/zset

@kjmph

kjmph commented Jun 4, 2014

Copy link
Copy Markdown
Author

Thanks for your feedback.

  • Thanks for squashing
  • Tests still pass because there doesn't appear to be a test that will throw error if the result of a ZUNIONSTORE is unsorted.
    • Good catch.
    • Replacing elements? Do you mean calculating aggregate values?
  • Ah, ok, I'm used to the continue style. It looks odd to me to use if/else. I'll change it though.
  • I spent some time reading the refcount usage. Actually, zval.ele is a pointer to the robj *. So, it was the iterator style that I didn't expect. I'll update the commentary. Also of note, the incrRefCount(zval.ele) pre-existed the code in this pull request. I would prefer to either change in both places, or not. Feedback?

I'll add the new test. Time to dust off my TCL.

@mattsta

mattsta commented Jun 4, 2014

Copy link
Copy Markdown
Contributor

Yeah, you're right about my mistaking replacing for updating aggregate values.

The existing Redis zunion tests are actually enforcing order checking. I think the test cases just don't have a case where the union is a different order than the original values after multiple updates. Maybe test with negative weights or negative scores on some elements so the order of the union isn't the order of the traversal to create it?

I see what you mean about zval.ele now. tmp actually equals zval.ele, so everybody is right! The zintersect branch increases on tmp, but the zunion branch increases on zval.ele. For consistency, I'd recommend increasing only on tmp, because we shouldn't be grabbing values inside the structure itself (that's what zuiObjectFromValue is for).

Thanks for getting all this sorted!

@michael-grunder

Copy link
Copy Markdown
Contributor

I'll run this on various bits of live data we have and paste the performance differences I encounter here. If this increase in speed can be replicated generically, I need it in my life. 😄

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

Thanks @michael-grunder! Waiting for the benchmarks :-) 👍

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

p.s. sorry reading the full thread only now, I'll start reviewing the patch and comments more closely to check if I can find some semantical issue here. 14 s -> 200 ms is a huge step forward... even if it happens only for special use cases.

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

Update. I'm trying to rewrite the code in a simpler way, but guaranteeing that the aggregation is performed with the same logic and cache-friendly way. This is the script I'm using to test:

require 'rubygems'
require 'redis'

MaxElements = 10000
Keys = 10
Sampling = 10

r = Redis.new
r.flushall
keys = []
(0..Keys).each{|i|
    key = "zset:#{i}"
    puts "Creating #{key}"
    keys << key
    r.multi {
        rand(MaxElements).times {
            r.zadd(key,i,"ele:#{rand(MaxElements)}")
        }
    }
}

start = Time.now
Sampling.times {puts r.zunionstore(:dstkey,keys)}
puts "Elapsed: #{(Time.now-start).to_f/Sampling} seconds."

The problem is, with the above script, I'm not able to replicate the big speed difference between the two implementations. Please could @kjmph provide some details about the key / zset layout so that I can use it as a testbed to check if my new implementation performs as fast as needed?

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

Nevermind... just adding more keys trashes even more the access schema of the original implementation, and now I can see a very big difference in performances.

@michael-grunder

Copy link
Copy Markdown
Contributor

Hey guys,

I ran some benchmarks from production data we're using of three different types, with various set counts.

The three types are as follows:

  • Horrible data, huge sets, almost entirely unique values (this data is the devil)
  • Better data, big sets but lots of sets share members
  • Good data, big sets but only a small number of shared members

My results are as follows:

Terrible data:

 sets  incard  outcard     old    new
----- -------  ------- ------- ------
 1000  210962   209952  0.7895 0.7065
 2000  402014   398234  2.3331 1.3666
 3000  653184   645704  4.7362 2.2826
 4000  716489   704769  7.2944 2.5551
 5000  778944   761348 10.5827 2.8060
 6000 1086422  1063786 16.9484 3.8118
 7000 1353463  1321590 25.8156 5.0257
 8000 1526383  1481590 31.5919 6.2615
 9000 1557691  1505788 37.2155 6.2446
10000 1739269  1675081 39.7824 6.6723

Better data:

 sets  incard outcard     old     new
----- ------- ------- -------  ------
10000  27909     2831  1.8006  0.0188  
20000  55977     4471  7.6253  0.0333  
30000  87758     6729 16.1100  0.0513
40000 117071     7592 28.1033  0.0652
50000 147528     8173 41.6088  0.0829

Good data:

  sets  incard outcard     old    new
------ ------- ------- ------- ------
 10000  134906      87  0.3966 0.0303
 20000  273611      87  0.9288 0.0637 
 30000  409257      87  1.4641 0.0935
 40000  547075      87  2.0427 0.1255
 50000  683781      87  2.6190 0.1593
 60000  820961      87  3.3493 0.1928
 70000  961180      87  3.9028 0.2203
 80000 1096768      87  4.4943 0.2514
 90000 1233960      87  5.0278 0.2839
100000 1369355      87  5.8539 0.3206

I too am seeing a big increase in performance, and I also verified that the input and output cardinality was unchanged with the old and new code. I didn't verify that the actual output ZSET was identical, but it seems rather likely given that the counts were correct.

@pete001

pete001 commented Jun 6, 2014

Copy link
Copy Markdown

Oh man... this is epic!

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

Great! I'm working at the new implementation, I hope Michael could re-run the tests against mine as well so that we are sure we are not regressing compared to the original implementation provided by the OP.

@michael-grunder

Copy link
Copy Markdown
Contributor

Of course, I'll run it when it's up. 😺

antirez added a commit that referenced this pull request Jun 6, 2014
The user @kjmph provided excellent ideas to improve speed of ZUNIONSTORE
(in certain cases by many order of magnitude), together with an
implementation of the ideas.

While the ideas were sounding, the implementation could be improved both
in terms of speed and clearness, so that's my attempt at reimplementing
the speedup proposed, trying to improve by directly using just a
dictionary with an embedded score inside, and reusing the single-pass
aggregate + order-later approach.

Note that you can't apply this commit without applying the previous
commit in this branch that adds a double in the dictEntry value union.

Issue #1786.
@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

Hey, I just tried to implement the same ideas as @kjmph in a more idiomatic way. I believe that since I touched more internals, my implementation should also be faster than the proposed one.

See commits fe85d06 and 932cc3e.

Waiting for the new @michael-grunder benchmarks before merging.

@kjmph

kjmph commented Jun 6, 2014

Copy link
Copy Markdown
Author

Hey, thanks for the interest! I was busy working this morning, sorry for the delay. I'm glad we can push forward performance of ZUNIONSTORE! I'll run our internal benchmark through this as well.. Give me a second.

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

Thank you @kjmph !

@kjmph

kjmph commented Jun 6, 2014

Copy link
Copy Markdown
Author

We are operating on 73690 zsets, with average cardinality ~250.

-- unpatched

$ time (cat test.run | redis-cli --pipe)
All data transferred. Waiting for the last reply...
No replies for 30 seconds: exiting.
errors: 1, replies: 0

real    0m31.026s
user    0m0.002s
sys 0m0.006s

--this pull request

$ time (cat test.run | redis-cli --pipe)
All data transferred. Waiting for the last reply...
Last reply received from server.
errors: 0, replies: 1

real    0m7.995s
user    0m0.002s
sys 0m0.006s

-- antirez's mod

$ time (cat test.run | redis-cli --pipe)
All data transferred. Waiting for the last reply...
Last reply received from server.
errors: 0, replies: 1

real    0m5.903s
user    0m0.002s
sys 0m0.006s

It looks great to me!

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

Awesome, thank you. I've to think a bit about if merging this into 2.8 or not... It's tempting because the slowdown in certain cases is bug-equivalent given the amount of unneeded work performed.

@kjmph

kjmph commented Jun 6, 2014

Copy link
Copy Markdown
Author

If it helps you at all, I merged the original mod into 2.8 for local usage. It was a bit fuzzy to apply the patch, but it was clean. It works well for us.. I can try merging your patch, see if that works locally.

@michael-grunder

Copy link
Copy Markdown
Contributor

Hey guys,

Terrible data:

 sets  incard outcard  simul antirez
----- ------- ------- ------ -------
 1000  210962  209952 0.7261   0.699
 2000  402014  398234 1.3778  1.5136
 3000  653184  645704 2.2863  2.7657
 4000  716489  704769 2.5477  3.0837
 5000  778944  761348 2.7972  3.4751
 6000 1086422 1063786 3.832   5.1017
 7000 1353463 1321590 5.1084  6.9063
 8000 1526383 1481590 5.9084  7.9222
 9000 1557691 1505788 5.9288  8.0592
10000 1739269 1675081 6.8483  8.9653

Better data:

 sets  incard outcard  simul antirez
----- ------- ------- ------ -------
10000   27909    2831 0.0166  0.0166
20000   55977    4471 0.0339  0.0304
30000   87758    6729 0.0535  0.0469
40000  117071    7592 0.0676  0.0641
50000  147528    8173 0.0818  0.0802
60000  177669    8668 0.0953  0.0966
70000  206338    9102 0.1082  0.1128
80000  236367    9614 0.1307  0.1254
90000  266938    9919 0.159   0.1409
100000 297171   10319 0.1603  0.1597
110000 326681   10496 0.1741   0.168
120000 357383   10722 0.198   0.1814
130000 384683   10868 0.1896  0.2001
140000 421635   11144 0.207   0.2117
150000 451829   11318 0.2319  0.2327
160000 479905   11419 0.2463  0.2406
170000 510744   11568 0.2596  0.2574
180000 539845   11675 0.2592  0.2724
190000 574045   11814 0.2852  0.2862
200000 603076   11919 0.2952  0.3159
210000 636362   12138 0.3064  0.3284
220000 666893   12252 0.3233  0.3284
230000 696814   12334 0.3344  0.3528
240000 728021   12412 0.3508  0.3675
250000 758040   12477  0.372  0.3876

Good data:

sets    incard  outcard  simul antirez
-----  -------  ------- ------ -------
10000   134906       87 0.0289  0.0307
20000   273611       87 0.0605  0.0622
30000   409257       87 0.0899  0.0942
40000   547075       87 0.1194  0.1318
50000   683781       87 0.1497  0.1647
60000   820961       87 0.1795  0.1953
70000   961180       87 0.2098  0.2314
80000  1096768       87 0.2409  0.2597
90000  1233960       87 0.2729  0.2955
100000 1369355       87 0.2994  0.3296

So I'm not seeing an improvement over @kjmph's mod, but that being said it's a benchmark so it could simply have to do with the data I'm using itself. I'm headed out the door but I'll re-run these in a more formalized way (it's a bit hackey right now) and post an update.

As far as I'm concerned the improvement is massive either way.

Cheers!
Mike

@kjmph

kjmph commented Jun 6, 2014

Copy link
Copy Markdown
Author

Since I have your ear on the subject. Performance of ~8s of my mod still wasn't good enough. I decreased it to roughly ~200ms. I would like to air it, maybe this isn't the right forum. I apologize if I am out of turn. However, I preloaded the full set of zsets(keys) into a compact multi-dimensional C array of doubles. Then, the ZUNIONSTORE is replaced with this custom command that takes the intersection between a provided set of key names and the preloaded set of keys and writes the aggregate to a destination key. It performs very well. Although, we only care about sums of weight 1.0, so I didn't code any other aggregates or weights into it. It should be easy to extend though. Is this a paradigm that is interesting to Redis?

@michael-grunder

Copy link
Copy Markdown
Contributor

Also +1 for merging into 2.8. :)

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

@kjmph the use case sounds interesting, but probably not general enough currently, however assuming at some point we add a matrix data type... this may be back into the mix of stuff that are possible using matrix and operations defined on the new data type. A field to explore... probably around 3.2, which is supposed to be the "back to data structures and API" fiesta ;-)

@antirez

antirez commented Jun 6, 2014

Copy link
Copy Markdown
Contributor

@michael-grunder thanks! A few of this columns actually look like a regression speed when using my updated code compared to @kjmph's. It is strange since my benchmarks and @kjmph original use case is faster with the new code that should do a bit less work, however I've the feeling that this may have something to do with dictExpand() calls I added... that trash locality, so when the access is repeated to the same elements, it may be a win to actually have a rehashing in progress instead to start with a huge table...

Please if you find some more time, would be awesome to have the benchmarks running with the dictExpand() calls commented, however I'll also try to work with parameters similar to yours to see if I'll be able to find tests where the original code was faster, and to check if actually my hypothesis has something to do with that. Thanks again!

@michael-grunder

Copy link
Copy Markdown
Contributor

@antirez I'll run a-b comparisons with the lines commented as well as against the original pull itself. In addition, I'll formalize the benchmark script just a bit more and post it so you can see if there is something about the test itself that is broken (don't see how, but it's always possible). I would even upload the rdb but it's client production data and I would likely have lawyers knocking on my door by morning. :P

@michael-grunder

Copy link
Copy Markdown
Contributor

Here are my updated benchmarks. The antirez-node column is with the dictExpand() calls commented out.

The code I used to benchmark is here:
https://gist.github.com/michael-grunder/4e315422d276f6701aaa

Terrible data:

sets  incard  outcard simul  antirez antirez-node
----- ------- ------- ------ ------- ------------
1000  210962  209952  0.6804 0.5784  0.6735
2000  402014  398234  1.3776 1.3203  1.5015
3000  653184  645704  2.3107 2.3951  2.662
4000  716489  704769  2.6867 2.7255  3.0219
5000  778944  761348  2.7778 3.0162  3.5083
6000  1086422 1063786 3.77   4.3757  4.9278
7000  1353463 1321590 5.0573 6.0919  6.4824
8000  1526383 1481590 5.7757 6.9882  7.6288
9000  1557691 1505788 5.8532 7.1209  7.654
10000 1739269 1675081 6.5317 8.0998  8.7956

Better data:

sets   incard outcard simul  antirez antirez-node 
------ ------ ------- ------ ------- ------------ 
10000  27909  2831    0.0177 0.0149  0.0156       
20000  55977  4471    0.0332 0.0306  0.0319       
30000  87758  6729    0.0515 0.0473  0.0506       
40000  117071 7592    0.0667 0.0653  0.0657       
50000  147528 8173    0.086  0.0781  0.0813       
60000  177669 8668    0.0965 0.0972  0.0971       
70000  206338 9102    0.1148 0.1094  0.1145       
80000  236367 9614    0.1243 0.1274  0.1272       
90000  266938 9919    0.1435 0.1395  0.1407       
100000 297171 10319   0.1549 0.1542  0.1583       
110000 326681 10496   0.1697 0.1653  0.1641       
120000 357383 10722   0.1806 0.1836  0.1812       
130000 384683 10868   0.191  0.1959  0.2017       
140000 421635 11144   0.2047 0.2111  0.2138       
150000 451829 11318   0.2178 0.2195  0.2245       
160000 479905 11419   0.2354 0.2403  0.2411       
170000 510744 11568   0.2519 0.2549  0.2513       
180000 539845 11675   0.2617 0.267   0.2761       
190000 574045 11814   0.2819 0.285   0.2841       
200000 603076 11919   0.3017 0.2974  0.3039       
210000 636362 12138   0.3095 0.3218  0.3176       
220000 666893 12252   0.3233 0.3306  0.3297       
230000 696814 12334   0.329  0.3402  0.3405       
240000 728021 12412   0.4109 0.3641  0.349        
250000 758040 12477   0.3973 0.3665  0.3758       

Good data:

sets   incard  outcard simul  antirez antirez-node 
------ ------- ------- ------ ------- ------------ 
10000  134906  87      0.0331 0.0301  0.0302       
20000  273611  87      0.0663 0.0633  0.0618       
30000  409257  87      0.1026 0.0956  0.0935       
40000  547075  87      0.1315 0.13    0.1281       
50000  683781  87      0.1664 0.1572  0.1595       
60000  820961  87      0.2001 0.1895  0.1898       
70000  961180  87      0.2296 0.2186  0.2241       
80000  1096768 87      0.2768 0.257   0.2542       
90000  1233960 87      0.3281 0.2934  0.2902       
100000 1369355 87      0.3666 0.3202  0.3296       

@mattsta

mattsta commented Jul 1, 2014

Copy link
Copy Markdown
Contributor

Hey everyone,

I was just thinking about this again today. It looks like the test with antirez version is the most acceptable here (the one with dictExpand()) as long as the data isn't "terrible" and assuming the tests are accurate and repeatable.

Potential idea: maybe generate sets in an independent script so we could test with redis-benchmark directly? It seems we should be able to smooth out the performance difference in the "terrible" cases with enough repeatable observations.

Any other ideas? We're looking at micro-optimizations at this point. The overall approach is a huge improvement from 40s down to under 1s for results.

@michael-grunder

Copy link
Copy Markdown
Contributor

@mattsta +1 to merging @antirez's branch. It's faster in two of the three use cases I tested, and nearly the same in the third. We'll probably push this live the moment it makes it into a stable branch, or even before. You know, YOLO and all. :)

@pete001

pete001 commented Jul 1, 2014

Copy link
Copy Markdown

+1 👍

@antirez

antirez commented Jul 1, 2014

Copy link
Copy Markdown
Contributor

Thank for bringing this up, I'm going to merge my version in this week since if there is not a huge bias towards the other version, mine is composed of simpler code I'm more confident backporting to 2.8. And judging from the other comments, there is no big bias to favor the original implementation in this PR. Thanks.

@michael-grunder

Copy link
Copy Markdown
Contributor

Shameless bump to see if we can get this into 2.8.14 :)

@pete001

pete001 commented Jul 22, 2014

Copy link
Copy Markdown

That would be amazing 👍

antirez added a commit that referenced this pull request Jul 22, 2014
The user @kjmph provided excellent ideas to improve speed of ZUNIONSTORE
(in certain cases by many order of magnitude), together with an
implementation of the ideas.

While the ideas were sounding, the implementation could be improved both
in terms of speed and clearness, so that's my attempt at reimplementing
the speedup proposed, trying to improve by directly using just a
dictionary with an embedded score inside, and reusing the single-pass
aggregate + order-later approach.

Note that you can't apply this commit without applying the previous
commit in this branch that adds a double in the dictEntry value union.

Issue #1786.
antirez added a commit that referenced this pull request Jul 22, 2014
This is not a regression but issue #1786 showed the need for this test.
antirez added a commit that referenced this pull request Jul 22, 2014
The user @kjmph provided excellent ideas to improve speed of ZUNIONSTORE
(in certain cases by many order of magnitude), together with an
implementation of the ideas.

While the ideas were sounding, the implementation could be improved both
in terms of speed and clearness, so that's my attempt at reimplementing
the speedup proposed, trying to improve by directly using just a
dictionary with an embedded score inside, and reusing the single-pass
aggregate + order-later approach.

Note that you can't apply this commit without applying the previous
commit in this branch that adds a double in the dictEntry value union.

Issue #1786.
antirez added a commit that referenced this pull request Jul 22, 2014
This is not a regression but issue #1786 showed the need for this test.
@antirez

antirez commented Jul 22, 2014

Copy link
Copy Markdown
Contributor

Just added a test for the issue found initially, of Redis test not testing order after an union operation, and merged into both unstable and 2.8. Thanks everybody for the collaboration with this issue!

@antirez antirez closed this Jul 22, 2014
antirez added a commit that referenced this pull request Jul 23, 2014
The user @kjmph provided excellent ideas to improve speed of ZUNIONSTORE
(in certain cases by many order of magnitude), together with an
implementation of the ideas.

While the ideas were sounding, the implementation could be improved both
in terms of speed and clearness, so that's my attempt at reimplementing
the speedup proposed, trying to improve by directly using just a
dictionary with an embedded score inside, and reusing the single-pass
aggregate + order-later approach.

Note that you can't apply this commit without applying the previous
commit in this branch that adds a double in the dictEntry value union.

Issue #1786.
antirez added a commit that referenced this pull request Jul 23, 2014
This is not a regression but issue #1786 showed the need for this test.
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.

5 participants