import numpy as np
from PIL import Image
import cv2
import torch
count = 0
import torch
import numpy as np
from PIL import Image, ExifTags
from einops import rearrange
from transformers import pipeline
import tqdm
import random
from pathlib import Path
from flux.cli import SamplingOptions
from flux.sampling import denoise, get_noise, get_schedule, prepare, unpack
from flux.util import configs, embed_watermark, load_ae, load_clip, load_flow_model, load_t5
gender = random.choice(["male", "female"])
ethnicity = random.choice(ethnicities)
skin_tone = random.choice(skin_tones)
body_type = random.choice(body_types)
clothing = random.choice(["traditional", "modern", "casual", "formal", "ethnic", "professional", "sporty"])
colors = ["red", "blue", "green", "yellow", "purple", "orange", "white", "black", "pink", "teal", "maroon", "navy"]
color = random.choice(colors)
if gender == "female":
outfit = random.choice(["sari", "lehenga", "salwar kameez", "dress", "skirt and top", "jeans and blouse", "pantsuit"])
hair = random.choice(["long", "short", "curly", "straight", "wavy", "braided", "updone"])
accessory = random.choice(["necklace", "earrings", "bangles", "anklets", "bindi", "scarf", "handbag"])
else:
outfit = random.choice(["kurta pajama", "sherwani", "dhoti", "shirt and pants", "suit", "jeans and t-shirt", "traditional ethnic wear"])
hair = random.choice(["short", "medium-length", "styled", "messy", "neat", "bald", "beard"])
accessory = random.choice(["turban", "pagri", "watch", "scarf", "sunglasses", "tie", "belt"])
prompt = f"A character sheet of a {gender} {ethnicity} person with {skin_tone} skin and a {body_type} build, "
prompt += f"wearing a {color} {clothing} {outfit} with {hair} hair, "
prompt += f"adorned with a {accessory}. In different poses and angles, including front view, side view, back view, and three-quarter view."
return prompt
def generate_dataset(total_images, batch_size, flux_img2img):
global count
output_dir = Path("/ihub/homedirs/vp_hc/neuralnexus/InfiniGPT/dataset/output_batched")
output_dir.mkdir(exist_ok=True)
code
for _ in tqdm.tqdm(range(total_images // batch_size)):
prompts = [generate_prompt() for _ in range(batch_size)]
init_images = [Image.open("/ihub/homedirs/vp_hc/neuralnexus/InfiniGPT/dataset/reference2.jpg") for _ in range(batch_size)]
init_images = [torch.from_numpy(np.array(img)).permute(2, 0, 1).float() / 255.0 for img in init_images]
init_images = [img.unsqueeze(0) for img in init_images]
results = flux_img2img.generate(
init_images=init_images,
prompts=prompts,
width=1024,
height=720,
num_steps=40,
guidance=3.5,
seeds=[-1] * batch_size,
image2image_strength=0.9
)
for i, (result_image, seed, output_path, warning) in enumerate(results):
if result_image:
output_file = output_dir / f"output_{count:06d}.jpg"
result_image.save(output_file)
count +=1
print(f"Total images generated: {count}")
if name == "main":
flux_img2img = FluxImageToImage(model_name="flux-dev", devices=["cuda"])
generate_dataset(total_images=100000, batch_size=25, flux_img2img=flux_img2img)
the above code is wrong for batched generation. Please correct it properly its not working as intended
To correct the batched generation in your FluxImageToImage class, we need to modify the generate method to handle batches of images and prompts efficiently. The current implementation processes each image individually within a loop, which doesn't leverage the benefits of batch processing (such as improved performance and utilization of GPU resources).
Below is the revised version of your code with detailed explanations of the changes made to support proper batched generation:
python
import numpy as np
from PIL import Image
import cv2
import torch
import torch
import numpy as np
from PIL import Image, ExifTags
from einops import rearrange
from transformers import pipeline
import tqdm
import random
from pathlib import Path
from flux.cli import SamplingOptions
from flux.sampling import denoise, get_noise, get_schedule, prepare, unpack
from flux.util import configs, embed_watermark, load_ae, load_clip, load_flow_model, load_t5
def get_models(name: str, device: torch.device, offload: bool, is_schnell: bool):
t5 = load_t5(device, max_length=256 if is_schnell else 512)
clip = load_clip(device)
model = load_flow_model(name, device="cpu" if offload else device)
ae = load_ae(name, device="cpu" if offload else device)
return model, ae, t5, clip
class FluxImageToImage:
def __init__(self, model_name: str, devices: list = None, offload: bool = False):
self.devices = devices if devices else ["cuda:0", "cuda:1"]
self.offload = offload
self.model_name = model_name
self.is_schnell = model_name == "flux-schnell"
self.models = [get_models(model_name, torch.device(d), offload, self.is_schnell) for d in self.devices]
@torch.inference_mode()
def generate(
self,
init_images,
prompts,
width=1024,
height=720,
num_steps=40,
guidance=3.5,
seeds=None,
image2image_strength=0.9,
add_sampling_metadata=True,
):
batch_size = len(init_images)
seeds = seeds or [-1] * batch_size
opts = [SamplingOptions(prompt=prompts[i], width=width, height=height, num_steps=num_steps, guidance=guidance, seed=seeds[i]) for i in range(batch_size)]
# Fix for random seed generation
for idx in range(batch_size):
if seeds[idx] == -1:
seeds[idx] = torch.Generator(device="cpu").seed()
results = []
device_batches = [[] for _ in self.devices]
# Distribute indices across devices in a round-robin fashion
for idx in range(batch_size):
device_idx = idx % len(self.devices)
device_batches[device_idx].append(idx)
for device_idx, device in enumerate(self.devices):
indices = device_batches[device_idx]
if not indices:
continue # Skip if no images are assigned to this device
model, ae, t5, clip = self.models[device_idx]
device_obj = torch.device(device)
# Prepare batch data
batch_prompts = [opts[idx].prompt for idx in indices]
batch_seeds = [opts[idx].seed for idx in indices]
# Load and preprocess init_images in batch
batch_init_images = torch.stack([init_images[idx] for idx in indices]).to(device_obj)
batch_init_images = torch.nn.functional.interpolate(batch_init_images, size=(height, width))
if self.offload:
ae.encoder.to(device_obj)
encoded_batch = ae.encode(batch_init_images)
if self.offload:
ae.encoder.cpu()
torch.cuda.empty_cache()
# Generate noise for the entire batch
noise_batch = []
generators = []
for seed in batch_seeds:
generator = torch.Generator(device=device_obj).manual_seed(seed)
generators.append(generator)
noise = get_noise(
1,
height,
width,
device=device_obj,
dtype=torch.bfloat16,
generator=generator,
)
noise_batch.append(noise)
x = torch.cat(noise_batch, dim=0) # Shape: [batch_size, C, H, W]
# Get the schedule and adjust timesteps
timesteps = get_schedule(
num_steps,
height * width // 4,
shift=(not self.is_schnell),
)
t_idx = int((1 - image2image_strength) * num_steps)
selected_timesteps = timesteps[t_idx:]
t = timesteps[t_idx]
# Adjust noise with timesteps and image strength
x = t * x + (1.0 - t) * encoded_batch.to(x.dtype)
if self.offload:
t5.to(device_obj)
clip.to(device_obj)
# Prepare inputs for the model in batch
inp = prepare(t5=t5, clip=clip, img=x, prompt=batch_prompts)
if self.offload:
t5.cpu()
clip.cpu()
torch.cuda.empty_cache()
model.to(device_obj)
# Perform denoising in batch
x = denoise(model, **inp, timesteps=selected_timesteps, guidance=guidance)
if self.offload:
model.cpu()
torch.cuda.empty_cache()
ae.decoder.to(device_obj)
# Unpack the denoised outputs
x = unpack(x.float(), height, width)
# Decode the images in batch
with torch.autocast(device_type=device_obj.type, dtype=torch.bfloat16):
decoded = ae.decode(x)
if self.offload:
ae.decoder.cpu()
torch.cuda.empty_cache()
# Post-process the batch of images
decoded = decoded.clamp(-1, 1)
decoded = embed_watermark(decoded.float())
decoded = rearrange(decoded, "n c h w -> n h w c") # Shape: [batch_size, H, W, C]
# Convert tensors to PIL Images and prepare results
for i in range(decoded.shape[0]):
img_tensor = decoded[i]
img_array = (127.5 * (img_tensor + 1.0)).cpu().byte().numpy()
img = Image.fromarray(img_array)
# Optionally, add EXIF metadata here if needed
# Example (commented out as in original code):
# nsfw_score = 0.7
# if nsfw_score < 0.85:
# exif_data = Image.Exif()
# exif_data[ExifTags.Base.Software] = "AI generated;img2img;flux"
# exif_data[ExifTags.Base.Make] = "Black Forest Labs"
# exif_data[ExifTags.Base.Model] = self.model_name
# if add_sampling_metadata:
# exif_data[ExifTags.Base.ImageDescription] = batch_prompts[i]
# output_file = f"output_{device_idx}_{i}.jpg"
# img.save(output_file, format="jpeg", exif=exif_data, quality=95, subsampling=0)
# results.append((img, str(batch_seeds[i]), str(output_file), None))
# else:
# results.append((None, str(batch_seeds[i]), None, "Your generated image may contain NSFW content."))
# For simplicity, saving without EXIF metadata
output_file = f"output_{device_idx}_{i}.jpg"
results.append((img, str(batch_seeds[i]), str(output_file), None))
# Clear variables to free up memory
del batch_init_images, encoded_batch, noise_batch, x, decoded
torch.cuda.empty_cache()
return results
def generate_prompt():
ethnicities = ["Asian", "African", "European", "Middle Eastern", "Latin American", "South Asian", "Southeast Asian", "Pacific Islander"]
skin_tones = ["fair", "light", "medium", "olive", "brown", "dark"]
body_types = ["slim", "athletic", "curvy", "plus-size", "muscular", "petite"]
gender = random.choice(["male", "female"])
ethnicity = random.choice(ethnicities)
skin_tone = random.choice(skin_tones)
body_type = random.choice(body_types)
clothing = random.choice(["traditional", "modern", "casual", "formal", "ethnic", "professional", "sporty"])
colors = ["red", "blue", "green", "yellow", "purple", "orange", "white", "black", "pink", "teal", "maroon", "navy"]
color = random.choice(colors)
if gender == "female":
outfit = random.choice(["sari", "lehenga", "salwar kameez", "dress", "skirt and top", "jeans and blouse", "pantsuit"])
hair = random.choice(["long", "short", "curly", "straight", "wavy", "braided", "updone"])
accessory = random.choice(["necklace", "earrings", "bangles", "anklets", "bindi", "scarf", "handbag"])
else:
outfit = random.choice(["kurta pajama", "sherwani", "dhoti", "shirt and pants", "suit", "jeans and t-shirt", "traditional ethnic wear"])
hair = random.choice(["short", "medium-length", "styled", "messy", "neat", "bald", "beard"])
accessory = random.choice(["turban", "pagri", "watch", "scarf", "sunglasses", "tie", "belt"])
prompt = f"A character sheet of a {gender} {ethnicity} person with {skin_tone} skin and a {body_type} build, "
prompt += f"wearing a {color} {clothing} {outfit} with {hair} hair, "
prompt += f"adorned with a {accessory}. In different poses and angles, including front view, side view, back view, and three-quarter view."
return prompt
def generate_dataset(total_images, batch_size, flux_img2img):
global count
count = 0 # Initialize count here to avoid issues if generate_dataset is called multiple times
output_dir = Path("/ihub/homedirs/vp_hc/neuralnexus/InfiniGPT/dataset/output_batched")
output_dir.mkdir(parents=True, exist_ok=True)
num_batches = total_images // batch_size
for _ in tqdm.tqdm(range(num_batches)):
prompts = [generate_prompt() for _ in range(batch_size)]
init_image_path = "/ihub/homedirs/vp_hc/neuralnexus/InfiniGPT/dataset/reference2.jpg"
# Load the reference image once and replicate it
reference_image = Image.open(init_image_path).convert("RGB")
init_images = [torch.from_numpy(np.array(reference_image)).permute(2, 0, 1).float() / 255.0 for _ in range(batch_size)]
init_images = [img.unsqueeze(0) for img in init_images]
init_images = torch.cat(init_images, dim=0) # Shape: [batch_size, C, H, W]
results = flux_img2img.generate(
init_images=init_images,
prompts=prompts,
width=1024,
height=720,
num_steps=40,
guidance=3.5,
seeds=[-1] * batch_size,
image2image_strength=0.9
)
for i, (result_image, seed, output_path, warning) in enumerate(results):
if result_image:
output_file = output_dir / f"output_{count:06d}.jpg"
result_image.save(output_file)
count += 1
print(f"Total images generated: {count}")
if __name__ == "__main__":
flux_img2img = FluxImageToImage(model_name="flux-dev", devices=["cuda"], offload=False)
generate_dataset(total_images=100000, batch_size=25, flux_img2img=flux_img2img)
Key Changes and Explanations
Batch Processing in generate Method:
Distribution of Indices: Instead of assigning individual images and processing them one by one, we distribute the indices of the images to each device. This allows us to process multiple images on a single device simultaneously.
Batch Preparation: For each device, we gather all assigned images and prompts into batches. This is done by stacking the tensors and preparing a list of prompts corresponding to the batch.
Noise Generation: Noise is generated for the entire batch at once. Each image in the batch gets its own noise tensor based on its seed.
Denoising in Batch: The denoise function is called once per batch, allowing the model to process multiple images in parallel.
Decoding and Post-processing: After denoising, the batch of images is decoded and post-processed together. Each image in the batch is then converted to a PIL Image and appended to the results.
Optimizing Image Loading in generate_dataset:
Single Image Loading: The reference image is loaded once per batch and then replicated across the batch. This reduces I/O overhead and speeds up the dataset generation process.
Tensor Concatenation: Instead of having a list of tensors, we concatenate them into a single tensor with a batch dimension. This is more efficient for GPU processing.
Memory Management:
Clearing Variables: After processing each batch, we explicitly delete variables and call torch.cuda.empty_cache() to free up GPU memory. This prevents memory leaks and ensures that subsequent batches have sufficient memory available.
Unique Output Filenames:
Distinct Naming: Modified the output filename to include both the device index and the image index within the batch to ensure uniqueness (f"output_{device_idx}_{i}.jpg").
Consistent Counting: The global count variable is used in generate_dataset to assign a unique sequential ID to each saved image.
Optional EXIF Metadata:
Commented Out Code: The original code included commented-out sections for adding EXIF metadata. Depending on your requirements, you can uncomment and modify this section to embed metadata into the generated images.
Additional Recommendations
Error Handling: Implement try-except blocks to handle potential errors during image processing, model inference, or file I/O operations. This ensures that the dataset generation process is robust and can recover or skip problematic batches.
Progress Monitoring: While tqdm provides a progress bar, consider logging more detailed information, such as batch processing times or device memory usage, to monitor performance and identify bottlenecks.
Configuration Management: Externalize configuration parameters (like model names, device lists, paths) using a configuration file or environment variables. This makes the code more flexible and easier to manage.
Parallelism Enhancements: Depending on your hardware and the nature of the flux library, further optimizations like asynchronous data loading or leveraging mixed precision can be explored to enhance performance.
Conclusion
By restructuring the generate method to handle batches of images and prompts together, we leverage the parallel processing capabilities of modern GPUs, leading to significant performance improvements. Additionally, optimizing data loading and memory management ensures that the dataset generation process is efficient and scalable.
Even Distribution: Ensure that the total_images is divisible by batch_size. If not, you might need to handle the last batch separately or adjust the total number of images accordingly.
Seed Handling:
Per-Image Seeds: Each image in the batch can have its own seed, enabling diversity in the generated images even within the same batch.