tiled-diffusion icon indicating copy to clipboard operation
tiled-diffusion copied to clipboard

Working with Flux

Open jloganolson opened this issue 1 year ago • 1 comments

Has anyone gotten this working with Flux outside of ComfyUI? Like a python script example?

jloganolson avatar Mar 13 '25 16:03 jloganolson

I took a crack at it, can get the joining section continuous, but there seems to be some problem with it joining the main part of the image, here's my code if anyone can see the problem:

import gc
import logging
import os
from datetime import datetime
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import torch
from diffusers import FluxPipeline
from tqdm.auto import tqdm

# You'll need to import these from the original tiled diffusion codebase
from latent_handler import LatentHandler
from utils import generate_graph_groups


class FluxLatentClass:
    """
    Latent class for Flux model with support for dual text encoders and packed latents
    """

    def __init__(self, prompt, negative_prompt="", height=1024, width=1024, side_id=[], side_dir=[], is_fixed=False,
                 eval_image=None):
        self.prompt = prompt
        self.negative_prompt = negative_prompt
        self.height = height
        self.width = width
        if len(side_id) == 0:
            self.side_id = [None, None, None, None]
            self.side_dir = [None, None, None, None]
        else:
            self.side_id = side_id
            self.side_dir = side_dir
        self.is_fixed = is_fixed
        
        # Flux-specific embeddings
        self.prompt_embeds = None  # T5 embeddings
        self.pooled_prompt_embeds = None  # CLIP pooled embeddings
        self.text_ids = None  # Text position IDs
        self.negative_prompt_embeds = None
        self.negative_pooled_prompt_embeds = None
        self.negative_text_ids = None
        
        # Latent tensors (packed format for Flux)
        self.pre_latent = None
        self.post_latent = None
        self.latent_image_ids = None  # Image position IDs for Flux
        
        # Output
        self.image = None
        self.eval_image = eval_image

    def is_xy(self):
        """Check if tiling is needed in both X and Y directions"""
        return (self.side_dir[1] or self.side_dir[0]) and (self.side_dir[2] or self.side_dir[3])

    def is_x(self):
        """Check if tiling is needed in X direction"""
        return self.side_dir[1] or self.side_dir[0]

    def is_y(self):
        """Check if tiling is needed in Y direction"""
        return self.side_dir[2] or self.side_dir[3]

    def clone_post_latents(self):
        """Clone pre_latent to post_latent"""
        self.post_latent = self.pre_latent.clone()


