Skip to content

ReduceLayer much slower than Pytorch #1491

Closed

Description

@entropyfeng

Description

TenorRT's addReduce() 10 times slower than Pytorch's .sum() operation.
Using addReduce() consumes about 9.38 ms.
Using .sum() consumes ablut 0.89 ms

Environment

TensorRT Version: 7.1.3.0
NVIDIA Platform: Jetson TX2
NVIDIA Driver Version:
CUDA Version: 10.2.89
CUDNN Version: 8.0.0.120
Operating System: Ubuntu 18.04
Python Version (if applicable): 3.6.9
PyTorch Version (if applicable): 1.8.0

Relevant Files

a=torch.rand((1,1,256,49,16,16),device='cuda:0')
b=torch.rand((1,1,1,49,16,16),device='cuda:0')
time_start = time.time()
temp = (a * b).sum(3)
time_end = time.time()
print('totally cost', (time_end - time_start),' s')

and the TensorRT code

    // Create builder
    IBuilder *builder = createInferBuilder(gLogger);
    IBuilderConfig *config = builder->createBuilderConfig();
    // Create model to populate the network, then set the outputs and create an engine
    const auto explicitBatch = 1U << static_cast<uint32_t>(NetworkDefinitionCreationFlag::kEXPLICIT_BATCH);
    INetworkDefinition *network = builder->createNetworkV2(explicitBatch);
    DataType dt = DataType::kFLOAT;

    ITensor *input0 = network->addInput("input0", dt, Dims{6, {1, 1, 256, 49, 16, 16}});
    ITensor *input1 = network->addInput("input1", dt, Dims{6, {1, 1, 1, 49, 16, 16}});


    IElementWiseLayer *elementWiseLayer = network->addElementWise(*input0, *input1, ElementWiseOperation::kPROD);
    IReduceLayer *reduceLayer = network->addReduce(*elementWiseLayer->getOutput(0), ReduceOperation::kSUM, 8, true);
    network->markOutput(*reduceLayer->getOutput(0));
    ITensor *res = reduceLayer->getOutput(0);
    res->setName("res");
    std::cout << "Building engine, please wait for a while..." << std::endl;
    ICudaEngine *engine = builder->buildEngineWithConfig(*network, *config);
    // Build engine
    builder->setMaxBatchSize(1);
    config->setMaxWorkspaceSize(16 * (1 << 20)); 
    config->setFlag(BuilderFlag::kTF32);

    assert(engine != nullptr);
    std::cout << "Build engine successfully!" << std::endl;
    const int input0Size = 256 * 49 * 16 * 16;
    const int input1Size = 49 * 16 * 16;
    const int outputSize = 256 * 16 * 16;
    IExecutionContext *context = engine->createExecutionContext();
    assert(context != nullptr);
    context->setProfiler(&myProfile);
    assert(engine->getNbBindings() == 3);

    // prepare input data ---------------------------
    auto *data0 = new float[input0Size];
    for (int i = 0; i < input0Size; i++) {
        data0[i] = i + 1.0;
    }
    auto *data1 = new float[input1Size];
    for (int i = 0; i < input1Size; i++) {
        data1[i] = i + 1.0;
    }
    auto *outData = new float[outputSize];
    void *buffers[3];
    // In order to bind the buffers, we need to know the names of the input and output tensors.
    // Note that indices are guaranteed to be less than IEngine::getNbBindings()
    const int input0Index = engine->getBindingIndex("input0");
    const int input1Index = engine->getBindingIndex("input1");
    const int outputIndex = engine->getBindingIndex("res");
    assert(input0Index == 0);
    assert(input1Index == 1);
    assert(outputIndex == 2);
    // Create GPU buffers on device
    CUDA_CHECK(cudaMalloc(&buffers[input0Index], input0Size * sizeof(float)));
    CUDA_CHECK(cudaMalloc(&buffers[input1Index], input1Size * sizeof(float)));
    CUDA_CHECK(cudaMalloc(&buffers[outputIndex], outputSize * sizeof(float)));

    auto start = std::chrono::system_clock::now();
    cudaStream_t stream;
    CUDA_CHECK(cudaStreamCreate(&stream));
    CUDA_CHECK(cudaMemcpyAsync(buffers[0], data0, input0Size * sizeof(float), cudaMemcpyHostToDevice, stream));
    CUDA_CHECK(cudaMemcpyAsync(buffers[1], data1, input1Size * sizeof(float), cudaMemcpyHostToDevice, stream));
    context->executeV2(buffers);
    CUDA_CHECK(cudaMemcpyAsync(outData, buffers[2], outputSize * sizeof(float), cudaMemcpyDeviceToHost, stream));
    auto end = std::chrono::system_clock::now();
    std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;

    myProfile.printLayerTimes();
    // Release stream and buffers
    CUDA_CHECK(cudaFree(buffers[input0Index]));
    CUDA_CHECK(cudaFree(buffers[input1Index]));
    CUDA_CHECK(cudaFree(buffers[outputIndex]));

    // Close everything down
    engine->destroy();
    builder->destroy();
    config->destroy();

In addition, i re implement IProfile interface to measure the forward time at each layer of the network.
(Unnamed Layer* 0) [ElementWise] 1.144ms
(Unnamed Layer* 1) [Reduce] 9.380ms
Time over all layers: 10.524

struct Profiler : public IProfiler {
    typedef std::pair<std::string, float> Record;
    std::vector<Record> mProfile;
    virtual void reportLayerTime(const char *layerName, float ms) {
        auto record = std::find_if(mProfile.begin(), mProfile.end(),
                                   [&](const Record &r) { return r.first == layerName; });

        if (record == mProfile.end())
            mProfile.push_back(std::make_pair(layerName, ms));
        else
            record->second += ms;
    }
    void printLayerTimes() {
        float totalTime = 0;
        for (size_t i = 0; i < mProfile.size(); i++) {
            printf("%-80.80s %4.3fms\n", mProfile[i].first.c_str(), mProfile[i].second / TIMING_ITERATIONS);
            totalTime += mProfile[i].second;
        }
        printf("Time over all layers: %4.3f\n", totalTime / TIMING_ITERATIONS);
    }
} myProfile;

Activity

  1. self-assigned this
    on May 19, 2022
  2. added
    Module:Performance
    triaged
    on May 19, 2022
  3. nvpohanh commented on May 19, 2022

    @nvpohanh
    Collaborator

    @entropyfeng This performance issue should have been fixed as of TensorRT 8.2. Could you try a newer TensorRT version? Thanks

  4. nvpohanh commented on Jul 1, 2022

    @nvpohanh
    Collaborator

    Closing due to >14 days without activity. Please feel free to reopen if the issue still exists. Thanks

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

Metadata

Metadata

Assignees

Labels

Module:Performancetriaged

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions