added real-esrgan (#999)

* added real-esrgan

* deleted sample image & modified README

* tab to space
This commit is contained in:
yhpark 2022-05-23 11:14:05 +09:00 committed by GitHub
parent 42b4f94527
commit e0c5243a53
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 1717 additions and 0 deletions

View File

@ -0,0 +1,44 @@
cmake_minimum_required(VERSION 2.6)
project(real-esrgan)
add_definitions(-std=c++11)
add_definitions(-DAPI_EXPORTS)
option(CUDA_USE_STATIC_CUDA_RUNTIME OFF)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_BUILD_TYPE Debug)
find_package(CUDA REQUIRED)
if(WIN32)
enable_language(CUDA)
endif(WIN32)
include_directories(${PROJECT_SOURCE_DIR}/include)
# include and link dirs of cuda and tensorrt, you need adapt them if yours are different
# cuda
include_directories(/usr/local/cuda/include)
link_directories(/usr/local/cuda/lib64)
# tensorrt
include_directories(/usr/include/x86_64-linux-gnu/)
link_directories(/usr/lib/x86_64-linux-gnu/)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall -Ofast -g -Wfatal-errors -D_MWAITXINTRIN_H_INCLUDED")
cuda_add_library(myplugins SHARED preprocess.cu postprocess.cu)
target_link_libraries(myplugins nvinfer cudart)
find_package(OpenCV)
include_directories(${OpenCV_INCLUDE_DIRS})
cuda_add_executable(real-esrgan real-esrgan.cpp)
target_link_libraries(real-esrgan nvinfer)
target_link_libraries(real-esrgan cudart)
target_link_libraries(real-esrgan myplugins)
target_link_libraries(real-esrgan ${OpenCV_LIBS})
if(UNIX)
add_definitions(-O2 -pthread)
endif(UNIX)

59
real-esrgan/README.md Normal file
View File