class FluxLatentTiling:
    def __init__(self, model_id="black-forest-labs/FLUX.1-dev", scheduler="euler"):
        self.model_id = model_id
        
        # Load the full Flux pipeline with balanced device mapping
        self.pipe = FluxPipeline.from_pretrained(
            model_id,
            torch_dtype=torch.bfloat16,
            device_map="balanced"
        )
        
        # Extract individual components for easier access
        self.tokenizer = self.pipe.tokenizer
        self.tokenizer_2 = self.pipe.tokenizer_2
        self.text_encoder = self.pipe.text_encoder
        self.text_encoder_2 = self.pipe.text_encoder_2
        self.transformer = self.pipe.transformer
        self.vae = self.pipe.vae
        self.scheduler = self.pipe.scheduler
        
        logging.warning("Finished loading Flux models..")

    @property
    def device(self):
        """Get the pipeline's execution device"""
        return self.pipe._execution_device

    def __call__(self, latents_arr, negative_prompt="", inference_steps=28, seed=42,
                 guidance_scale=3.5, height=1024, width=1024, max_width=10, max_replica_width=5, 
                 device=None, max_sequence_length=512, true_cfg_scale=1.0):
        """
        Generate tiled images using Flux pipeline.
        
        Args:
            device: Device to use for tensor operations. If None, uses pipeline's execution device.
                   Can specify specific device like 'cuda:0', 'cpu', etc.
        """
        
        # Use pipeline's execution device if none specified
        if device is None:
            device = self.pipe._execution_device
        
        # Set up generator on the appropriate device  
        generator = torch.Generator(device=device)
        generator.manual_seed(seed)
        
        # Prepare text embeddings for each latent using pipeline's encode_prompt method
        for latent in latents_arr:
            # Encode positive prompt
            prompt_embeds, pooled_prompt_embeds, text_ids = self.pipe.encode_prompt(
                prompt=latent.prompt,
                prompt_2=latent.prompt,  # Use same prompt for both encoders
                device=device,
                num_images_per_prompt=1,
                max_sequence_length=max_sequence_length
            )
            
            latent.prompt_embeds = prompt_embeds
            latent.pooled_prompt_embeds = pooled_prompt_embeds
            latent.text_ids = text_ids
            
            # Encode negative prompt if provided
            if latent.negative_prompt:
                neg_prompt_embeds, neg_pooled_prompt_embeds, neg_text_ids = self.pipe.encode_prompt(
                    prompt=latent.negative_prompt,
                    prompt_2=latent.negative_prompt,
                    device=device,
                    num_images_per_prompt=1,
                    max_sequence_length=max_sequence_length
                )
                latent.negative_prompt_embeds = neg_prompt_embeds
                latent.negative_pooled_prompt_embeds = neg_pooled_prompt_embeds
                latent.negative_text_ids = neg_text_ids
            else:
                latent.negative_prompt_embeds = None
                latent.negative_pooled_prompt_embeds = None
                latent.negative_text_ids = None

        # Prepare latents using pipeline's method with padding for all sides
        num_channels_latents = self.transformer.config.in_channels // 4
        batch_size = 1
        
        # Calculate padded dimensions
        padded_height = height + 2 * max_width * self.pipe.vae_scale_factor
        padded_width = width + 2 * max_width * self.pipe.vae_scale_factor
        
        for latent in latents_arr:
            # Use pipeline's prepare_latents method
            latent_tensor, latent_image_ids = self.pipe.prepare_latents(
                batch_size,
                num_channels_latents,
                padded_height,
                padded_width,
                latent.prompt_embeds.dtype,
                device,
                generator
            )
            
            latent.pre_latent = latent_tensor
            latent.latent_image_ids = latent_image_ids
            latent.clone_post_latents()

        # Set up scheduler
        sigmas = np.linspace(1.0, 1 / inference_steps, inference_steps)
        
        # Calculate shift parameter for Flux
        image_seq_len = latents_arr[0].pre_latent.shape[1]  # Number of patches
        mu = self.calculate_shift(image_seq_len)
        
        # Set timesteps on scheduler
        self.scheduler.set_timesteps(sigmas=sigmas, device=device, mu=mu)
        timesteps = self.scheduler.timesteps

        # Set up guidance
        if self.transformer.config.guidance_embeds:
            guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
            guidance = guidance.expand(batch_size)
        else:
            guidance = None

        # Generate graph groups for tiling
        graph_groups = generate_graph_groups(latents_arr)
        
        # Main denoising loop
        for i, t in tqdm(enumerate(timesteps)):
            logging.warning(f"Running step {i} of {len(timesteps)}")
            
            # Apply similarity constraint (unpack -> modify -> pack)
            logging.warning("Applying Similarity Constraint")
            for latent in latents_arr:
                latent.pre_latent = self.pipe._unpack_latents(
                    latent.pre_latent, 
                    padded_height, 
                    padded_width, 
                    self.pipe.vae_scale_factor
                )
            
            latents_arr = LatentHandler.apply_similarity_constraint(
                latents_arr, i, groups=graph_groups, max_width=max_width, max_replica_width=max_replica_width
            )
            
            for latent in latents_arr:
                B, C, H, W = latent.pre_latent.shape
                latent.pre_latent = self.pipe._pack_latents(latent.pre_latent, B, C, H, W)
                latent.clone_post_latents()

            # Apply tiling (unpack -> modify -> pack)
            logging.warning("Tiling latents")
            for latent in latents_arr:
                latent.pre_latent = self.pipe._unpack_latents(
                    latent.pre_latent, 
                    padded_height, 
                    padded_width, 
                    self.pipe.vae_scale_factor
                )
                latent.post_latent = self.pipe._unpack_latents(
                    latent.post_latent, 
                    padded_height, 
                    padded_width, 
                    self.pipe.vae_scale_factor
                )
            
            latents_arr = LatentHandler.tile(latents_arr, i, groups=graph_groups, max_width=max_width)
            
            for latent in latents_arr:
                B, C, H, W = latent.pre_latent.shape
                latent.pre_latent = self.pipe._pack_latents(latent.pre_latent, B, C, H, W)
                latent.post_latent = self.pipe._pack_latents(latent.post_latent, B, C, H, W)

            # Transformer forward pass for each latent
            for latent in latents_arr:
                torch.cuda.empty_cache()
                gc.collect()
                
                # Broadcast timestep
                timestep = t.expand(latent.post_latent.shape[0]).to(latent.post_latent.dtype)
                
                with torch.no_grad():
                    # Forward pass through transformer
                    noise_pred = self.transformer(
                        hidden_states=latent.post_latent,
                        timestep=timestep / 1000,
                        guidance=guidance,
                        pooled_projections=latent.pooled_prompt_embeds,
                        encoder_hidden_states=latent.prompt_embeds,
                        txt_ids=latent.text_ids,
                        img_ids=latent.latent_image_ids,
                        return_dict=False,
                    )[0]
                    
                    # Apply true CFG if negative prompts are provided
                    if (true_cfg_scale > 1.0 and latent.negative_prompt_embeds is not None):
                        neg_noise_pred = self.transformer(
                            hidden_states=latent.post_latent,
                            timestep=timestep / 1000,
                            guidance=guidance,
                            pooled_projections=latent.negative_pooled_prompt_embeds,
                            encoder_hidden_states=latent.negative_prompt_embeds,
                            txt_ids=latent.negative_text_ids,
                            img_ids=latent.latent_image_ids,
                            return_dict=False,
                        )[0]
                        noise_pred = neg_noise_pred + true_cfg_scale * (noise_pred - neg_noise_pred)

                # Scheduler step
                latent_new = self.scheduler.step(noise_pred, t, latent.post_latent, return_dict=False)[0]
                latent.pre_latent = latent_new
                latent.clone_post_latents()

        # Final processing
        logging.warning("Decoding latents and getting images")
        
        # Apply final similarity constraint
        logging.warning("Applying final Similarity Constraint")
        for latent in latents_arr:
            latent.pre_latent = self.pipe._unpack_latents(
                latent.pre_latent, 
                padded_height, 
                padded_width, 
                self.pipe.vae_scale_factor
            )
        
        latents_arr = LatentHandler.apply_similarity_constraint(
            latents_arr, len(timesteps), groups=graph_groups, max_width=max_width, max_replica_width=max_replica_width
        )
        for latent in latents_arr:
            latent.clone_post_latents()

        # Apply final tiling - need both pre_latent and post_latent unpacked
        logging.warning("Final tiling")
        
        latents_arr = LatentHandler.tile(latents_arr, len(timesteps), groups=graph_groups, max_width=max_width)
        
        # No need to repack - post_latent will be used directly for decoding

        # Apply random padding constraint
        logging.warning("Applying Random Padding Constraint")
        latents_arr = LatentHandler.apply_random_padding_constraint(
            latents_arr, groups=graph_groups, max_width=max_width
        )

        # Decode latents to images using pipeline's methods
        for latent in latents_arr:
            torch.cuda.empty_cache()
            gc.collect()
            
            # post_latent is already unpacked from final tiling, ready for VAE decoding
            unpacked_latents = latent.post_latent
            
            # Prepare for VAE decoding
            latents_for_decode = (unpacked_latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
            
            # Decode using VAE
            with torch.no_grad():
                images = self.vae.decode(latents_for_decode, return_dict=False)[0]
            
            # Post-process using pipeline's image processor
            images = self.pipe.image_processor.postprocess(images, output_type="np")
            
            # Crop padding from all sides
            img_array = images[0]  # Get first (and only) image from batch
            crop_pixels = max_width * self.pipe.vae_scale_factor
            
            # Crop padding from all sides to get original dimensions
            img_array = img_array[crop_pixels:-crop_pixels, crop_pixels:-crop_pixels, :]

            latent.image = img_array

        return latents_arr

    def calculate_shift(self, image_seq_len, base_seq_len=256, max_seq_len=4096, base_shift=0.5, max_shift=1.15):
        """Calculate shift parameter for Flux scheduler"""
        m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
        b = base_shift - m * base_seq_len
        mu = image_seq_len * m + b
        return mu


def main():
    """Main execution function"""
    os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
    torch.cuda.empty_cache()
    gc.collect()

    # Initialize Flux model with balanced device mapping
    print("Loading Flux model with balanced device mapping...")
    model = FluxLatentTiling(model_id="black-forest-labs/FLUX.1-dev")
    print(f"Model loaded. Primary execution device: {model.device}")

    # Parameters
    prompt_1 = "A seamless red brick wall texture, highly detailed, photorealistic"
    prompt_2 = "A seamless green brick wall texture, highly detailed, photorealistic"
    negative_prompt = "blurry, ugly, deformed, disfigured, poor details, bad anatomy, pixelated, bad quality, watermark"
    inference_steps = 28  # Flux typically uses fewer steps than SD
    seed = 151
    guidance_scale = 3.5  # Flux uses lower guidance scales
    true_cfg_scale = 1.0  # For true CFG with negative prompts
    max_replica_width = 4
    max_width = 8 # Smaller max_width for Flux due to different latent space
    height = 512  # Flux default resolution
    width = 512
    max_sequence_length = 512

    device = None  # Use pipeline's execution device (from device_map="balanced")

    # Create latent instances
    # Many-to-many tiling example on X axis
    # Right, Left, Up, Down
    lat1 = FluxLatentClass(
        prompt=prompt_1, 
        negative_prompt=negative_prompt, 
        height=height,
        width=width,
        side_id=[1, 1, None, None],
        side_dir=['cw', 'ccw', None, None]
    )

    # lat2 = FluxLatentClass(
    #     prompt=prompt_2, 
    #     negative_prompt=negative_prompt,
    #     height=height,
    #     width=width, 
    #     side_id=[1, 1, None, None],
    #     side_dir=['cw', 'ccw', None, None]
    # )

    latents_arr = [lat1]

    print("Starting Flux tiled diffusion...")
    new_latents_arr = model(
        latents_arr=latents_arr,
        negative_prompt=negative_prompt,
        inference_steps=inference_steps,
        seed=seed,
        guidance_scale=guidance_scale,
        true_cfg_scale=true_cfg_scale,
        height=height,
        width=width,
        max_width=max_width,
        max_replica_width=max_replica_width,
        device=device,  # None = uses pipeline's execution device from device_map="balanced"
        max_sequence_length=max_sequence_length
    )

    print("Generation complete!")

    # Clean up GPU memory
    torch.cuda.empty_cache()
    gc.collect()

    # Get results
    lat1_new = new_latents_arr[0]
    # lat2_new = new_latents_arr[1]

    # Create tiled visualization
    t_1 = np.concatenate((lat1_new.image, lat1_new.image), axis=1)

    plt.figure(figsize=(20, 5))
    plt.imshow(t_1)
    plt.axis('off')
    plt.title('Flux Tiled Diffusion - Many-to-Many X-axis Tiling')
    plt.tight_layout()
    plt.show()

    # Save individual images and tiled result
    print("Saving images...")

    # Create output directory
    os.makedirs("flux_outputs", exist_ok=True)

    # Convert to uint8 and save individual tiles
    lat1_image = (lat1_new.image * 255).astype(np.uint8)
    # lat2_image = (lat2_new.image * 255).astype(np.uint8)
    tiled_image = (t_1 * 255).astype(np.uint8)

    Image.fromarray(lat1_image).save("flux_outputs/flux_tile_1.png")
    # Image.fromarray(lat2_image).save("flux_outputs/flux_tile_2.png")
    Image.fromarray(tiled_image).save("flux_outputs/flux_tiled_result.png")

    print("Images saved to flux_outputs/:")
    print("- flux_tile_1.png (Red brick texture)")
    print("- flux_tile_2.png (Green brick texture)")
    print("- flux_tiled_result.png (Combined tiling demonstration)")

    # Also save with timestamp for multiple runs
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    Image.fromarray(lat1_image).save(f"flux_outputs/flux_tile_1_{timestamp}.png")
    # Image.fromarray(lat2_image).save(f"flux_outputs/flux_tile_2_{timestamp}.png")
    Image.fromarray(tiled_image).save(f"flux_outputs/flux_tiled_result_{timestamp}.png")

    print(f"\nTimestamped copies saved with suffix: {timestamp}")


if __name__ == "__main__":
    main()

hoagy-davis-digges avatar Jun 03 '25 20:06 hoagy-davis-digges