Skip to content

Introducing (Const)StridedRandomAccessor + CompositeRandomAccessor + migrate sort to ATen (CPU) - #39744

Closed
nikitaved wants to merge 10 commits into
masterfrom
nikved/sort_to_ATen
Closed

nikitaved wants to merge 10 commits into
masterfrom
nikved/sort_to_ATen

Conversation

@nikitaved

@nikitaved nikitaved commented Jun 9, 2020 •

Copy link
Copy Markdown
Collaborator

This PR introduces a (Const)StridedRandomAccessor, a random access iterator over a strided array, and a CompositeRandomAccessor, a random access iterator over two random access iterators.

The main motivation is to be able to use a handful of operations from STL and thrust in numerous dim-apply types of algorithms and eliminate unnecessary buffer allocations. Plus more advanced algorithms are going to be available with C++17.

Porting sort provides a hands-on example of how these iterators could be used.

Fixes #24770.

Some benchmarks:

from IPython import get_ipython

torch.manual_seed(13)

ipython = get_ipython()

sizes = [
        [10000, 10000],
        [1000, 1000, 100]
        ]
for size in sizes:
    t = torch.randn(*size)
    dims = len(size)

    print(f"Tensor of size {size}")
    for dim in range(dims):
        print(f"sort for dim={dim}")
        print("float:")
        ipython.magic("timeit t.sort(dim)")
    print()

Master

Tensor of size [10000, 10000]                                                                                                                     
sort for dim=0                                                                                                                                    
float:                                                                                                                                            
10.7 s ± 201 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)                                                                                
sort for dim=1                                                                                                                                    
float:                                                                                                                                            
6.27 s ± 50.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Tensor of size [1000, 1000, 100]
sort for dim=0
float:
7.21 s ± 23.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=1
float:
6.1 s ± 21.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=2
float:
3.58 s ± 27 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

This PR

Tensor of size [10000, 10000]
sort for dim=0
float:
10.5 s ± 209 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=1
float:
6.16 s ± 28.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Tensor of size [1000, 1000, 100]
sort for dim=0
float:
5.94 s ± 60.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=1
float:
5.1 s ± 11.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=2
float:
3.43 s ± 8.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

As you can see, the legacy sorting routine is actually quite efficient. The performance gain is likely due to the improved reduction with TensorIterator.

@nikitaved nikitaved changed the title [WIP] migrate [WIP] migrate 'sort' to ATen Jun 9, 2020
@nikitaved
nikitaved marked this pull request as draft June 9, 2020 18:35
@ShawnZhong

ShawnZhong commented Jun 9, 2020 •

Copy link
Copy Markdown
Contributor

Wow! It's pretty cool that you implemented the random-access iterator! I think this PR also paves the roads for a stable sort with std::stable_sort.

@dr-ci

dr-ci Bot commented Jun 9, 2020 •

Copy link
Copy Markdown

💊 CI failures summary and remediations

As of commit 5975f98 (more details on the Dr. CI page):


💚 💚 Looks good so far! There are no failures yet. 💚 💚


This comment was automatically generated by Dr. CI (expand for details).Follow this link to opt-out of these comments for your Pull Requests.

Please report bugs/suggestions on the GitHub issue tracker or post in the (internal) Dr. CI Users group.

See how this bot performed.

This comment has been revised 77 times.

@nikitaved nikitaved changed the title [WIP] migrate 'sort' to ATen [WIP] Introduce (Const)StridedRandomAccessor + CompositeRandomAccessor + migrate sort to ATen Jun 9, 2020
@nikitaved nikitaved changed the title [WIP] Introduce (Const)StridedRandomAccessor + CompositeRandomAccessor + migrate sort to ATen [WIP] Introduce (Const)StridedRandomAccessor + CompositeRandomAccessor + migrate sort to ATen (CPU) Jun 9, 2020
@nikitaved
nikitaved force-pushed the nikved/sort_to_ATen branch 2 times, most recently from 3fc19b9 to 647eb16 Compare June 11, 2020 22:10
@nikitaved
nikitaved force-pushed the nikved/sort_to_ATen branch 2 times, most recently from a6c143b to c05afe3 Compare June 12, 2020 13:38
@nikitaved
nikitaved marked this pull request as ready for review June 12, 2020 13:39
@nikitaved nikitaved changed the title [WIP] Introduce (Const)StridedRandomAccessor + CompositeRandomAccessor + migrate sort to ATen (CPU) Introducing (Const)StridedRandomAccessor + CompositeRandomAccessor + migrate sort to ATen (CPU) Jun 12, 2020
@kurtamohler

Copy link
Copy Markdown
Collaborator

Do you think there should be unit tests for all of the accessor methods? It's a pretty extensive API.

@nikitaved

nikitaved commented Jun 12, 2020 •

