ホーム 暮らし [Part 1] Too late to ask! A thorough explanation of how ControlNet works and how to use it!

[Part 1] Too late to ask! A thorough explanation of how ControlNet works and how to use it!

三浦 拓海 三浦 拓海 • 更新: • 公開: • 読了約 59 分
目次

2024.07.16 Update
I forgot to include information about the Hires-Fix Option and the dedicated options within Img2Img for ControlNet parameters, so I have added them.


Introduction

n95399958196e

Everyone, are you using ControlNet?
ControlNet became a hot topic around April 2023, was recognized as a groundbreaking technology released by lllyasviel, and is now widely known.
However, there may be some of you who are using it without fully understanding what kind of function it actually is, what the characteristics of each ControlNet type are, or what a ControlNet model is.

This is the first part of the series, so I will explain the basics, but I intend to provide a thorough explanation in the future.


What is ControlNet?

It may not need an introduction, but this technology was announced and released by lllyasviel, and it has become an extension that is no exaggeration to call essential.

As for its purpose, it supports various uses such as fixing compositions, specifying character poses, and adjusting or improving the quality of details.
It is a technology that sent shockwaves through the image generation AI community by making it possible to easily control parts that previously had to be painstakingly controlled via prompts.


Overview of ControlNet

In summary, ControlNet is a technology with a neural network structure that adds conditions to each block within the neural network of a diffusion model to control the diffusion model process.

This is very logical for controlling the latent space in image generation AI.

What this means is that the U-Net is originally an independent neural network structure that generates products through various layers.

The U-Net, which is a CNN-based neural network for diffusion models, proceeds with inference through each block.
The main resources that users could provide as conditions were prompts used in Text-to-Image and image data used in Image-to-Image. (Along with associated inference parameters, etc.)

In other words, there were limits to the resources that users could specify.
Therefore, in the past, users had to use prompts and various parameters to try and error compositions and character depictions within a system that could only be completed within the U-Net.

ControlNet solved that problem.
ControlNet retains the neural network blocks of the U-Net, adds the additional conditions provided by the user via the neural network on ControlNet, and returns them to the U-Net.

By doing so, you can significantly improve control over generated products, such as fixing the composition.

For those who might not quite grasp it yet, to put it more simply: "By returning the results processed by another neural network (the ControlNet model) to the main Stable Diffusion U-Net with additional conditions applied, it has become much easier to contribute to fixed compositions, character poses, and the like".


Features of ControlNet

As you can see by referring to the overview of ControlNet illustrated in the previous section, the weights of the conv layers (layers related to convolution weights) are zero.

What this means is that in CNN-based convolution, you cannot perform feature convolution without calculating a dimensional vector.
Returning zero weights or biases to the conv layer means the vector gradient also becomes zero (zero convolution), and one would normally think that the neural network learns nothing.

However, lllyasviel stated, "Without being affected by the held neural network blocks, as long as the given features are non-zero, they are optimized into a non-zero matrix in the first gradient descent iteration, and eventually, the zero convolution gradually becomes a common conv layer with non-zero weights", thereby creating the foundation for ControlNet.

To put it extremely simply, it is like saying, "You can provide only the weights of the additional ControlNet conditions without being influenced by the generation process (= it is difficult to produce completely unintended outputs)".


Differences between ControlNet and Image-to-Image

Now, I will explain the difference between ControlNet and Image-to-Image (img2img), which many people are likely wondering about.

Both ControlNet and img2img use image data (including images processed by a preprocessor in the case of ControlNet) as input resources.

So, is it essentially img2img?Many people might think this, but the nature and process are completely different.

img2img is a function that "calculates the features of an image and infers an image similar to the features of the entire image".
In contrast, ControlNet is a technology that "infers a new image by using the features of the image composition, such as lines, depth, contours, and landmarks (structures such as skeletons and joints) within the image, as additional conditions".

In terms of appearance on the frontend and usability, it is easy to get the feeling that it is close to img2img, but the essence is completely different, and it can be said that ControlNet has higher versatility and applicability than img2img.


