MangaNinja Documentation

repository·main·Indexed 20 days ago

https://github.com/ali-vilab/manganinjia

A reference-based line art colorization method for the anime industry. MangaNinja enables precise color control by automatically aligning reference images with line art and supporting optional point-based guidance. The system includes tools for line art detection via LineartDetector and BatchLineartDetector, as well as a ReferenceAttentionControl mechanism for injecting reference features into UNet models.

Tokens
9.8K
Snippets
27
Records
36
Agent score
72%

What's inside MangaNinja

  1. Configure MangaNinja model weights

    main

    MangaNinja requires several pre-trained weights from HuggingFace (StableDiffusion, CLIP, ControlNet, and Annotators) as well as the specific MangaNinjia model weights.

    Ensure your checkpoints directory follows this structure:

    -- checkpoints
        |-- StableDiffusion
        |-- models
            |-- clip-vit-large-patch14
            |-- control_v11p_sd15_lineart
            |-- Annotators
                |-- sk_model.pth
        |-- MangaNinjia
            |-- denoising_unet.pth
            |-- reference_unet.pth
            |-- point_net.pth
            |-- controlnet.pth

    Before running the Gradio interface, you must modify ./configs/inference.yaml to point to the correct paths for these model weights.

  2. Run MangaNinja with Gradio UI

    main

    For a user-friendly interface, use the Gradio demo.

    1. Modify ./configs/inference.yaml to set the paths to your model weights.
    2. Run the Gradio script:
    python run_gradio.py

    Gradio Workflow:

    1. Upload Images: Upload a reference image and a target image. For the target, you can upload an RGB image (auto-extraction) or check 'input is lineart' to upload a grayscale line art directly.
    2. Process: Click 'Process Images' to resize them to 512x512.
    3. Point Guidance (Optional): Alternately click on the reference and target images to define matching points. Use 'Undo' to revert.
    4. Generate: Click 'Generate' to produce the colorized result.
  3. Install MangaNinja

    main

    To set up MangaNinja, clone the repository and create a Conda environment using the provided environment.yaml file.

    # Clone the repository
    git clone https://github.com/ali-vilab/MangaNinjia.git
    cd MangaNinjia
    
    # Create and activate the Conda environment
    conda env create -f environment.yaml
    conda activate MangaNinjia
    git clone https://github.com/ali-vilab/MangaNinjia.git
    cd MangaNinjia
    conda env create -f environment.yaml
    conda activate MangaNinjia
  4. How ReferenceAttentionControl manages attention fusion

    main

    The ReferenceAttentionControl mechanism works by intercepting the forward pass of BasicTransformerBlock modules within the UNet.

    1. Write Mode: As the UNet processes the reference image, the ReferenceAttentionControl hooks into the transformer blocks and appends the normalized hidden states to a bank attribute within each module.
    2. Read Mode: When processing the target image, the hooks retrieve the stored features from the bank. It then performs a modified self-attention where the query comes from the target image, but the keys and values are augmented with the features from the reference bank.
    3. Fusion Scopes:
      • "midup": Only modifies the mid_block and up_blocks. This is often more efficient and focuses on structural/color fusion at higher resolutions.
      • "full": Modifies every BasicTransformerBlock found in the entire UNet hierarchy.
    4. Point Embeddings: The system supports point_bank_ref and point_bank_main, which allow for more precise, point-based reference following by filtering embedding matrices to match the specific spatial dimensions of the attention blocks.
  5. Configure GLIGEN via cross_attention_kwargs

    main

    To use GLIGEN positioning, pass a gligen key within the cross_attention_kwargs dictionary during the forward pass. This triggers the use of the model's position_net to process object arguments.

    Expected structure in cross_attention_kwargs:

    {
        "gligen": {
            "objs": [...] # Object definitions
        }
    }
  6. Configure PointNet architecture parameters

    main

    When instantiating PointNet, you can control the depth and width of the feature extraction pipeline using the following parameters:

    • conditioning_channels (int): The number of input channels. Default is 1.
    • out_channels (Tuple[int]): A tuple defining the number of output channels for each convolutional block. Default is (320, 640, 1280, 1280).
    • downsamples (Tuple[int]): A tuple defining the downsampling factor for each block. Note that the internal loop uses downsample // 2 to determine the number of Conv2d layers per block. Default is (6, 2, 2, 2).
  7. Configure Transformer2DModel parameters

    main

    When initializing Transformer2DModel, use the following parameters:

    ParameterTypeDefaultDescription
    num_attention_headsint16Number of heads for multi-head attention.
    attention_head_dimint88Number of channels in each head.
    in_channelsintNoneNumber of input/output channels (for continuous input).
    out_channelsintNoneNumber of output channels.
    num_layersint1Number of Transformer block layers.
    dropoutfloat0.0Dropout probability.
    cross_attention_dimintNoneDimensions of encoder_hidden_states for cross-attention.
    sample_sizeintNoneWidth of latent images (for discrete input).
    num_vector_embedsintNoneNumber of classes for vector embeddings (for discrete input).
    activation_fnstr"geglu"Activation function in feed-forward layers.
    num_embeds_ada_normintNoneNumber of diffusion steps used for AdaLayerNorm.
    norm_typestr"layer_norm"Type of normalization. Use "ada_norm" if num_embeds_ada_norm is set.
    attention_biasboolFalseWhether TransformerBlocks should contain a bias parameter.
  8. Configure inference settings

    main

    The inference behavior can be customized using the following parameters:

    • --denoise_steps: Number of denoising steps per inference pass. For the original DDIM version, 20-50 steps are recommended.
    • --is_lineart: Set this if the input is already a line art image and no additional extraction is needed. If providing an RGB image, the model will automatically extract the line art.
    • --guidance_scale_ref: Controls how strongly the model follows the reference image.
    • --guidance_scale_point: Controls how strongly the model follows point guidance for customized colorization.
    • --point_ref_paths and --point_lineart_paths (optional): Two 512x512 matrices representing matching points between the reference and line art. Matching points use continuously increasing integers (1, 2, 3, etc.) at the same coordinates in both matrices, while other positions are 0.
  9. Optimize memory with set_attention_slice in UNet2DConditionModel

    main

    To save memory during attention computation at the cost of a small speed decrease, you can enable sliced attention. This splits the input tensor into slices for computation.

    Arguments:

    • slice_size (str | int | list(int), optional):
      • `
  10. Use the RefUNet2DConditionModel forward method

    main

    The forward method performs the denoising pass through the UNet. It supports various conditioning types including text, images, and additional residuals for ControlNet or T2I-Adapters.

    Key Arguments:

    • sample (torch.FloatTensor): Noisy input tensor of shape (batch, channel, height, width).
    • timestep (torch.FloatTensor | float | int): The number of timesteps to denoise.
    • encoder_hidden_states (torch.FloatTensor): Encoder hidden states of shape (batch, sequence_length, feature_dim).
    • class_labels (torch.Tensor, optional): Class labels for conditioning.
    • attention_mask (torch.Tensor, optional): Mask of shape (batch, key_tokens) (1 to keep, 0 to discard).
    • encoder_attention_mask (torch.Tensor, optional): Cross-attention mask of shape (batch, sequence_length).
    • added_cond_kwargs (dict, optional): Dictionary for additional embeddings. Depending on addition_embed_type in config, it may require:
      • image_embeds: For text_image, image, or image_hint modes.
      • text_embeds: For text_time mode.
      • time_ids: For text_time mode.
      • hint: For image_hint mode.
    • down_block_additional_residuals (tuple[torch.Tensor], optional): Residuals for ControlNet.
    • mid_block_additional_residual (torch.Tensor, optional): Residual for the middle block.
    • down_intrablock_additional_residuals (tuple[torch.Tensor], optional): Residuals for T2I-Adapters.
    • return_dict (bool, optional, defaults to True): If True, returns UNet2DConditionOutput; otherwise returns a tuple containing the sample.
    # Example: Basic forward pass
    output = model(
        sample=noisy_latents,
        timestep=50.0,
        encoder_hidden_states=text_embeddings
    )
    
    # If return_dict=False, access the sample directly
    output_tuple = model(
        sample=noisy_latents,
        timestep=50.0,
        encoder_hidden_states=text_embeddings,
        return_dict=False
    )
    sample = output_tuple[0]
  11. Initialize Transformer2DModel

    main

    The Transformer2DModel is a 2D Transformer designed for image-like data. It can process three types of inputs based on the configuration provided:

    1. Continuous Input: Standard images with shape (batch_size, num_channels, height, width). Requires setting in_channels and ensuring patch_size is None.
    2. Vectorized Input: Quantized image embeddings with shape (batch_size, num_vector_embeds). Requires setting num_vector_embeds and ensuring patch_size is None.
    3. Patch Input: Requires setting both in_channels and patch_size.

    Note: You cannot define both in_channels and num_vector_embeds simultaneously, nor can you define both num_vector_embeds and patch_size.

    from src.models.transformer_2d import Transformer2DModel
    
    # Example for continuous input
    model = Transformer2DModel(
        num_attention_heads=16,
        attention_head_dim=88,
        in_channels=4,
        num_layers=12,
        cross_attention_dim=768
    )