Copy link
Copy Markdown
Collaborator Author

So far I test with std::sort as it tests all the methods.

@kurtamohler

kurtamohler commented Jun 12, 2020 •

Copy link
Copy Markdown
Collaborator

@nikitaved , woops, accidentally edited your comment instead of replying, sorry! If std::sort exercises everything, then that's perfect.

@nikitaved

nikitaved commented Jun 12, 2020 •

Copy link
Copy Markdown
Collaborator Author

@kurtamohler , well, more tests never do harm :) Do you know how I could add cpp tests?

@kurtamohler

kurtamohler commented Jun 12, 2020 •

Copy link
Copy Markdown
Collaborator

You might be able to put it in test/cpp/api/. Maybe make your own file there. But I suspect there's a chance that at::native:: is not accessible from there. If not, you might be able to put them in aten/src/ATen/test/, though I've never dealt with those files before.

If test/cpp/api works, you can run ./build/bin/test_api --gtest_filter=<filter> after building to run your tests.

Comment on lines +73 to +84
template <typename scalar_t>
struct KeyValueCompAsc {
template <typename LHS, typename RHS>
constexpr bool operator()(LHS lhs, RHS rhs) const {
return (!_isnan<scalar_t>(get<0>(lhs)) && _isnan<scalar_t>(get<0>(rhs)))
|| (get<0>(lhs) < get<0>(rhs));
}
};

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Add a comment why we need typename LHS & RHS here.

@ailzhang
ailzhang requested a review from kurtamohler June 17, 2020 16:45
@ailzhang ailzhang added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Jun 17, 2020
@nikitaved

nikitaved commented Sep 18, 2020 •

Copy link
Copy Markdown
Collaborator Author

@glaringlee , note that swap and tie are defined with the same arguments for CPU and CUDA, only the implementation differs. Hence, they cannot lie in the same namespace, unless we split them somehow. Putting things into cpu and cuda folder makes sure that things live in the same namespace (at::native), so that the standard lookup works.
Another words, we do not exploit any AVX, but rather enable the (device-agnostic, depending on which header you inlcude) C++ Argument-Dependent Lookup within the same namespace, because, for example, std::sort needs std::swap and std::tie, while thrust::sort requires thrust::swap and thrust::tie.

@glaringlee

glaringlee commented Sep 18, 2020 •

Copy link
Copy Markdown
Contributor

@glaringlee , note that swap and tie are defined with the same arguments for CPU and CUDA, only the implementation differs. Hence, they cannot lie in the same namespace, unless we split them somehow. Putting things into cpu and cuda folder makes sure that things live in the same namespace (at::native), so that the standard lookup works.
Another words, we do not exploit any AVX, but rather enable the (device-agnostic, depending on which header you inlcude) C++ Argument-Dependent Lookup within the same namespace, because, for example, std::sort needs std::swap and std::tie, while thrust::sort requires thrust::swap and thrust::tie.

@nikitaved putting cuda code into cuda folder is fine. The reason I want the CPU code out of cpu folder is that any code within cpu folder will be compiled 3 times, one with DEFAULT instructions, one with AVX instructions and one with AVX2 instructions. This is only for cpu. cc @VitalyFedyunin

@nikitaved

Copy link
Copy Markdown
Collaborator Author

@glaringlee , got it! Thank you for this clarification :)

@nikitaved

nikitaved commented Sep 18, 2020 •

Copy link
Copy Markdown
Collaborator Author

@glaringlee , and what about the TensorIterator traversal? Does it make sense to move it from cpu?
/native/cpu/SortingKernel.cpp -> /native/SortingKernel.cpp

@glaringlee

Copy link
Copy Markdown
Contributor

@glaringlee , and what about the TensorIterator traversal? Does it make sense to move it from cpu?
/native/cpu/SortingKernel.cpp -> /native/SortingKernel.cpp

The sort_kernel related stuff can be moved out from cpu folder for sure. The topk_kernel seems fine to me as well. But if we want to move that out as well, need to do small benchmark to make sure the perf of topk_kernel doesn't change.

@nikitaved

nikitaved commented Sep 18, 2020 •

Copy link
Copy Markdown
Collaborator Author

After moving sorting_kernel outside the cpu folder I spotted a 10-15% regression in my tests on my system for large input.

Outside cpu:

Tensor of size [10000, 10000]                                                                                                                     
sort for dim=0                                                                                                                                    
float:                                                                                                                                            
11.2 s ± 324 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)                                                                                
sort for dim=1                                                                                                                                    
float:                                                                                                                                            
7.01 s ± 40 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Tensor of size [1000, 1000, 1000]
sort for dim=0
float:
6.52 s ± 238 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=1
float:
4.85 s ± 135 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=2
float:
4.32 s ± 105 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Inside cpu:

Tensor of size [10000, 10000]
sort for dim=0
float:
10.3 s ± 497 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=1
float:
6.6 s ± 473 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Tensor of size [1000, 1000, 1000]
sort for dim=0
float:
5.45 s ± 259 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=1
float:
4.11 s ± 183 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
sort for dim=2
float:
3.75 s ± 128 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

lscpu
Architecture:        x86_64
CPU op-mode(s):      32-bit, 64-bit
Byte Order:          Little Endian
CPU(s):              48
On-line CPU(s) list: 0-47
Thread(s) per core:  2
Core(s) per socket:  24
Socket(s):           1
NUMA node(s):        4
Vendor ID:           AuthenticAMD
CPU family:          23
Model:               8
Model name:          AMD Ryzen Threadripper 2970WX 24-Core Processor
Stepping:            2
CPU MHz:             1715.787
CPU max MHz:         3000.0000
CPU min MHz:         2200.0000
BogoMIPS:            5988.08
Virtualization:      AMD-V
L1d cache:           32K
L1i cache:           64K
L2 cache:            512K
L3 cache:            8192K
NUMA node0 CPU(s):   0-5,24-29
NUMA node1 CPU(s):   12-17,36-41
NUMA node2 CPU(s):   6-11,30-35
NUMA node3 CPU(s):   18-23,42-47
Flags:               fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid amd_dcm aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb hw_pstate sme ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 xsaves clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca

@glaringlee

Copy link
Copy Markdown
Contributor

@nikitaved give me 30mins, I'll do a test.

@nikitaved

Copy link
Copy Markdown
Collaborator Author

@glaringlee , do you want me to push the commit that moves things?

@codecov

codecov Bot commented Sep 18, 2020

Copy link
Copy Markdown

Codecov Report

Merging #39744 into master will increase coverage by 0.00%.
The diff coverage is n/a.

Impacted file tree graph

@@           Coverage Diff           @@
##           master   #39744   +/-   ##
=======================================
  Coverage   67.83%   67.83%           
=======================================
  Files         384      384           
  Lines       49945    49945           
=======================================
+ Hits        33881    33882    +1     
+ Misses      16064    16063    -1     
Impacted Files Coverage Δ
torch/testing/_internal/expecttest.py 78.57% <0.00%> (+1.02%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 0063512...5975f98. Read the comment docs.

@glaringlee

Copy link
Copy Markdown
Contributor

@glaringlee , and what about the TensorIterator traversal? Does it make sense to move it from cpu?
/native/cpu/SortingKernel.cpp -> /native/SortingKernel.cpp

I think

@glaringlee , do you want me to push the commit that moves things?

@nikitaved
Just tested on my end. around 10% regression outside the cpu folder.
I noticed a difference between -O3 and -O3 -mavx/-mavx2, vector and tuple initializations are faster under avx/2, I think this probably be the reason why we have this regression outside the cpu folder. std::sort is slightly faster, but not much.

Let's keep the code in cpu folder then. Sorry about this back and force.
Please do a rebase against the latest master branch. I think this is good to land. I'll land this code once the CI tests and fb internal tests done.

@facebook-github-bot facebook-github-bot left a comment

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.

@glaringlee has imported this pull request. If you are a Facebook employee, you can view this diff on Phabricator.

@glaringlee

glaringlee commented Sep 18, 2020 •

Copy link
Copy Markdown
Contributor

@nikitaved One more thing i want to ask is that. I saw the benchmark you post. For 3D tensor, the new benchmark is much faster than the old code, this probably due to the parallel computing that supported by Tensoriterator. Can you do a benchmark to test the performance of your code under single thread?
In python, please set
torch.set_num_threads(1)
and
OMP_NUM_THREADS=1

@nikitaved

nikitaved commented Sep 18, 2020 •

Copy link
Copy Markdown
Collaborator Author

Will do, a more thorough benchmarking was done here:
#38338 (comment)

I have updated the benchmark in the header. Only single thread was used.

@glaringlee

Copy link
Copy Markdown
Contributor

@nikitaved Thanks a lot. I noticed that you actually rebased this code today. I will go ahead to land this once the fb internal tests are done.

@glaringlee glaringlee left a comment

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.

LGTM now.

@facebook-github-bot facebook-github-bot left a comment

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.

@glaringlee has imported this pull request. If you are a Facebook employee, you can view this diff on Phabricator.

@nikitaved

Copy link
Copy Markdown
Collaborator Author

@glaringlee , thank you for taking care of this one!

@facebook-github-bot

Copy link
Copy Markdown
Contributor

@glaringlee merged this pull request in 9dc2bcd.

@facebook-github-bot
facebook-github-bot deleted the nikved/sort_to_ATen branch January 27, 2021 18:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Merged open source triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Migrate sort from the TH to Aten (CPU)