Basic Knowledge of ControlNet

The following are the main scenes in which it is used.

  • I don't want to change the character's composition

  • I want to keep the character's pose fixed and only change the background

  • I want to make the character strike a specific pose

  • I only want to change the character's appearance

  • I want to change only a part of the generated image to something specific

  • I want to increase the level of detail and improve quality

And so on... the uses are extremely diverse.

Among these, making the character strike a specific pose is particularly excellent, and it significantly improves output quality compared to the traditional method of controlling via prompts and relying on the generation lottery.


Introduction

Since this is Part 1, I would like to cover the introduction and basic usage.

This section is for those who haven't installed ControlNet yet!
If you have already installed it, you can skip this.

First, let's install the main program.

It is developed by Mikubill as an extension for SD WebUI.

We will be using this.

There are two ways to install it.

  • Method of installing by cloning from the Git repository

  • Method of installing from the SD WebUI extension list

Either way is fine.


(1) Method of installing by cloning from the Git repository

First, use PowerShell or a similar tool to navigate to the extensions folder of your SD WebUI.

cd ./python/venv/stable-diffusion-webui/extentions

Please change the folder path as appropriate for your environment.

Next, perform a Git Clone.

git clone https://github.com/Mikubill/sd-webui-controlnet

This completes the installation of the main program.


(2) How to install from the SD WebUI extension list

Open the Extensions tab in SD WebUI, go to the Available list, and click Load.
A list of registered repositories will be displayed.

Next, enter "sd-webui-controlnet" into the search field.

Click Install to install the main program.

Next, let's install the ControlNet models.
ControlNet models are divided into those for SD1.x/2.x and those for SDXL.

ControlNet models come in both .pth and .safetensors extensions.
There are also yaml files; if they are missing, please download them.

ControlNet models for SD1.x/2.x

ControlNet models for SDXL

It is possible to download them manually one by one, but you can also download them in bulk.
If you want to download them in bulk, please try the following.


Bulk download ControlNet models from the repository

Open a terminal such as PowerShell and enter the following command.

First, install the huggingface_hub module via pip.

pip install huggingface_hub

Execute the Python command to enable script writing.

python

Import the snapshot_download function from the huggingface_hub module.

from huggingface_hub import snapshot_download

Specify the repository you want to download in bulk using the snapshot_download function and execute it.
The snapshot_download function should be specified as follows.

snapshot_download(
    # Hugging FaceリポジトリID
    repo_id="", 
    # ブランチ名
    revision="",
    # 一括ダウンロード対象の拡張子(正規表現指定可)
    allow_patterns="", 
    # 保存先
    local_dir="")

As an example, we will download the ControlNet models for SD1.x/2.x in bulk, so we will configure it as follows.

When replaced with the execution function, it becomes

snapshot_download(
    repo_id = "lllyasviel/ControlNet-v1-1",
    revision = "main",
    allow_patterns = ".pth",
    local_dir = ".\python\venv\stable-diffusion-webui\extensions\sd-webui-controlnet\models"
)

as follows.
Please change the local_dir as appropriate for your environment.

When executed, the download will start as shown below.

Fetching 14 files:   0%|                                                                       | 0/14 [00:00<?, ?it/s]
control_v11p_sd15_inpaint.pth:  25%|██████████████████████████████▍                            | 367M/1.45G [00:33<03:00, 5.97MB/s] 
control_v11e_sd15_shuffle.pth:  22%|██████████████████████████▉                                | 325M/1.45G [00:33<02:39, 7.02MB/s] 
control_v11p_sd15_canny.pth:  28%|█████████████████████████████████▋                           | 398M/1.45G [00:34<02:28, 7.04MB/s] 
control_v11e_sd15_ip2p.pth:  25%|██████████████████████████████▎                               | 357M/1.45G [00:33<03:07, 5.80MB/s] 
control_v11p_sd15_mlsd.pth:  23%|████████████████████████████▌                                 | 336M/1.45G [00:34<02:31, 7.30MB/s] 
control_v11p_sd15_normalbae.pth:  20%|███████████████████████▉                                 | 294M/1.45G [00:29<02:51, 6.73MB/s] 

