Class RealESRGAN<T>
Real-ESRGAN (Real Enhanced Super-Resolution GAN) for image and video super-resolution.
public class RealESRGAN<T> : NeuralNetworkBase<T>, INeuralNetworkModel<T>, INeuralNetwork<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable
Type Parameters
TThe numeric type used for calculations (typically float or double).
- Inheritance
-
RealESRGAN<T>
- Implements
- Inherited Members
- Extension Methods
Remarks
Real-ESRGAN is a practical super-resolution model that uses: - RRDB (Residual in Residual Dense Block) generator for deep feature extraction - U-Net discriminator for adversarial training - Combined loss: L1 (pixel) + Perceptual (VGG) + GAN (adversarial) - Second-order degradation model for realistic training data
For Beginners: Real-ESRGAN upscales images and video frames to higher resolution while adding realistic details. It's one of the most practical super-resolution models.
The network works by:
- Extracting deep features from low-resolution input using RRDB blocks
- Upsampling using pixel shuffle (efficient sub-pixel convolution)
- Training with adversarial loss to add realistic textures
- Using perceptual loss to ensure visual quality
Example usage:
// Create architectures
var generatorArch = new NeuralNetworkArchitecture<double>(
inputType: InputType.ThreeDimensional,
inputHeight: 128, inputWidth: 128, inputDepth: 3);
var discriminatorArch = new NeuralNetworkArchitecture<double>(
inputType: InputType.ThreeDimensional,
inputHeight: 512, inputWidth: 512, inputDepth: 3);
// Create model with 4x upscaling
var model = new RealESRGAN<double>(
generatorArch, discriminatorArch,
InputType.ThreeDimensional,
scaleFactor: 4);
// Train
var (dLoss, gLoss) = model.TrainStep(lowResImages, highResTargets);
// Inference
var highRes = model.Upscale(lowResImage);
Reference: Wang et al., "Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data", ICCV 2021. https://arxiv.org/abs/2107.10833
Constructors
RealESRGAN(NeuralNetworkArchitecture<T>, NeuralNetworkArchitecture<T>, InputType, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>?, int, int, int, double, double, double, double)
Initializes a new instance of the Real-ESRGAN class.
public RealESRGAN(NeuralNetworkArchitecture<T> generatorArchitecture, NeuralNetworkArchitecture<T> discriminatorArchitecture, InputType inputType, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? generatorOptimizer = null, IGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>? discriminatorOptimizer = null, int scaleFactor = 4, int numRRDBBlocks = 23, int numFeatures = 64, double residualScale = 0.2, double l1Lambda = 1, double perceptualLambda = 1, double ganLambda = 0.1)
Parameters
generatorArchitectureNeuralNetworkArchitecture<T>Architecture for the RRDB-Net generator.
discriminatorArchitectureNeuralNetworkArchitecture<T>Architecture for the U-Net discriminator.
inputTypeInputTypeThe type of input data (typically ThreeDimensional for images).
generatorOptimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optional optimizer for the generator. Default: Adam with lr=0.0001, beta2=0.99.
discriminatorOptimizerIGradientBasedOptimizer<T, Tensor<T>, Tensor<T>>Optional optimizer for the discriminator. Default: Adam with lr=0.0001, beta2=0.99.
scaleFactorintUpscaling factor. Default: 4 (4x super-resolution).
numRRDBBlocksintNumber of RRDB blocks in generator. Default: 23 (Real-ESRGAN standard).
numFeaturesintNumber of feature channels. Default: 64.
residualScaledoubleResidual scaling factor. Default: 0.2 (Real-ESRGAN standard).
l1LambdadoubleL1 loss coefficient. Default: 1.0 (from Real-ESRGAN paper).
perceptualLambdadoublePerceptual loss coefficient. Default: 1.0 (from Real-ESRGAN paper).
ganLambdadoubleGAN loss coefficient. Default: 0.1 (from Real-ESRGAN paper).
Remarks
For Beginners: Create a Real-ESRGAN model with sensible defaults:
var model = new RealESRGAN<double>(generatorArch, discriminatorArch, InputType.ThreeDimensional);
Or customize for your needs:
// 2x upscaling with fewer blocks (faster but lower quality)
var model = new RealESRGAN<double>(
generatorArch, discriminatorArch, InputType.ThreeDimensional,
scaleFactor: 2, numRRDBBlocks: 16);
The default values are from the Real-ESRGAN paper and work well for most use cases.
RealESRGAN(NeuralNetworkArchitecture<T>, string, int)
Creates a Real-ESRGAN model using a pretrained ONNX model for inference.
public RealESRGAN(NeuralNetworkArchitecture<T> architecture, string onnxModelPath, int scaleFactor = 4)
Parameters
architectureNeuralNetworkArchitecture<T>The neural network architecture configuration.
onnxModelPathstringPath to the pretrained Real-ESRGAN ONNX model.
scaleFactorintUpscaling factor of the pretrained model. Default: 4.
Remarks
For Beginners: Use this constructor when you have a pretrained Real-ESRGAN model in ONNX format. This is the fastest way to use Real-ESRGAN for inference without training.
Example:
var arch = new NeuralNetworkArchitecture<float>(
inputType: InputType.ThreeDimensional,
inputHeight: 128, inputWidth: 128, inputDepth: 3);
var model = new RealESRGAN<float>(arch, "realesrgan_x4.onnx");
var highRes = model.Upscale(lowResImage);
Note: Training is not supported in ONNX mode. Use the native constructor for training.
Pretrained ONNX models can be downloaded from: - https://github.com/xinntao/Real-ESRGAN (official) - Hugging Face model hub
Exceptions
- FileNotFoundException
Thrown if the ONNX model file is not found.
Properties
Discriminator
Gets the U-Net discriminator network that judges image quality.
public UNetDiscriminator<T>? Discriminator { get; }
Property Value
Remarks
Real-ESRGAN uses a U-Net discriminator that provides per-pixel feedback, which helps generate more detailed and realistic textures compared to standard discriminators that only provide a single real/fake score.
For Beginners: The discriminator learns to tell the difference between real high-resolution images and generated ones. This adversarial training helps the generator create more realistic outputs. Only available in native mode.
Generator
Gets the RRDB-Net generator network that produces super-resolved images.
public RRDBNetGenerator<T>? Generator { get; }
Property Value
Remarks
The generator uses Residual in Residual Dense Blocks (RRDB) for deep feature extraction, followed by pixel shuffle upsampling. This architecture is highly effective for super-resolution tasks.
For Beginners: The generator is the main network that takes your low-resolution image and outputs the high-resolution version. Only available in native mode.
LastDiscriminatorLoss
Gets the last discriminator loss value.
public T LastDiscriminatorLoss { get; }
Property Value
- T
LastGeneratorLoss
Gets the last generator loss value.
public T LastGeneratorLoss { get; }
Property Value
- T
ScaleFactor
Gets the upscaling factor for this model.
public int ScaleFactor { get; }
Property Value
SupportsTraining
Gets whether training is supported (only in native mode).
public override bool SupportsTraining { get; }
Property Value
UseNativeMode
Gets whether this model uses native mode (true) or ONNX mode (false).
public bool UseNativeMode { get; }
Property Value
Remarks
For Beginners: Native mode allows training and uses pure C# layers. ONNX mode loads a pre-trained model for inference only.
Methods
CreateNewInstance()
Creates a new instance of the same type as this neural network.
protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()
Returns
- IFullModel<T, Tensor<T>, Tensor<T>>
A new instance of the same neural network type.
Remarks
For Beginners: This creates a blank version of the same type of neural network.
It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.
DeserializeNetworkSpecificData(BinaryReader)
Deserializes network-specific data that was not covered by the general deserialization process.
protected override void DeserializeNetworkSpecificData(BinaryReader reader)
Parameters
readerBinaryReaderThe BinaryReader to read the data from.
Remarks
This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.
For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.
GetModelMetadata()
Gets the metadata for this neural network model.
public override ModelMetadata<T> GetModelMetadata()
Returns
- ModelMetadata<T>
A ModelMetaData object containing information about the model.
InitializeLayers()
Initializes the layers of the neural network based on the architecture.
protected override void InitializeLayers()
Remarks
For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.
Predict(Tensor<T>)
Makes a prediction using the neural network.
public override Tensor<T> Predict(Tensor<T> input)
Parameters
inputTensor<T>The input data to process.
Returns
- Tensor<T>
The network's prediction.
Remarks
For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).
SerializeNetworkSpecificData(BinaryWriter)
Serializes network-specific data that is not covered by the general serialization process.
protected override void SerializeNetworkSpecificData(BinaryWriter writer)
Parameters
writerBinaryWriterThe BinaryWriter to write the data to.
Remarks
This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.
For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.
Train(Tensor<T>, Tensor<T>)
Trains the neural network on a single input-output pair.
public override void Train(Tensor<T> input, Tensor<T> expectedOutput)
Parameters
inputTensor<T>The input data.
expectedOutputTensor<T>The expected output for the given input.
Remarks
This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.
For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)
The network then:
- Makes a prediction based on the input
- Compares its prediction to the expected output
- Calculates how wrong it was (the loss)
- Adjusts its internal values to do better next time
After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.
TrainStep(Tensor<T>, Tensor<T>)
Performs one training step for Real-ESRGAN.
public (T discriminatorLoss, T generatorLoss) TrainStep(Tensor<T> lowResImages, Tensor<T> highResTargets)
Parameters
lowResImagesTensor<T>Low-resolution input images.
highResTargetsTensor<T>High-resolution target images.
Returns
Remarks
This method performs one complete training iteration: 1. Generate super-resolved images from low-res input 2. Train discriminator to distinguish real from generated 3. Train generator to fool discriminator and minimize reconstruction loss
For Beginners: Call this method repeatedly during training:
for (int epoch = 0; epoch < numEpochs; epoch++)
{
foreach (var batch in dataLoader)
{
var (dLoss, gLoss) = model.TrainStep(batch.LowRes, batch.HighRes);
Console.WriteLine($"D Loss: {dLoss:F4}, G Loss: {gLoss:F4}");
}
}
UpdateParameters(Vector<T>)
Updates the network's parameters with new values.
public override void UpdateParameters(Vector<T> parameters)
Parameters
parametersVector<T>The new parameter values to set.
Remarks
For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.
This is typically used by optimization algorithms that calculate better parameter values based on training data.
Upscale(Tensor<T>)
Upscales a low-resolution image to high resolution.
public Tensor<T> Upscale(Tensor<T> lowResImage)
Parameters
lowResImageTensor<T>The low-resolution input image tensor.
Returns
- Tensor<T>
The super-resolved high-resolution image tensor.
Remarks
For Beginners: Use this method after training to upscale images:
var highResImage = model.Upscale(lowResImage);