CudaSort.cpp 7.59 KB
Newer Older
1
2
3
4
5
6
7
8
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
 * This is part of the OpenMM molecular simulation toolkit originating from   *
 * Simbios, the NIH National Center for Physics-Based Simulation of           *
 * Biological Structures at Stanford, funded under the NIH Roadmap for        *
 * Medical Research, grant U54 GM072970. See https://simtk.org.               *
 *                                                                            *
9
 * Portions copyright (c) 2010-2025 Stanford University and the Authors.      *
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 * Authors: Peter Eastman                                                     *
 * Contributors:                                                              *
 *                                                                            *
 * This program is free software: you can redistribute it and/or modify       *
 * it under the terms of the GNU Lesser General Public License as published   *
 * by the Free Software Foundation, either version 3 of the License, or       *
 * (at your option) any later version.                                        *
 *                                                                            *
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Lesser General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
 * -------------------------------------------------------------------------- */

#include "CudaSort.h"
#include "CudaKernelSources.h"
peastman's avatar
peastman committed
29
#include <algorithm>
30
31
32
33
34
#include <map>

using namespace OpenMM;
using namespace std;

35
CudaSort::CudaSort(CudaContext& context, ComputeSortImpl::SortTrait* trait, unsigned int length, bool uniform) :
36
        context(context), trait(trait), dataLength(length), uniform(uniform) {
37
38
39
40
41
42
43
44
45
    // Create kernels.

    map<string, string> replacements;
    replacements["DATA_TYPE"] = trait->getDataType();
    replacements["KEY_TYPE"] =  trait->getKeyType();
    replacements["SORT_KEY"] = trait->getSortKey();
    replacements["MIN_KEY"] = trait->getMinKey();
    replacements["MAX_KEY"] = trait->getMaxKey();
    replacements["MAX_VALUE"] = trait->getMaxValue();
46
    replacements["UNIFORM"] = (uniform ? "1" : "0");
47
    CUmodule module = context.createModule(context.replaceStrings(CudaKernelSources::sort, replacements));
48
    shortListKernel = context.getKernel(module, "sortShortList");
peastman's avatar
peastman committed
49
    shortList2Kernel = context.getKernel(module, "sortShortList2");
50
    computeRangeKernel = context.getKernel(module, "computeRange");
51
    assignElementsKernel = context.getKernel(module, uniform ? "assignElementsToBuckets" : "assignElementsToBuckets2");
52
53
54
55
56
57
58
59
    computeBucketPositionsKernel = context.getKernel(module, "computeBucketPositions");
    copyToBucketsKernel = context.getKernel(module, "copyDataToBuckets");
    sortBucketsKernel = context.getKernel(module, "sortBuckets");

    // Work out the work group sizes for various kernels.

    int maxBlockSize;
    cuDeviceGetAttribute(&maxBlockSize, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, context.getDevice());
60
61
    int maxSharedMem;
    cuDeviceGetAttribute(&maxSharedMem, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, context.getDevice());
peastman's avatar
peastman committed
62
    int maxLocalBuffer = (maxSharedMem/trait->getDataSize())/2;
63
    int maxShortList = min(3000, max(maxLocalBuffer, CudaContext::ThreadBlockSize*context.getNumThreadBlocks()));
peastman's avatar
peastman committed
64
    isShortList = (length <= maxShortList);
65
66
67
    for (rangeKernelSize = 1; rangeKernelSize*2 <= maxBlockSize; rangeKernelSize *= 2)
        ;
    positionsKernelSize = rangeKernelSize;
68
    sortKernelSize = (isShortList ? rangeKernelSize/2 : rangeKernelSize/4);
69
70
71
72
73
74
75
76
77
78
79
80
81
    if (rangeKernelSize > length)
        rangeKernelSize = length;
    if (sortKernelSize > maxLocalBuffer)
        sortKernelSize = maxLocalBuffer;
    unsigned int targetBucketSize = sortKernelSize/2;
    unsigned int numBuckets = length/targetBucketSize;
    if (numBuckets < 1)
        numBuckets = 1;
    if (positionsKernelSize > numBuckets)
        positionsKernelSize = numBuckets;

    // Create workspace arrays.

82
    if (!isShortList) {
Peter Eastman's avatar
Peter Eastman committed
83
84
85
86
        dataRange.initialize(context, 2, trait->getKeySize(), "sortDataRange");
        bucketOffset.initialize<uint1>(context, numBuckets, "bucketOffset");
        bucketOfElement.initialize<uint1>(context, length, "bucketOfElement");
        offsetInBucket.initialize<uint1>(context, length, "offsetInBucket");
87
    }
peastman's avatar
peastman committed
88
    buckets.initialize(context, length, trait->getDataSize(), "buckets");
89
90
91
92
93
94
}