After that, please wait a while until the download is complete.


Explanation of common features

Now, let's open ControlNet.
If the installation of the main body is complete, items like the ones below should have been added to the Generation tab.

You can see that there are various functions, preprocessors, models, and other items.
I would like to explain what each of them is one by one.

Image resource section

Single Image
Use this when performing one ControlNet process for one output.
With one output, one mask image is generated, and the inference result of the ControlNet model affects one image.

Basically, you will use this function.
Since it is one ControlNet assignment per image, it is easy to visualize.

An example is given below.

For example, suppose you want to create a composition similar to one image.

Pass this through the Canny preprocessor.

A mask image like the one above has been generated.
Let's try running the generation as is.

An image with a fixed composition and pose, as shown above, has been generated.



Batch
Used when performing ControlNet processing multiple times under the same generation conditions and outputting them in bulk.
The ControlNet model will perform inference on all image resources within the specified folder.
Multiple mask images are generated in a single output, and the inference results of the ControlNet model will affect the output for each image in the folder.

As for how to utilize this feature, since you can output multiple images with ControlNet applied at once, if you have a fixed composition, you can use it to output images that follow the mask images in bulk rather than generating them one by one with single specifications.

An example is provided below.

For instance, suppose you specify a folder containing two different mask images.

When you generate with Batch enabled, the result will be as follows.

This process is performed in a single generation run.

However, please note that the generation conditions at that time, such as the prompt and parameters, will be identical, and since the mask images are processed in order, it is not suitable for random generation.


Multi-Inputs
Used when performing multiple ControlNet processes on a single image.
The ControlNet model performs inference on the specified image resource.
Multiple mask images are generated in a single output, and the inference results of the ControlNet model influence the generation of a single image by the specified number of images.

The difference from batch processing is whether it is processed one by one (batch mode) or processed with multiple images (Multi-Inputs).

In other words,

  • Batch mode = one generated image with one ControlNet process. This is performed multiple times.

  • Multi-Inputs = one generated image with n ControlNet processes. This is performed once.

is what it is.

The way to utilize this feature is that when there are multiple people or multiple objects with a fixed layout, you can specify multiple mask images to place characters or other elements at your preferred positions in the generated image.

An example is given below.

For example, suppose there are two different mask images.

Provide these two mask images as input images to Multi-Inputs.

When you generate, it will look like the following.

In this way, mask images function like multiple layers, and you can apply multiple mask images to a single generated image.

Since this feature processes multiple ControlNet Units in parallel, you need to change the WebUI settings to enable it.

This setting requires a restart of the WebUI.

2024-07-15 14:19:25,989 - ControlNet - INFO - unit_separate = False, style_align = False
2024-07-15 14:19:25,989 - ControlNet - INFO - Loading model from cache: control_v11p_sd15_canny [d14c016b]
2024-07-15 14:19:26,001 - ControlNet - INFO - Using preprocessor: none
2024-07-15 14:19:26,001 - ControlNet - INFO - preprocessor resolution = 512
2024-07-15 14:19:26,340 - ControlNet - INFO - Loading model from cache: control_v11p_sd15_canny [d14c016b]
2024-07-15 14:19:26,352 - ControlNet - INFO - Using preprocessor: none
2024-07-15 14:19:26,352 - ControlNet - INFO - preprocessor resolution = 512
2024-07-15 14:19:26,456 - ControlNet - INFO - ControlNet Hooked - Time = 0.4697611331939697

If you look at the log above, you can see that the ControlNet model is loaded twice in one section.

I will list some supplementary notes regarding the input image area.

Q. What is this at the bottom right of the image resource canvas?

ControlNet Settings Section

Enable
Enables the application of ControlNet.

Low VRAM
Prioritizes processing with low VRAM.
In exchange, it sacrifices processing speed, making it extremely slow.

Pixel Perfect
This setting maintains pixel-level accuracy for the input image.
For some tasks, you can expect a certain improvement in quality.

Allow Preview
Allows you to check a preview of the mask image processed by the preprocessor.