@ -0,0 +1,59 @@
# Real-ESRGAN
The Pytorch implementation is [real-esrgan](https://github.com/xinntao/Real-ESRGAN).
## Config
- Input shape(**INPUT_H**, **INPUT_W**, **INPUT_C**) defined in real-esrgan.cpp
- GPU id(**DEVICE**) can be selected by the macro in real-esrgan.cpp
- **BATCH_SIZE** can be selected by the macro in real-esrgan.cpp
- FP16/FP32 can be selected by **PRECISION_MODE** in real-esrgan.cpp
- The example result can be visualized by **VISUALIZATION**.
## How to Run, real-esrgan as example
0. prepare test image
- download : [OST_009.png](https://drive.google.com/file/d/1KAyAiQ8qHc5jSBkk2Uft2LfIhzi9XSyH/view?usp=sharing)
```
cd {tensorrtx}/real-esrgan/
mkdir sample
cp ~/Download/OST_009.png {tensorrtx}/real-esrgan/sample
```
1. generate .wts from pytorch with .pt, or download .wts from model zoo
```
git clone https://github.com/xinntao/Real-ESRGAN.git
cd Real-ESRGAN
pip install basicsr
pip install facexlib
pip install gfpgan
pip install -r requirements.txt
python setup.py develop
// download https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth
cp ~/RealESRGAN_x4plus.pth {xinntao}/Real-ESRGAN/experiments/pretrained_models
cp {tensorrtx}/Real-ESRGAN/gen_wts.py {xinntao}/Real-ESRGAN
cd {xinntao}/Real-ESRGAN
python gen_wts.py
// a file 'real-esrgan.wts' will be generated.
```
2. build tensorrtx/real-esrgan and run
```
cd {tensorrtx}/real-esrgan/
mkdir build
cd build
cp {xinntao}/Real-ESRGAN/real-esrgan.wts {tensorrtx}/real-esrgan/build
cmake ..
make
sudo ./real-esrgan -s [.wts] [.engine] // serialize model to plan file
sudo ./real-esrgan -d [.engine] [image folder] // deserialize and run inference, the images in [image folder] will be processed.
// For example
// sudo ./real-esrgan -s ./real-esrgan.wts ./real-esrgan_f32.engine
// sudo ./real-esrgan -d ./real-esrgan_f32.engine ../samples
```
3. check the images generated, as follows. _OST_009.png

137
real-esrgan/common.hpp Normal file
View File

@ -0,0 +1,137 @@
#ifndef REAL_ESRGAN_COMMON_H_
#define REAL_ESRGAN_COMMON_H_
#include <fstream>
#include <map>
#include <sstream>
#include <vector>
#include <opencv2/opencv.hpp>
#include "NvInfer.h"
using namespace nvinfer1;
// TensorRT weight files have a simple space delimited format:
// [type] [size] <data x size in hex>
std::map<std::string, Weights> loadWeights(const std::string file) {
std::cout << "Loading weights: " << file << std::endl;
std::map<std::string, Weights> weightMap;
// Open weights file
std::ifstream input(file);
assert(input.is_open() && "Unable to load weight file. please check if the .wts file path is right!!!!!!");
// Read number of weight blobs
int32_t count;
input >> count;
assert(count > 0 && "Invalid weight map file.");
while (count--)
{
Weights wt{ DataType::kFLOAT, nullptr, 0 };
uint32_t size;
// Read name and type of blob
std::string name;
input >> name >> std::dec >> size;
wt.type = DataType::kFLOAT;
// Load blob
uint32_t* val = reinterpret_cast<uint32_t*>(malloc(sizeof(val) * size));
for (uint32_t x = 0, y = size; x < y; ++x)
{
input >> std::hex >> val[x];
}
wt.values = val;
wt.count = size;
weightMap[name] = wt;
}
return weightMap;
}
ITensor* residualDenseBlock(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor* x, std::string lname)
{
IConvolutionLayer* conv_1 = network->addConvolutionNd(*x, 32, DimsHW{ 3, 3 }, weightMap[lname + ".conv1.weight"], weightMap[lname + ".conv1.bias"]);
conv_1->setStrideNd(DimsHW{ 1, 1 });
conv_1->setPaddingNd(DimsHW{ 1, 1 });
IActivationLayer* leaky_relu_1 = network->addActivation(*conv_1->getOutput(0), ActivationType::kLEAKY_RELU);
leaky_relu_1->setAlpha(0.2);
ITensor* x1 = leaky_relu_1->getOutput(0);
ITensor* concat_input2[] = { x, x1 };
IConcatenationLayer* concat2 = network->addConcatenation(concat_input2, 2);
concat2->setAxis(0);
IConvolutionLayer* conv_2 = network->addConvolutionNd(*concat2->getOutput(0), 32, DimsHW{ 3, 3 }, weightMap[lname + ".conv2.weight"], weightMap[lname + ".conv2.bias"]);
conv_2->setStrideNd(DimsHW{ 1, 1 });
conv_2->setPaddingNd(DimsHW{ 1, 1 });
IActivationLayer* leaky_relu_2 = network->addActivation(*conv_2->getOutput(0), ActivationType::kLEAKY_RELU);
leaky_relu_2->setAlpha(0.2);
ITensor* x2 = leaky_relu_2->getOutput(0);
ITensor* concat_input3[] = { x, x1, x2 };
IConcatenationLayer* concat3 = network->addConcatenation(concat_input3, 3);
concat3->setAxis(0);
IConvolutionLayer* conv_3 = network->addConvolutionNd(*concat3->getOutput(0), 32, DimsHW{ 3, 3 }, weightMap[lname + ".conv3.weight"], weightMap[lname + ".conv3.bias"]);
conv_3->setStrideNd(DimsHW{ 1, 1 });
conv_3->setPaddingNd(DimsHW{ 1, 1 });
IActivationLayer* leaky_relu_3 = network->addActivation(*conv_3->getOutput(0), ActivationType::kLEAKY_RELU);
leaky_relu_3->setAlpha(0.2);
ITensor* x3 = leaky_relu_3->getOutput(0);
ITensor* concat_input4[] = { x, x1, x2, x3 };
IConcatenationLayer* concat4 = network->addConcatenation(concat_input4, 4);
concat4->setAxis(0);
IConvolutionLayer* conv_4 = network->addConvolutionNd(*concat4->getOutput(0), 32, DimsHW{ 3, 3 }, weightMap[lname + ".conv4.weight"], weightMap[lname + ".conv4.bias"]);
conv_4->setStrideNd(DimsHW{ 1, 1 });
conv_4->setPaddingNd(DimsHW{ 1, 1 });
IActivationLayer* leaky_relu_4 = network->addActivation(*conv_4->getOutput(0), ActivationType::kLEAKY_RELU);
leaky_relu_4->setAlpha(0.2);
ITensor* x4 = leaky_relu_4->getOutput(0);
ITensor* concat_input5[] = { x, x1, x2, x3, x4 };
IConcatenationLayer* concat5 = network->addConcatenation(concat_input5, 5);
concat5->setAxis(0);
IConvolutionLayer* conv_5 = network->addConvolutionNd(*concat5->getOutput(0), 64, DimsHW{ 3, 3 }, weightMap[lname + ".conv5.weight"], weightMap[lname + ".conv5.bias"]);
conv_5->setStrideNd(DimsHW{ 1, 1 });
conv_5->setPaddingNd(DimsHW{ 1, 1 });
ITensor* x5 = conv_5->getOutput(0);
float *scval = reinterpret_cast<float*>(malloc(sizeof(float)));
*scval = 0.2;
Weights scale{ DataType::kFLOAT, scval, 1 };
float *shval = reinterpret_cast<float*>(malloc(sizeof(float)));
*shval = 0.0;
Weights shift{ DataType::kFLOAT, shval, 1 };
float *pval = reinterpret_cast<float*>(malloc(sizeof(float)));
*pval = 1.0;
Weights power{ DataType::kFLOAT, pval, 1 };
IScaleLayer* scaled = network->addScale(*x5, ScaleMode::kUNIFORM, shift, scale, power);
IElementWiseLayer* ew1 = network->addElementWise(*scaled->getOutput(0), *x, ElementWiseOperation::kSUM);
return ew1->getOutput(0);
}
ITensor* RRDB(INetworkDefinition *network, std::map<std::string, Weights>& weightMap, ITensor* x, std::string lname)
{
ITensor* out = residualDenseBlock(network, weightMap, x, lname + ".rdb1");
out = residualDenseBlock(network, weightMap, out, lname + ".rdb2");
out = residualDenseBlock(network, weightMap, out, lname + ".rdb3");
float *scval = reinterpret_cast<float*>(malloc(sizeof(float)));
*scval = 0.2;
Weights scale{ DataType::kFLOAT, scval, 1 };
float *shval = reinterpret_cast<float*>(malloc(sizeof(float)));
*shval = 0.0;
Weights shift{ DataType::kFLOAT, shval, 1 };
float *pval = reinterpret_cast<float*>(malloc(sizeof(float)));
*pval = 1.0;
Weights power{ DataType::kFLOAT, pval, 1 };
IScaleLayer* scaled = network->addScale(*out, ScaleMode::kUNIFORM, shift, scale, power);
IElementWiseLayer* ew1 = network->addElementWise(*scaled->getOutput(0), *x, ElementWiseOperation::kSUM);
return ew1->getOutput(0);
}
#endif

22
real-esrgan/cuda_utils.h Normal file
View File

@ -0,0 +1,22 @@
#ifndef TRTX_CUDA_UTILS_H_
#define TRTX_CUDA_UTILS_H_
#include <cuda_runtime_api.h>
#include <stdint.h>
#include <cstdio>
#include <vector>
#include <iostream>
#ifndef CUDA_CHECK
#define CUDA_CHECK(callstr)\
{\
cudaError_t error_code = callstr;\
if (error_code != cudaSuccess) {\
std::cerr << "CUDA error " << error_code << " at " << __FILE__ << ":" << __LINE__;\
assert(0);\
}\
}
#endif // CUDA_CHECK
#endif // TRTX_CUDA_UTILS_H_

92
real-esrgan/gen_wts.py Normal file
View File

@ -0,0 +1,92 @@
import argparse
import os
import struct
from basicsr.archs.rrdbnet_arch import RRDBNet
from realesrgan import RealESRGANer
from realesrgan.archs.srvgg_arch import SRVGGNetCompact
def main():
"""Inference demo for Real-ESRGAN.
"""
parser = argparse.ArgumentParser()
#parser.add_argument('-i', '--input', type=str, default='../TestData3', help='Input image or folder')
parser.add_argument('-i', '--input', type=str, default='inputs', help='Input image or folder')
parser.add_argument(
'-n',
'--model_name',
type=str,
default='RealESRGAN_x4plus',
help=('Model names: RealESRGAN_x4plus | RealESRNet_x4plus | RealESRGAN_x4plus_anime_6B | RealESRGAN_x2plus | '
'realesr-animevideov3'))
parser.add_argument('-o', '--output', type=str, default='results', help='Output folder')
parser.add_argument('-s', '--outscale', type=float, default=4, help='The final upsampling scale of the image')
parser.add_argument('--suffix', type=str, default='out', help='Suffix of the restored image')
parser.add_argument('-t', '--tile', type=int, default=0, help='Tile size, 0 for no tile during testing')
parser.add_argument('--tile_pad', type=int, default=10, help='Tile padding')
parser.add_argument('--pre_pad', type=int, default=0, help='Pre padding size at each border')
parser.add_argument('--face_enhance', action='store_true', help='Use GFPGAN to enhance face')
parser.add_argument(
'--fp32', action='store_true', help='Use fp32 precision during inference. Default: fp16 (half precision).')
parser.add_argument(
'--alpha_upsampler',
type=str,
default='realesrgan',
help='The upsampler for the alpha channels. Options: realesrgan | bicubic')
parser.add_argument(
'--ext',
type=str,
default='auto',
help='Image extension. Options: auto | jpg | png, auto means using the same extension as inputs')
args = parser.parse_args()
# determine models according to model names
args.model_name = args.model_name.split('.')[0]
if args.model_name in ['RealESRGAN_x4plus', 'RealESRNet_x4plus']: # x4 RRDBNet model
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4)
netscale = 4
elif args.model_name in ['RealESRGAN_x4plus_anime_6B']: # x4 RRDBNet model with 6 blocks
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
netscale = 4
elif args.model_name in ['RealESRGAN_x2plus']: # x2 RRDBNet model
model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=2)
netscale = 2
elif args.model_name in ['realesr-animevideov3']: # x4 VGG-style model (XS size)
model = SRVGGNetCompact(num_in_ch=3, num_out_ch=3, num_feat=64, num_conv=16, upscale=4, act_type='prelu')
netscale = 4
# determine model paths
model_path = os.path.join('experiments/pretrained_models', args.model_name + '.pth')
if not os.path.isfile(model_path):
model_path = os.path.join('realesrgan/weights', args.model_name + '.pth')
if not os.path.isfile(model_path):
raise ValueError(f'Model {args.model_name} does not exist.')
# restorer
upsampler = RealESRGANer(
scale=netscale,
model_path=model_path,
model=model,
tile=args.tile,
tile_pad=args.tile_pad,
pre_pad=args.pre_pad,
half=args.fp32)
if os.path.isfile('real-esrgan.wts'):
print('Already, real-esrgan.wts file exists.')
else:
print('making real-esrgan.wts file ...')
f = open("real-esrgan.wts", 'w')
f.write("{}\n".format(len(upsampler.model.state_dict().keys())))
for k, v in upsampler.model.state_dict().items():
print('key: ', k)
print('value: ', v.shape)
vr = v.reshape(-1).cpu().numpy()
f.write("{} {}".format(k, len(vr)))
for vv in vr:
f.write(" ")
f.write(struct.pack(">f", float(vv)).hex())
f.write("\n")
print('Completed real-esrgan.wts file!')
if __name__ == '__main__':
main()

504
real-esrgan/logging.h Normal file
View File

@ -0,0 +1,504 @@
/*
* Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENSORRT_LOGGING_H
#define TENSORRT_LOGGING_H
#include "NvInferRuntimeCommon.h"
#include <cassert>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <ostream>
#include <sstream>
#include <string>
#include "macros.h"
using Severity = nvinfer1::ILogger::Severity;
class LogStreamConsumerBuffer : public std::stringbuf
{
public:
LogStreamConsumerBuffer(std::ostream& stream, const std::string& prefix, bool shouldLog)
: mOutput(stream)
, mPrefix(prefix)
, mShouldLog(shouldLog)
{
}
LogStreamConsumerBuffer(LogStreamConsumerBuffer&& other)
: mOutput(other.mOutput)
{
}
~LogStreamConsumerBuffer()
{
// std::streambuf::pbase() gives a pointer to the beginning of the buffered part of the output sequence
// std::streambuf::pptr() gives a pointer to the current position of the output sequence
// if the pointer to the beginning is not equal to the pointer to the current position,
// call putOutput() to log the output to the stream
if (pbase() != pptr())
{
putOutput();
}
}
// synchronizes the stream buffer and returns 0 on success
// synchronizing the stream buffer consists of inserting the buffer contents into the stream,
// resetting the buffer and flushing the stream
virtual int sync()
{
putOutput();
return 0;
}
void putOutput()
{
if (mShouldLog)
{
// prepend timestamp
std::time_t timestamp = std::time(nullptr);
tm* tm_local = std::localtime(&timestamp);
std::cout << "[";
std::cout << std::setw(2) << std::setfill('0') << 1 + tm_local->tm_mon << "/";
std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_mday << "/";
std::cout << std::setw(4) << std::setfill('0') << 1900 + tm_local->tm_year << "-";
std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_hour << ":";
std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_min << ":";
std::cout << std::setw(2) << std::setfill('0') << tm_local->tm_sec << "] ";
// std::stringbuf::str() gets the string contents of the buffer
// insert the buffer contents pre-appended by the appropriate prefix into the stream
mOutput << mPrefix << str();
// set the buffer to empty
str("");
// flush the stream
mOutput.flush();
}
}
void setShouldLog(bool shouldLog)
{
mShouldLog = shouldLog;
}
private:
std::ostream& mOutput;
std::string mPrefix;
bool mShouldLog;
};
//!
//! \class LogStreamConsumerBase
//! \brief Convenience object used to initialize LogStreamConsumerBuffer before std::ostream in LogStreamConsumer
//!
class LogStreamConsumerBase
{
public:
LogStreamConsumerBase(std::ostream& stream, const std::string& prefix, bool shouldLog)
: mBuffer(stream, prefix, shouldLog)
{
}
protected:
LogStreamConsumerBuffer mBuffer;
};
//!
//! \class LogStreamConsumer
//! \brief Convenience object used to facilitate use of C++ stream syntax when logging messages.
//! Order of base classes is LogStreamConsumerBase and then std::ostream.
//! This is because the LogStreamConsumerBase class is used to initialize the LogStreamConsumerBuffer member field
//! in LogStreamConsumer and then the address of the buffer is passed to std::ostream.
//! This is necessary to prevent the address of an uninitialized buffer from being passed to std::ostream.
//! Please do not change the order of the parent classes.
//!
class LogStreamConsumer : protected LogStreamConsumerBase, public std::ostream
{
public:
//! \brief Creates a LogStreamConsumer which logs messages with level severity.
//! Reportable severity determines if the messages are severe enough to be logged.
LogStreamConsumer(Severity reportableSeverity, Severity severity)
: LogStreamConsumerBase(severityOstream(severity), severityPrefix(severity), severity <= reportableSeverity)
, std::ostream(&mBuffer) // links the stream buffer with the stream
, mShouldLog(severity <= reportableSeverity)
, mSeverity(severity)
{
}
LogStreamConsumer(LogStreamConsumer&& other)
: LogStreamConsumerBase(severityOstream(other.mSeverity), severityPrefix(other.mSeverity), other.mShouldLog)
, std::ostream(&mBuffer) // links the stream buffer with the stream
, mShouldLog(other.mShouldLog)
, mSeverity(other.mSeverity)
{
}
void setReportableSeverity(Severity reportableSeverity)
{
mShouldLog = mSeverity <= reportableSeverity;
mBuffer.setShouldLog(mShouldLog);
}
private:
static std::ostream& severityOstream(Severity severity)
{
return severity >= Severity::kINFO ? std::cout : std::cerr;
}
static std::string severityPrefix(Severity severity)
{
switch (severity)
{
case Severity::kINTERNAL_ERROR: return "[F] ";
case Severity::kERROR: return "[E] ";
case Severity::kWARNING: return "[W] ";
case Severity::kINFO: return "[I] ";
case Severity::kVERBOSE: return "[V] ";
default: assert(0); return "";
}
}
bool mShouldLog;
Severity mSeverity;
};
//! \class Logger
//!
//! \brief Class which manages logging of TensorRT tools and samples
//!
//! \details This class provides a common interface for TensorRT tools and samples to log information to the console,
//! and supports logging two types of messages:
//!
//! - Debugging messages with an associated severity (info, warning, error, or internal error/fatal)
//! - Test pass/fail messages
//!
//! The advantage of having all samples use this class for logging as opposed to emitting directly to stdout/stderr is
//! that the logic for controlling the verbosity and formatting of sample output is centralized in one location.
//!
//! In the future, this class could be extended to support dumping test results to a file in some standard format
//! (for example, JUnit XML), and providing additional metadata (e.g. timing the duration of a test run).
//!
//! TODO: For backwards compatibility with existing samples, this class inherits directly from the nvinfer1::ILogger
//! interface, which is problematic since there isn't a clean separation between messages coming from the TensorRT
//! library and messages coming from the sample.
//!
//! In the future (once all samples are updated to use Logger::getTRTLogger() to access the ILogger) we can refactor the
//! class to eliminate the inheritance and instead make the nvinfer1::ILogger implementation a member of the Logger
//! object.
class Logger : public nvinfer1::ILogger
{
public:
Logger(Severity severity = Severity::kWARNING)
: mReportableSeverity(severity)
{
}
//!
//! \enum TestResult
//! \brief Represents the state of a given test
//!
enum class TestResult
{
kRUNNING, //!< The test is running
kPASSED, //!< The test passed
kFAILED, //!< The test failed
kWAIVED //!< The test was waived
};
//!
//! \brief Forward-compatible method for retrieving the nvinfer::ILogger associated with this Logger
//! \return The nvinfer1::ILogger associated with this Logger
//!
//! TODO Once all samples are updated to use this method to register the logger with TensorRT,
//! we can eliminate the inheritance of Logger from ILogger
//!
nvinfer1::ILogger& getTRTLogger()
{
return *this;
}
//!
//! \brief Implementation of the nvinfer1::ILogger::log() virtual method
//!
//! Note samples should not be calling this function directly; it will eventually go away once we eliminate the
//! inheritance from nvinfer1::ILogger
//!
void log(Severity severity, const char* msg) TRT_NOEXCEPT override
{
LogStreamConsumer(mReportableSeverity, severity) << "[TRT] " << std::string(msg) << std::endl;
}
//!
//! \brief Method for controlling the verbosity of logging output
//!
//! \param severity The logger will only emit messages that have severity of this level or higher.
//!
void setReportableSeverity(Severity severity)
{
mReportableSeverity = severity;
}
//!
//! \brief Opaque handle that holds logging information for a particular test
//!
//! This object is an opaque handle to information used by the Logger to print test results.
//! The sample must call Logger::defineTest() in order to obtain a TestAtom that can be used
//! with Logger::reportTest{Start,End}().
//!
class TestAtom
{
public:
TestAtom(TestAtom&&) = default;
private:
friend class Logger;
TestAtom(bool started, const std::string& name, const std::string& cmdline)
: mStarted(started)
, mName(name)
, mCmdline(cmdline)
{
}
bool mStarted;
std::string mName;
std::string mCmdline;
};
//!
//! \brief Define a test for logging
//!
//! \param[in] name The name of the test. This should be a string starting with
//! "TensorRT" and containing dot-separated strings containing
//! the characters [A-Za-z0-9_].
//! For example, "TensorRT.sample_googlenet"
//! \param[in] cmdline The command line used to reproduce the test
//
//! \return a TestAtom that can be used in Logger::reportTest{Start,End}().
//!
static TestAtom defineTest(const std::string& name, const std::string& cmdline)
{
return TestAtom(false, name, cmdline);
}
//!
//! \brief A convenience overloaded version of defineTest() that accepts an array of command-line arguments
//! as input
//!
//! \param[in] name The name of the test
//! \param[in] argc The number of command-line arguments
//! \param[in] argv The array of command-line arguments (given as C strings)
//!
//! \return a TestAtom that can be used in Logger::reportTest{Start,End}().
static TestAtom defineTest(const std::string& name, int argc, char const* const* argv)
{
auto cmdline = genCmdlineString(argc, argv);
return defineTest(name, cmdline);
}
//!
//! \brief Report that a test has started.
//!
//! \pre reportTestStart() has not been called yet for the given testAtom
//!
//! \param[in] testAtom The handle to the test that has started
//!
static void reportTestStart(TestAtom& testAtom)
{
reportTestResult(testAtom, TestResult::kRUNNING);
assert(!testAtom.mStarted);
testAtom.mStarted = true;
}
//!
//! \brief Report that a test has ended.
//!
//! \pre reportTestStart() has been called for the given testAtom
//!
//! \param[in] testAtom The handle to the test that has ended
//! \param[in] result The result of the test. Should be one of TestResult::kPASSED,
//! TestResult::kFAILED, TestResult::kWAIVED
//!
static void reportTestEnd(const TestAtom& testAtom, TestResult result)
{
assert(result != TestResult::kRUNNING);
assert(testAtom.mStarted);
reportTestResult(testAtom, result);
}
static int reportPass(const TestAtom& testAtom)
{
reportTestEnd(testAtom, TestResult::kPASSED);
return EXIT_SUCCESS;
}
static int reportFail(const TestAtom& testAtom)
{
reportTestEnd(testAtom, TestResult::kFAILED);
return EXIT_FAILURE;
}
static int reportWaive(const TestAtom& testAtom)
{
reportTestEnd(testAtom, TestResult::kWAIVED);
return EXIT_SUCCESS;
}
static int reportTest(const TestAtom& testAtom, bool pass)
{
return pass ? reportPass(testAtom) : reportFail(testAtom);
}
Severity getReportableSeverity() const
{
return mReportableSeverity;
}
private:
//!
//! \brief returns an appropriate string for prefixing a log message with the given severity
//!
static const char* severityPrefix(Severity severity)
{
switch (severity)
{
case Severity::kINTERNAL_ERROR: return "[F] ";
case Severity::kERROR: return "[E] ";
case Severity::kWARNING: return "[W] ";
case Severity::kINFO: return "[I] ";
case Severity::kVERBOSE: return "[V] ";
default: assert(0); return "";
}
}
//!
//! \brief returns an appropriate string for prefixing a test result message with the given result
//!
static const char* testResultString(TestResult result)
{
switch (result)
{
case TestResult::kRUNNING: return "RUNNING";
case TestResult::kPASSED: return "PASSED";
case TestResult::kFAILED: return "FAILED";
case TestResult::kWAIVED: return "WAIVED";
default: assert(0); return "";
}
}
//!
//! \brief returns an appropriate output stream (cout or cerr) to use with the given severity
//!
static std::ostream& severityOstream(Severity severity)
{
return severity >= Severity::kINFO ? std::cout : std::cerr;
}
//!
//! \brief method that implements logging test results
//!
static void reportTestResult(const TestAtom& testAtom, TestResult result)
{
severityOstream(Severity::kINFO) << "&&&& " << testResultString(result) << " " << testAtom.mName << " # "
<< testAtom.mCmdline << std::endl;
}
//!
//! \brief generate a command line string from the given (argc, argv) values
//!
static std::string genCmdlineString(int argc, char const* const* argv)
{
std::stringstream ss;
for (int i = 0; i < argc; i++)
{
if (i > 0)
ss << " ";
ss << argv[i];
}
return ss.str();
}
Severity mReportableSeverity;
};
namespace
{
//!
//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kVERBOSE
//!
//! Example usage:
//!
//! LOG_VERBOSE(logger) << "hello world" << std::endl;
//!
inline LogStreamConsumer LOG_VERBOSE(const Logger& logger)
{
return LogStreamConsumer(logger.getReportableSeverity(), Severity::kVERBOSE);
}
//!
//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kINFO
//!
//! Example usage:
//!
//! LOG_INFO(logger) << "hello world" << std::endl;
//!
inline LogStreamConsumer LOG_INFO(const Logger& logger)
{
return LogStreamConsumer(logger.getReportableSeverity(), Severity::kINFO);
}
//!
//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kWARNING
//!
//! Example usage:
//!
//! LOG_WARN(logger) << "hello world" << std::endl;
//!
inline LogStreamConsumer LOG_WARN(const Logger& logger)
{
return LogStreamConsumer(logger.getReportableSeverity(), Severity::kWARNING);
}
//!
//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kERROR
//!
//! Example usage:
//!
//! LOG_ERROR(logger) << "hello world" << std::endl;
//!
inline LogStreamConsumer LOG_ERROR(const Logger& logger)
{
return LogStreamConsumer(logger.getReportableSeverity(), Severity::kERROR);
}
//!
//! \brief produces a LogStreamConsumer object that can be used to log messages of severity kINTERNAL_ERROR
// ("fatal" severity)
//!
//! Example usage:
//!
//! LOG_FATAL(logger) << "hello world" << std::endl;
//!
inline LogStreamConsumer LOG_FATAL(const Logger& logger)
{
return LogStreamConsumer(logger.getReportableSeverity(), Severity::kINTERNAL_ERROR);
}
} // anonymous namespace
#endif // TENSORRT_LOGGING_H

27
real-esrgan/macros.h Normal file
View File

@ -0,0 +1,27 @@
#ifndef __MACROS_H
#define __MACROS_H
#ifdef API_EXPORTS
#if defined(_MSC_VER)
#define API __declspec(dllexport)
#else
#define API __attribute__((visibility("default")))
#endif
#else
#if defined(_MSC_VER)
#define API __declspec(dllimport)
#else
#define API
#endif
#endif // API_EXPORTS
#if NV_TENSORRT_MAJOR >= 8
#define TRT_NOEXCEPT noexcept
#define TRT_CONST_ENQUEUE const
#else
#define TRT_NOEXCEPT
#define TRT_CONST_ENQUEUE
#endif
#endif // __MACROS_H

View File

@ -0,0 +1,54 @@
#include "cuda_utils.h"
using namespace std;
// postprocess (NCHW->NHWC, RGB->BGR, *255, ROUND, uint8)
__global__ void postprocess_kernel(uint8_t* output, float* input,
const int batchSize, const int height, const int width, const int channel,
const int thread_count)
{
int index = threadIdx.x + blockIdx.x * blockDim.x;
if (index >= thread_count) return;
const int c_idx = index % channel;
int idx = index / channel;
const int w_idx = idx % width;
idx /= width;
const int h_idx = idx % height;
const int b_idx = idx / height;
int g_idx = b_idx * height * width * channel + (2 - c_idx)* height * width + h_idx * width + w_idx;
float tt = input[g_idx] * 255.f;
if (tt > 255)
tt = 255;
output[index] = tt;
}
void postprocess(uint8_t* output, float*input, int batchSize, int height, int width, int channel, cudaStream_t stream)
{
int thread_count = batchSize * height * width * channel;
int block = 512;
int grid = (thread_count - 1) / block + 1;
postprocess_kernel << <grid, block, 0, stream >> > (output, input, batchSize, height, width, channel, thread_count);
}
#include "postprocess.hpp"
namespace nvinfer1
{
int PostprocessPluginV2::enqueue(int batchSize, const void* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept
{
float* input = (float*)inputs[0];
uint8_t* output = (uint8_t*)outputs[0];
const int H = mPostprocess.H;
const int W = mPostprocess.W;
const int C = mPostprocess.C;
postprocess(output, input, batchSize, H, W, C, stream);
return 0;
}
}

206
real-esrgan/postprocess.hpp Normal file
View File

@ -0,0 +1,206 @@
#pragma once
#include <NvInfer.h>
#include <fstream>
#include "macros.h"
#include <assert.h>
struct Postprocess {
int N;
int C;
int H;
int W;
};
namespace nvinfer1
{
class PostprocessPluginV2 : public IPluginV2IOExt
{
public:
PostprocessPluginV2(const Postprocess& arg)
{
mPostprocess = arg;
}
PostprocessPluginV2(const void* data, size_t length)
{
const char* d = static_cast<const char*>(data);
const char* const a = d;
mPostprocess = read<Postprocess>(d);
assert(d == a + length);
}
PostprocessPluginV2() = delete;
virtual ~PostprocessPluginV2() {}
public:
int getNbOutputs() const noexcept override
{
return 1;
}
Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) noexcept override
{
return Dims3(mPostprocess.H, mPostprocess.W, mPostprocess.C);
}
int initialize() noexcept override
{
return 0;
}
void terminate() noexcept override
{
}
size_t getWorkspaceSize(int maxBatchSize) const noexcept override
{
return 0;
}
int enqueue(int batchSize, const void* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept override;
size_t getSerializationSize() const noexcept override
{
size_t serializationSize = 0;
serializationSize += sizeof(mPostprocess);
return serializationSize;
}
void serialize(void* buffer) const noexcept override
{
char* d = static_cast<char*>(buffer);
const char* const a = d;
write(d, mPostprocess);
assert(d == a + getSerializationSize());
}
void configurePlugin(const PluginTensorDesc* in, int nbInput, const PluginTensorDesc* out, int nbOutput) noexcept override
{
}
//! The combination of kLINEAR + kINT8/kHALF/kFLOAT is supported.
bool supportsFormatCombination(int pos, const PluginTensorDesc* inOut, int nbInputs, int nbOutputs) const noexcept override
{
assert(nbInputs == 1 && nbOutputs == 1 && pos < nbInputs + nbOutputs);
bool condition = inOut[pos].format == TensorFormat::kLINEAR;
condition &= inOut[pos].type != DataType::kINT32;
condition &= inOut[pos].type == inOut[0].type;
return condition;
}
DataType getOutputDataType(int index, const DataType* inputTypes, int nbInputs) const noexcept override
{
assert(inputTypes && nbInputs == 1);
return DataType::kFLOAT; //
}
const char* getPluginType() const noexcept override
{
return "postprocess";
}
const char* getPluginVersion() const noexcept override
{
return "1";
}
void destroy() noexcept override
{
delete this;
}
IPluginV2Ext* clone() const noexcept override
{
PostprocessPluginV2* plugin = new PostprocessPluginV2(*this);
return plugin;
}
void setPluginNamespace(const char* libNamespace) noexcept override
{
mNamespace = libNamespace;
}
const char* getPluginNamespace() const noexcept override
{
return mNamespace.data();
}
bool isOutputBroadcastAcrossBatch(int outputIndex, const bool* inputIsBroadcasted, int nbInputs) const noexcept override
{
return false;
}
bool canBroadcastInputAcrossBatch(int inputIndex) const noexcept override
{
return false;
}
private:
template <typename T>
void write(char*& buffer, const T& val) const
{
*reinterpret_cast<T*>(buffer) = val;
buffer += sizeof(T);
}
template <typename T>
T read(const char*& buffer) const
{
T val = *reinterpret_cast<const T*>(buffer);
buffer += sizeof(T);
return val;
}
private:
Postprocess mPostprocess;
std::string mNamespace;
};
class PostprocessPluginV2Creator : public IPluginCreator
{
public:
const char* getPluginName() const noexcept override
{
return "postprocess";
}
const char* getPluginVersion() const noexcept override
{
return "1";
}
const PluginFieldCollection* getFieldNames() noexcept override
{
return nullptr;
}
IPluginV2* createPlugin(const char* name, const PluginFieldCollection* fc) noexcept override
{
PostprocessPluginV2* plugin = new PostprocessPluginV2(*(Postprocess*)fc);
mPluginName = name;
return plugin;
}
IPluginV2* deserializePlugin(const char* name, const void* serialData, size_t serialLength) noexcept override
{
auto plugin = new PostprocessPluginV2(serialData, serialLength);
mPluginName = name;
return plugin;
}
void setPluginNamespace(const char* libNamespace) noexcept override
{
mNamespace = libNamespace;
}
const char* getPluginNamespace() const noexcept override
{
return mNamespace.c_str();
}
private:
std::string mNamespace;
std::string mPluginName;
};
REGISTER_TENSORRT_PLUGIN(PostprocessPluginV2Creator);
};

51
real-esrgan/preprocess.cu Normal file
View File

@ -0,0 +1,51 @@
#include "cuda_utils.h"
using namespace std;
// preprocess (NHWC->NCHW, BGR->RGB, [0, 255]->[0, 1](Normalize))
__global__ void preprocess_kernel(float* output, uint8_t* input,
const int batchSize, const int height, const int width, const int channel,
const int thread_count)
{
int index = threadIdx.x + blockIdx.x * blockDim.x;
if (index >= thread_count) return;
const int w_idx = index % width;
int idx = index / width;
const int h_idx = idx % height;
idx /= height;
const int c_idx = idx % channel;
const int b_idx = idx / channel;
int g_idx = b_idx * height * width * channel + h_idx * width * channel + w_idx * channel + 2 - c_idx;
output[index] = input[g_idx] / 255.f;
}
void preprocess(float* output, uint8_t*input, int batchSize, int height, int width, int channel, cudaStream_t stream)
{
int thread_count = batchSize * height * width * channel;
int block = 512;
int grid = (thread_count - 1) / block + 1;
preprocess_kernel << <grid, block, 0, stream >> > (output, input, batchSize, height, width, channel, thread_count);
}
#include "preprocess.hpp"
namespace nvinfer1
{
int PreprocessPluginV2::enqueue(int batchSize, const void* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept
{
uint8_t* input = (uint8_t*)inputs[0];
float* output = (float*)outputs[0];
const int H = mPreprocess.H;
const int W = mPreprocess.W;
const int C = mPreprocess.C;
preprocess(output, input, batchSize, H, W, C, stream);
return 0;
}
}

206
real-esrgan/preprocess.hpp Normal file
View File

@ -0,0 +1,206 @@
#pragma once
#include <NvInfer.h>
#include <fstream>
#include "macros.h"
#include <assert.h>
struct Preprocess {
int N;
int C;
int H;
int W;
};
namespace nvinfer1
{
class PreprocessPluginV2 : public IPluginV2IOExt
{
public:
PreprocessPluginV2(const Preprocess& arg)
{
mPreprocess = arg;
}
PreprocessPluginV2(const void* data, size_t length)
{
const char* d = static_cast<const char*>(data);
const char* const a = d;
mPreprocess = read<Preprocess>(d);
assert(d == a + length);
}
PreprocessPluginV2() = delete;
virtual ~PreprocessPluginV2() {}
public:
int getNbOutputs() const noexcept override
{
return 1;
}
Dims getOutputDimensions(int index, const Dims* inputs, int nbInputDims) noexcept override
{
return Dims3(mPreprocess.C, mPreprocess.H, mPreprocess.W);
}
int initialize() noexcept override
{
return 0;
}
void terminate() noexcept override
{
}
size_t getWorkspaceSize(int maxBatchSize) const noexcept override
{
return 0;
}
int enqueue(int batchSize, const void* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept override;
size_t getSerializationSize() const noexcept override
{
size_t serializationSize = 0;
serializationSize += sizeof(mPreprocess);
return serializationSize;
}
void serialize(void* buffer) const noexcept override
{
char* d = static_cast<char*>(buffer);
const char* const a = d;
write(d, mPreprocess);
assert(d == a + getSerializationSize());
}
void configurePlugin(const PluginTensorDesc* in, int nbInput, const PluginTensorDesc* out, int nbOutput) noexcept override
{
}
//! The combination of kLINEAR + kINT8/kHALF/kFLOAT is supported.
bool supportsFormatCombination(int pos, const PluginTensorDesc* inOut, int nbInputs, int nbOutputs) const noexcept override
{
assert(nbInputs == 1 && nbOutputs == 1 && pos < nbInputs + nbOutputs);
bool condition = inOut[pos].format == TensorFormat::kLINEAR;
condition &= inOut[pos].type != DataType::kINT32;
condition &= inOut[pos].type == inOut[0].type;
return condition;
}
DataType getOutputDataType(int index, const DataType* inputTypes, int nbInputs) const noexcept override
{
assert(inputTypes && nbInputs == 1);
return DataType::kFLOAT; //
}
const char* getPluginType() const noexcept override
{
return "preprocess";
}
const char* getPluginVersion() const noexcept override
{
return "1";
}
void destroy() noexcept override
{
delete this;
}
IPluginV2Ext* clone() const noexcept override
{
PreprocessPluginV2* plugin = new PreprocessPluginV2(*this);
return plugin;
}
void setPluginNamespace(const char* libNamespace) noexcept override
{
mNamespace = libNamespace;
}
const char* getPluginNamespace() const noexcept override
{
return mNamespace.data();
}
bool isOutputBroadcastAcrossBatch(int outputIndex, const bool* inputIsBroadcasted, int nbInputs) const noexcept override
{
return false;
}
bool canBroadcastInputAcrossBatch(int inputIndex) const noexcept override
{
return false;
}
private:
template <typename T>
void write(char*& buffer, const T& val) const
{
*reinterpret_cast<T*>(buffer) = val;
buffer += sizeof(T);
}
template <typename T>
T read(const char*& buffer) const
{
T val = *reinterpret_cast<const T*>(buffer);
buffer += sizeof(T);
return val;
}
private:
Preprocess mPreprocess;
std::string mNamespace;
};
class PreprocessPluginV2Creator : public IPluginCreator
{
public:
const char* getPluginName() const noexcept override
{
return "preprocess";
}
const char* getPluginVersion() const noexcept override
{
return "1";
}
const PluginFieldCollection* getFieldNames() noexcept override
{
return nullptr;
}
IPluginV2* createPlugin(const char* name, const PluginFieldCollection* fc) noexcept override
{
PreprocessPluginV2* plugin = new PreprocessPluginV2(*(Preprocess*)fc);
mPluginName = name;
return plugin;
}
IPluginV2* deserializePlugin(const char* name, const void* serialData, size_t serialLength) noexcept override
{
auto plugin = new PreprocessPluginV2(serialData, serialLength);
mPluginName = name;
return plugin;
}
void setPluginNamespace(const char* libNamespace) noexcept override
{
mNamespace = libNamespace;
}
const char* getPluginNamespace() const noexcept override
{
return mNamespace.c_str();
}
private:
std::string mNamespace;
std::string mPluginName;
};
REGISTER_TENSORRT_PLUGIN(PreprocessPluginV2Creator);
};

285
real-esrgan/real-esrgan.cpp Normal file
View File

@ -0,0 +1,285 @@
#include "cuda_utils.h"
#include "common.hpp"
#include "preprocess.hpp"// preprocess plugin
#include "postprocess.hpp"// postprocess plugin
#include "logging.h"
#include "utils.h"
#include <unistd.h>//access()
#define DEVICE 0 // GPU id
#define BATCH_SIZE 1
// stuff we know about the network and the input/output blobs
static const int PRECISION_MODE = 32; // fp32 : 32, fp16 : 16
static const bool VISUALIZATION = true;
static const int INPUT_H = 640;
static const int INPUT_W = 448;
static const int INPUT_C = 3;
static const int OUT_SCALE = 4;
static const int OUTPUT_SIZE = INPUT_C * INPUT_H * OUT_SCALE * INPUT_W * OUT_SCALE;
const char* INPUT_BLOB_NAME = "data";
const char* OUTPUT_BLOB_NAME = "prob";
static Logger gLogger;
// Creat the engine using only the API and not any parser.
ICudaEngine* build_engine(unsigned int maxBatchSize, IBuilder* builder, IBuilderConfig* config, DataType dt, std::string& wts_name) {
INetworkDefinition* network = builder->createNetworkV2(0U);
// Create input tensor of shape {INPUT_H, INPUT_W, INPUT_C} with name INPUT_BLOB_NAME
ITensor* data = network->addInput(INPUT_BLOB_NAME, dt, Dims3{ INPUT_H, INPUT_W, INPUT_C });
assert(data);
std::map<std::string, Weights> weightMap = loadWeights(wts_name);
// Custom preprocess (NHWC->NCHW, BGR->RGB, [0, 255]->[0, 1](Normalize))
Preprocess preprocess{ maxBatchSize, INPUT_C, INPUT_H, INPUT_W };
IPluginCreator* preprocess_creator = getPluginRegistry()->getPluginCreator("preprocess", "1");
IPluginV2 *preprocess_plugin = preprocess_creator->createPlugin("preprocess_plugin", (PluginFieldCollection*)&preprocess);
IPluginV2Layer* preprocess_layer = network->addPluginV2(&data, 1, *preprocess_plugin);
preprocess_layer->setName("preprocess_layer");
ITensor* prep = preprocess_layer->getOutput(0);
// conv_first
IConvolutionLayer* conv_first = network->addConvolutionNd(*prep, 64, DimsHW{ 3, 3 }, weightMap["conv_first.weight"], weightMap["conv_first.bias"]);
conv_first->setStrideNd(DimsHW{ 1, 1 });
conv_first->setPaddingNd(DimsHW{ 1, 1 });
conv_first->setName("conv_first");
ITensor* feat = conv_first->getOutput(0);
// conv_body
ITensor* body_feat = RRDB(network, weightMap, feat, "body.0");
for (int idx = 1; idx < 23; idx++) {
body_feat = RRDB(network, weightMap, body_feat, "body." + std::to_string(idx));
}
IConvolutionLayer* conv_body = network->addConvolutionNd(*body_feat, 64, DimsHW{ 3, 3 }, weightMap["conv_body.weight"], weightMap["conv_body.bias"]);
conv_body->setStrideNd(DimsHW{ 1, 1 });
conv_body->setPaddingNd(DimsHW{ 1, 1 });
IElementWiseLayer* ew1 = network->addElementWise(*feat, *conv_body->getOutput(0), ElementWiseOperation::kSUM);
feat = ew1->getOutput(0);
//upsample
IResizeLayer* interpolate_nearest = network->addResize(*feat);
float sclaes1[] = { 1, 2, 2 };
interpolate_nearest->setScales(sclaes1, 3);
interpolate_nearest->setResizeMode(ResizeMode::kNEAREST);
IConvolutionLayer* conv_up1 = network->addConvolutionNd(*interpolate_nearest->getOutput(0), 64, DimsHW{ 3, 3 }, weightMap["conv_up1.weight"], weightMap["conv_up1.bias"]);
conv_up1->setStrideNd(DimsHW{ 1, 1 });
conv_up1->setPaddingNd(DimsHW{ 1, 1 });
IActivationLayer* leaky_relu_1 = network->addActivation(*conv_up1->getOutput(0), ActivationType::kLEAKY_RELU);
leaky_relu_1->setAlpha(0.2);
IResizeLayer* interpolate_nearest2 = network->addResize(*leaky_relu_1->getOutput(0));
float sclaes2[] = { 1, 2, 2 };
interpolate_nearest2->setScales(sclaes2, 3);
interpolate_nearest2->setResizeMode(ResizeMode::kNEAREST);
IConvolutionLayer* conv_up2 = network->addConvolutionNd(*interpolate_nearest2->getOutput(0), 64, DimsHW{ 3, 3 }, weightMap["conv_up2.weight"], weightMap["conv_up2.bias"]);
conv_up2->setStrideNd(DimsHW{ 1, 1 });
conv_up2->setPaddingNd(DimsHW{ 1, 1 });
IActivationLayer* leaky_relu_2 = network->addActivation(*conv_up2->getOutput(0), ActivationType::kLEAKY_RELU);
leaky_relu_2->setAlpha(0.2);
IConvolutionLayer* conv_hr = network->addConvolutionNd(*leaky_relu_2->getOutput(0), 64, DimsHW{ 3, 3 }, weightMap["conv_hr.weight"], weightMap["conv_hr.bias"]);
conv_hr->setStrideNd(DimsHW{ 1, 1 });
conv_hr->setPaddingNd(DimsHW{ 1, 1 });
IActivationLayer* leaky_relu_hr = network->addActivation(*conv_hr->getOutput(0), ActivationType::kLEAKY_RELU);
leaky_relu_hr->setAlpha(0.2);
IConvolutionLayer* conv_last = network->addConvolutionNd(*leaky_relu_hr->getOutput(0), 3, DimsHW{ 3, 3 }, weightMap["conv_last.weight"], weightMap["conv_last.bias"]);
conv_last->setStrideNd(DimsHW{ 1, 1 });
conv_last->setPaddingNd(DimsHW{ 1, 1 });
ITensor* out = conv_last->getOutput(0);
// Custom postprocess (RGB -> BGR, NCHW->NHWC, *255, ROUND, uint8)
Postprocess postprocess{ maxBatchSize, out->getDimensions().d[0], out->getDimensions().d[1], out->getDimensions().d[2] };
IPluginCreator* postprocess_creator = getPluginRegistry()->getPluginCreator("postprocess", "1");
IPluginV2 *postprocess_plugin = postprocess_creator->createPlugin("postprocess_plugin", (PluginFieldCollection*)&postprocess);
IPluginV2Layer* postprocess_layer = network->addPluginV2(&out, 1, *postprocess_plugin);
postprocess_layer->setName("postprocess_layer");
ITensor* final_tensor = postprocess_layer->getOutput(0);
final_tensor->setName(OUTPUT_BLOB_NAME);
network->markOutput(*final_tensor);
// Build engine
builder->setMaxBatchSize(maxBatchSize);
config->setMaxWorkspaceSize(16 * (1 << 20)); // 16MB
if (PRECISION_MODE == 16) {
std::cout << "==== precision f16 ====" << std::endl << std::endl;
config->setFlag(BuilderFlag::kFP16);
}
else {
std::cout << "==== precision f32 ====" << std::endl << std::endl;
}
std::cout << "Building engine, please wait for a while..." << std::endl;
ICudaEngine* engine = builder->buildEngineWithConfig(*network, *config);
std::cout << "Build engine successfully!" << std::endl;
// Don't need the network any more
delete network;
// Release host memory
for (auto& mem : weightMap)
{
free((void*)(mem.second.values));
}
return engine;
}
void APIToModel(unsigned int maxBatchSize, IHostMemory** modelStream, std::string& wts_name) {
// Create builder
IBuilder* builder = createInferBuilder(gLogger);
IBuilderConfig* config = builder->createBuilderConfig();
// Create model to populate the network, then set the outputs and create an engine
ICudaEngine *engine = build_engine(maxBatchSize, builder, config, DataType::kFLOAT, wts_name);
assert(engine != nullptr);
// Serialize the engine
(*modelStream) = engine->serialize();
// Close everything down
delete engine;
delete builder;
delete config;
}
void doInference(IExecutionContext& context, cudaStream_t& stream, void **buffers, uint8_t* output, int batchSize) {
// infer on the batch asynchronously, and DMA output back to host
context.enqueue(batchSize, buffers, stream, nullptr);
CUDA_CHECK(cudaMemcpyAsync(output, buffers[1], batchSize * OUTPUT_SIZE * sizeof(uint8_t), cudaMemcpyDeviceToHost, stream));
cudaStreamSynchronize(stream);
}
bool parse_args(int argc, char** argv, std::string& wts, std::string& engine, std::string& img_dir) {
if (argc < 4) return false;
if (std::string(argv[1]) == "-s" && argc == 4) {
wts = std::string(argv[2]);
engine = std::string(argv[3]);
}
else if (std::string(argv[1]) == "-d" && argc == 4) {
engine = std::string(argv[2]);
img_dir = std::string(argv[3]);
}
else {
return false;
}
return true;
}
// ./real-esrgan -s ./real-esrgan.wts ./real-esrgan_f32.engine
// ./real-esrgan -d ./real-esrgan_f32.engine ../samples
int main(int argc, char** argv) {
std::string wts_name = "";
std::string engine_name = "";
std::string img_dir;
if (!parse_args(argc, argv, wts_name, engine_name, img_dir)) {
std::cerr << "arguments not right!" << std::endl;
std::cerr << "./real-esrgan -s [.wts] [.engine] // serialize model to plan file" << std::endl;
std::cerr << "./real-esrgan -d [.engine] ../samples // deserialize plan file and run inference" << std::endl;
return -1;
}
// create a model using the API directly and serialize it to a stream
if (!wts_name.empty()) {
IHostMemory* modelStream{ nullptr };
APIToModel(BATCH_SIZE, &modelStream, wts_name);
assert(modelStream != nullptr);
std::ofstream p(engine_name, std::ios::binary);
if (!p) {
std::cerr << "could not open plan output file" << std::endl;
return -1;
}
p.write(reinterpret_cast<const char*>(modelStream->data()), modelStream->size());
delete modelStream;
return 0;
}
// deserialize the .engine and run inference
std::ifstream file(engine_name, std::ios::binary);
if (!file.good()) {
std::cerr << "read " << engine_name << " error!" << std::endl;
return -1;
}
char *trtModelStream = nullptr;
size_t size = 0;
file.seekg(0, file.end);
size = file.tellg();
file.seekg(0, file.beg);
trtModelStream = new char[size];
assert(trtModelStream);
file.read(trtModelStream, size);
file.close();
std::vector<std::string> file_names;
if (read_files_in_dir(img_dir.c_str(), file_names) < 0) {
std::cerr << "read_files_in_dir failed." << std::endl;
return -1;
}
IRuntime* runtime = createInferRuntime(gLogger);
assert(runtime != nullptr);
ICudaEngine* engine = runtime->deserializeCudaEngine(trtModelStream, size);
assert(engine != nullptr);
IExecutionContext* context = engine->createExecutionContext();
assert(context != nullptr);
delete[] trtModelStream;
assert(engine->getNbBindings() == 2);
void* buffers[2];
// 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 inputIndex = engine->getBindingIndex(INPUT_BLOB_NAME);
const int outputIndex = engine->getBindingIndex(OUTPUT_BLOB_NAME);
assert(inputIndex == 0);
assert(outputIndex == 1);
// Create GPU buffers on device
CUDA_CHECK(cudaMalloc(&buffers[inputIndex], BATCH_SIZE * INPUT_C * INPUT_H * INPUT_W * sizeof(uint8_t)));
CUDA_CHECK(cudaMalloc(&buffers[outputIndex], BATCH_SIZE * OUTPUT_SIZE * sizeof(uint8_t)));
std::vector<uint8_t> input(BATCH_SIZE * INPUT_H * INPUT_W * INPUT_C);
std::vector<uint8_t> outputs(BATCH_SIZE * OUTPUT_SIZE);
// Create stream
cudaStream_t stream;
CUDA_CHECK(cudaStreamCreate(&stream));
std::vector<cv::Mat> imgs_buffer(BATCH_SIZE);
for (int f = 0; f < (int)file_names.size(); f++) {
for (int b = 0; b < BATCH_SIZE; b++) {
cv::Mat img = cv::imread(img_dir + "/" + file_names[f]);
if (img.empty()) continue;
memcpy(input.data() + b * INPUT_H * INPUT_W * INPUT_C, img.data, INPUT_H * INPUT_W * INPUT_C);
}
CUDA_CHECK(cudaMemcpyAsync(buffers[inputIndex], input.data(), BATCH_SIZE * INPUT_C * INPUT_H * INPUT_W * sizeof(uint8_t), cudaMemcpyHostToDevice, stream));
// Run inference
auto start = std::chrono::system_clock::now();
doInference(*context, stream, (void**)buffers, outputs.data(), BATCH_SIZE);
auto end = std::chrono::system_clock::now();
std::cout << "inference time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;
}
cv::Mat frame = cv::Mat(INPUT_H * OUT_SCALE, INPUT_W * OUT_SCALE, CV_8UC3, outputs.data());
cv::imwrite("../_" + file_names[0] + ".png", frame);
if (VISUALIZATION) {
cv::imshow("result : " + file_names[0], frame);
cv::waitKey(0);
}
// Release stream and buffers
cudaStreamDestroy(stream);
CUDA_CHECK(cudaFree(buffers[inputIndex]));
CUDA_CHECK(cudaFree(buffers[outputIndex]));
// Destroy the engine
delete context;
delete engine;
delete runtime;
}

30
real-esrgan/utils.h Normal file
View File

@ -0,0 +1,30 @@
#ifndef TRTX_REAL_ESRGAN_UTILS_H_
#define TRTX_REAL_ESRGAN_UTILS_H_
#include <dirent.h>
#include <opencv2/opencv.hpp>
static inline int read_files_in_dir(const char *p_dir_name, std::vector<std::string> &file_names) {
DIR *p_dir = opendir(p_dir_name);
if (p_dir == nullptr) {
return -1;
}
struct dirent* p_file = nullptr;
while ((p_file = readdir(p_dir)) != nullptr) {
if (strcmp(p_file->d_name, ".") != 0 &&
strcmp(p_file->d_name, "..") != 0) {
//std::string cur_file_name(p_dir_name);
//cur_file_name += "/";
//cur_file_name += p_file->d_name;
std::string cur_file_name(p_file->d_name);
file_names.push_back(cur_file_name);
}
}
closedir(p_dir);
return 0;
}
#endif // TRTX_YOLOV5_UTILS_H_