CudaSort::~CudaSort() {
    delete trait;
}

95
void CudaSort::sort(ArrayInterface& data) {
96
    if (data.getSize() != dataLength || data.getElementSize() != trait->getDataSize())
97
98
99
        throw OpenMMException("CudaSort called with different data size");
    if (data.getSize() == 0)
        return;
100
    CudaArray& cudata = context.unwrap(data);
101
    if (isShortList) {
peastman's avatar
peastman committed
102
        // We can use a simpler sort kernel that does the entire operation in one kernel.
103
        
peastman's avatar
peastman committed
104
        if (dataLength <= CudaContext::ThreadBlockSize*context.getNumThreadBlocks()) {
105
            void* sortArgs[] = {&cudata.getDevicePointer(), &buckets.getDevicePointer(), &dataLength};
peastman's avatar
peastman committed
106
            context.executeKernel(shortList2Kernel, sortArgs, dataLength);
107
            buckets.copyTo(cudata);
peastman's avatar
peastman committed
108
109
        }
        else {
110
            void* sortArgs[] = {&cudata.getDevicePointer(), &dataLength};
peastman's avatar
peastman committed
111
112
            context.executeKernel(shortListKernel, sortArgs, sortKernelSize, sortKernelSize, dataLength*trait->getDataSize());
        }
113
114
115
    }
    else {
        // Compute the range of data values.
116

Peter Eastman's avatar
Peter Eastman committed
117
        unsigned int numBuckets = bucketOffset.getSize();
118
        void* rangeArgs[] = {&cudata.getDevicePointer(), &dataLength, &dataRange.getDevicePointer(), &numBuckets, &bucketOffset.getDevicePointer()};
Peter Eastman's avatar
Peter Eastman committed
119
        context.executeKernel(computeRangeKernel, rangeArgs, rangeKernelSize, rangeKernelSize, 2*rangeKernelSize*trait->getKeySize());
120

121
        // Assign array elements to buckets.
122

123
        void* elementsArgs[] = {&cudata.getDevicePointer(), &dataLength, &numBuckets, &dataRange.getDevicePointer(),
Peter Eastman's avatar
Peter Eastman committed
124
                &bucketOffset.getDevicePointer(), &bucketOfElement.getDevicePointer(), &offsetInBucket.getDevicePointer()};
125
        context.executeKernel(assignElementsKernel, elementsArgs, cudata.getSize(), 128);
126

127
        // Compute the position of each bucket.
128

Peter Eastman's avatar
Peter Eastman committed
129
        void* computeArgs[] = {&numBuckets, &bucketOffset.getDevicePointer()};
130
        context.executeKernel(computeBucketPositionsKernel, computeArgs, positionsKernelSize, positionsKernelSize, positionsKernelSize*sizeof(int));
131

132
        // Copy the data into the buckets.
133

134
        void* copyArgs[] = {&cudata.getDevicePointer(), &buckets.getDevicePointer(), &dataLength, &bucketOffset.getDevicePointer(),
Peter Eastman's avatar
Peter Eastman committed
135
                &bucketOfElement.getDevicePointer(), &offsetInBucket.getDevicePointer()};
136
        context.executeKernel(copyToBucketsKernel, copyArgs, cudata.getSize());
137

138
        // Sort each bucket.
139

140
141
        void* sortArgs[] = {&cudata.getDevicePointer(), &buckets.getDevicePointer(), &numBuckets, &bucketOffset.getDevicePointer()};
        context.executeKernel(sortBucketsKernel, sortArgs, ((cudata.getSize()+sortKernelSize-1)/sortKernelSize)*sortKernelSize, sortKernelSize, sortKernelSize*trait->getDataSize());
142
    }
143
}