You can create a preprocessor preview by pressing the button below.

Also, by pressing the Edit button within the Preprocessor Preview, you can edit the mask image canvas.

Effective Region Mask

This is a feature that specifies the region where ControlNet is applied.
This feature uses black and white mask images.

In the figure above, the left side (white) is the effective region, and the right side (black) is the ineffective region.

ControlNet Parameters Section

Control Type

ControlNet has multiple types of inference methods.
It is no exaggeration to say that this is the core of ControlNet.
Details about this feature will be explained in Part 2 and beyond.


Preprocessor

A preprocessor refers to a pre-processing device that converts an image into a format that a specified model can appropriately handle before passing it to the ControlNet model.

For example, suppose you have an image like the one below.

If you pass this through a Depth Preprocessor, it will look like the following.

This is a necessary pre-processing step for the ControlNet Depth function to read depth information.
It is used to convert the depth information of the input image into an image represented by shades of black and white, and then pass it to the ControlNet Depth model.


Model

The model refers to the ControlNet model.
Unlike standard Checkpoint models, it plays the role of inferring structural information from a mask image and passing additional conditions to the Stable Diffusion U-Net.


Control Weight
Starting Control Step
Ending Control Step
Resolution

Control Weight
You can specify the application strength of ControlNet.
It has a role similar to specifying emphasis or strength in prompts.

For composition fixing such as pose specification (Canny or Depth), a relatively strong intensity (0.8 to 1) is a good guideline.
For the amount of detail (Tile), it is considered desirable to use around 0.4 to 0.6.


Starting Control Step / Ending Control Step
Starting Control Step allows you to specify the starting percentage of the ControlNet application steps.
It specifies at what step the application of ControlNet should begin.

For example,

  • Step : 30

  • Starting Control Step : 0.2

If this is the case, ControlNet will be applied from the 6th step, which is 20% of 30 steps.

Ending Control Step allows you to specify the percentage at which ControlNet application ends.
You specify at what point the application of ControlNet should terminate.
For it to function correctly, the specified value must be "Starting Control Step < Ending Control Step".

For composition fixing such as pose specification (Canny or Depth), it reflects beautifully even at the default (Start 0 - End 1), but for the amount of detail (Tile), the balance with the Ending Control Step is important, and if not adjusted, it may cause the composition to collapse.


Resolution
Specifies the resolution of the preprocessor's preprocessed image (mask image).
This affects the resize mode described later.


Control Mode
Resize Mode
Hires-Fix Option

Control Mode
When ControlNet merges with the main path, the U-Net Block, and additional conditions, you can choose whether to prioritize the main path side (Stable Diffusion side) or the sub-path side (ControlNet side).

・Balanced
Acts like Alpha=0.5 in model merging, setting the priority to half and half.

・My prompt is more important
As the name suggests, this prioritizes the main path side (the prompt on the Stable Diffusion side).

・ControlNet is more important
As the name suggests, this prioritizes the sub-path side (the additional conditions on the ControlNet side).

Basically, Balanced is fine, but if you want to fix the composition and change the appearance of the character, you need to select My prompt is more important.
Since there are more scenes where you prioritize the specified prompt, it is thought that there are few opportunities to select ControlNet is more important.


Resize Mode

Specifies how to execute resizing (resolution change) when there is a difference between the resolution of the mask image and the generated image.

・Just Resize
Resizes without considering the aspect ratio.

・Crop and Resize
Crops to an aspect ratio that matches the specified resolution and resizes while maintaining the aspect ratio.
The parts that stick out are excluded.

・Resize and Fill

It is resized to an aspect ratio that matches the specified resolution, and the blank parts are filled with a mask as an invalid area.


Hires-Fix Option

This feature can only be selected when the Hires.fix feature is enabled.

・Both
Applies the ControlNet processing steps to both the Sampling Steps and the Hires Steps.

・Low res only
Applies the ControlNet processing steps only to the Sampling Steps.

・High res only
Applies the ControlNet processing steps only to the Hires Steps.

[ Technical Note ]
Since there is no detailed documentation on the behavior of this feature in various places, I will explain it by reading through the ControlNet script.

This feature is quite simple.
It only contains descriptions of whether to apply ControlNet processing in the normal flow, or whether to enable or disable ControlNet processing for Hires-Fix.

The following is a part of sd-webui-controlnet/scripts/hook.py.
(Since the branching is extensive and long, I will only quote the flag section.)

    def disabled_by_hr_option(self, is_in_high_res_fix: bool) -> bool:
        if self.hr_option == HiResFixOption.BOTH:
            control_disabled = False
        elif self.hr_option == HiResFixOption.LOW_RES_ONLY:
            control_disabled = is_in_high_res_fix
        elif self.hr_option == HiResFixOption.HIGH_RES_ONLY:
            control_disabled = not is_in_high_res_fix
        else:
            assert False, "NOTREACHED"
        return control_disabled

In the disabled_by_hr_option function, it is written such that is_in_high_res_fix (a boolean value) is referenced as a flag.
This variable is used as a flag in subsequent branches to determine whether to proceed with the normal Sampling Steps processing and Hires-Fix processing.

  • Both (HiResFixOption.BOTH) If selected, the Hires-Fix disabling process is disabled, and it proceeds with the normal flow.

  • Low res only (HiResFixOption.LOW_RES_ONLY) If selected, the Hires-Fix disabling process is enabled, and the Hires-Fix processing by ControlNet is skipped.

  • High res only (HiResFixOption.HIGH_RES_ONLY) If selected, because it is not is_in_high_res_fix, the flag is inverted, and if the result is True, the Hires-Fix processing by ControlNet itself is enabled, but the Sampling Steps processing by ControlNet is skipped.

In any case, since the HiresFix processing on the Stable Diffusion side is executed, it is something that is completed solely within the ControlNet processing.

However, since the application range of ControlNet changes, it is assumed that significant changes will occur in the output.


Batch Loopback

This feature can only be selected in batch mode.
This feature allows you to perform ControlNet processing by importing generated images without specifying a mask image.

This makes it possible to add subtle changes to generated images or regenerate them using different preprocessors or parameters.


Upload independent control image

This feature can only be selected during img2img.

Normally, you cannot select an image resource (input image) during img2img.
This is because, due to the nature of img2img, inference is performed based on the feature values of the entire image.

However, enabling this feature allows you to select an image resource.

This allows for ControlNet processing independent of img2img, making it possible to apply specific compositions to img2img generated images.


Multi ControlNet

Multi ControlNet is a feature that allows you to process images using multiple ControlNet Units.

You can use different preprocessors or ControlNet models to apply ControlNet processing to generated images.

As mentioned in the Multi-Inputs mode section, this feature requires the following setting to be enabled.
A restart of the WebUI is required after changing the setting.

In the example shown above, Canny is used to fix the character composition, while Tile is used to increase detail and quality.

Previously, this task could not be completed in a single sequence and had to be done in separate steps, but since the implementation of Multi ControlNet, it can now be completed within a single process.


Conclusion

How was it?
This time, I provided some basic background knowledge on ControlNet.
ControlNet is an innovative feature, so you definitely shouldn't miss out on using it!

In Part 2, I will explain Control Types.
Please be aware that from the next installment, this will be a paid article for members.

If you are struggling with specifying compositions or poses, please give ControlNet a try!


References and Citations

1 : U-Net Convolutional Networks for Biomedical Image Segmentation - Fig.1 (Olaf Ronneberger, 18 May 2015)

2 : Below is ControlNet 1.0 - Stable Diffusion + ControlNet (lllyasviel Update commits on Sep 9, 2023)

3 : Adding Conditional Control to Text-to-Image Diffusion Models (Lvmin Zhang, 26 Nov 2023)


同じカテゴリの記事

三浦 拓海
コンテンツディレクター 三浦 拓海
プロフィールを見る →

映画と連続ドラマの公開情報を追う担当。配給会社のプレスシートと公式サイトの発表日を確認したうえで執筆します。

おすすめの関連記事