text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
latents = callback_outputs.pop("latents", latents)
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
# call the callback, if provided
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
... | 171 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_inpaint.py |
return FluxPipelineOutput(images=image) | 171 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_inpaint.py |
class FluxImg2ImgPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
r"""
The Flux pipeline for image inpainting.
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/ | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
Args:
transformer ([`FluxTransformer2DModel`]):
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
Tokenizer of class
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
tokenizer_2 (`T5TokenizerFast`):
Second Tokenizer of class
[T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Toke... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
_optional_components = []
_callback_tensor_inputs = ["latents", "prompt_embeds"]
def __init__(
self,
scheduler: FlowMatchEulerDiscreteScheduler,
vae: AutoencoderKL,
text_encoder: CLIPTextModel,
... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
self.register_modules(
vae=vae,
text_encoder=text_encoder,
text_encoder_2=text_encoder_2,
tokenizer=tokenizer,
tokenizer_2=tokenizer_2,
transformer=transformer,
scheduler=scheduler,
)
self.vae_scale_factor = 2 ** (len(se... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
def _get_t5_prompt_embeds(
self,
prompt: Union[str, List[str]] = None,
num_images_per_prompt: int = 1,
max_sequence_length: int = 512,
device: Optional[torch.device] = None,
dtype:... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
text_inputs = self.tokenizer_2(
prompt,
padding="max_length",
max_length=max_sequence_length,
truncation=True,
return_length=False,
return_overflowing_tokens=False,
return_tensors="pt",
)
text_input_ids = text_inputs.inp... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
dtype = self.text_encoder_2.dtype
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
_, seq_len, _ = prompt_embeds.shape
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_images... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
text_inputs = self.tokenizer(
prompt,
padding="max_length",
max_length=self.tokenizer_max_length,
truncation=True,
return_overflowing_tokens=False,
return_length=False,
return_tensors="pt",
)
text_input_ids = text_input... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# Use pooled output of CLIPTextModel
prompt_embeds = prompt_embeds.pooler_output
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
# duplicate text embeddings for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, n... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
Args:
prompt (`str` or `List[str]`, *optional*):
prompt to be encoded
prompt_2 (`str` or `List[str]`, *optional*):
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
used in all text-encoders
... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
If not provided, pooled text embeddings will be generated from `prompt` input argument.
lora_scale (`float`, *optional*):
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
"""
device = device or self._execution_device | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# set lora scale so that monkey patched LoRA
# function of text encoder can correctly access it
if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
self._lora_scale = lora_scale
# dynamically adjust the LoRA scale
if self.text_encoder is not None and... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# We only use the pooled prompt output from the CLIPTextModel
pooled_prompt_embeds = self._get_clip_prompt_embeds(
prompt=prompt,
device=device,
num_images_per_prompt=num_images_per_prompt,
)
prompt_embeds = self._get_t5_prompt_embeds(
... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
if self.text_encoder_2 is not None:
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
# Retrieve the original scale by scaling back the LoRA layers
unscale_lora_layers(self.text_encoder_2, lora_scale)
dtype = self.text_encoder.dtype if self.text_encoder ... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
if isinstance(generator, list):
image_latents = [
retrieve_late... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
def get_timesteps(self, num_inference_steps, strength, device):
# get the original timestep using init_timestep
init_timestep = min(num_inference_steps * strength, n... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
def check_inputs(
self,
prompt,
prompt_2,
strength,
height,
width,
prompt_embeds=None,
pooled_prompt_embeds=None,
callback_on_step_end_tensor_inputs=None,
max_sequence_length=None,
):
if strength < 0 or strength > 1:
... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
if callback_on_step_end_tensor_inputs is not None and not all(
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
):
raise ValueError(
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in cal... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
if prompt is not None and prompt_embeds is not None:
raise ValueError(
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
" only forward one of the two."
)
elif prompt_2 is not None and prompt_embeds is not ... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}") | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
if prompt_embeds is not None and pooled_prompt_embeds is None:
raise ValueError(
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
)
... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
latent_image_ids = latent_image_ids.reshape(
latent_image_id_height * latent_image_id_width, latent_image_id_channels
)
return latent_image_ids.to(device=device, dtype=dtype)
@stat... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# VAE applies 8x compression on images but we must also account for packing which requires
# latent height and width to be divisible by 2.
height = 2 * (int(height) // (vae_scale_factor * 2))
width = 2 * (int(width) // (vae_scale_factor * 2))
latents = latents.view(batch_size, height //... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
def prepare_latents(
self,
image,
timestep,
batch_size,
num_channels_latents,
height,
width,
dtype,
device,
generator,
latents=None,
):
if isinstance(generator, list) and len(generator) != batch_size:
raise V... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# VAE applies 8x compression on images but we must also account for packing which requires
# latent height and width to be divisible by 2.
height = 2 * (int(height) // (self.vae_scale_factor * 2))
width = 2 * (int(width) // (self.vae_scale_factor * 2))
shape = (batch_size, num_channels_l... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
image = image.to(device=device, dtype=dtype)
image_latents = self._encode_vae_image(image=image, generator=generator)
if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
# expand init_latents for batch_size
additional_image_per_prompt = batch_size... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
latents = self.scheduler.scale_noise(image_latents, timestep, noise)
latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
return latents, latent_image_ids
@property
def guidanc... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
@torch.no_grad()
@replace_example_docstring(EXAMPLE_DOC_STRING)
def __call__(
self,
prompt: Union[str, List[str]] = None,
prompt_2: Optional[Union[str, List[str]]] = None,
image: PipelineImageInput = None,
height: Optional[int] = None,
width: Optional[int] = None,... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
max_sequence_length: int = 512,
):
r"""
Function invoked when calling the pipeline for generation. | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
Args:
prompt (`str` or `List[str]`, *optional*):
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
instead.
prompt_2 (`str` or `List[str]`, *optional*):
The prompt or prompts to be sent to `tokeni... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
list of arrays, the expected shape should be `(B, H, W, C)` or `(H, W, C)` It can also accept image
latents as `image`, but if passing latents directly it is not encoded again.
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
The h... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
essentially ignores `image`.
num_inference_steps (`int`, *optional*, defaults... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
`guidance_scale` is defined as `w` of equation 2. of [Imagen
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
usually ... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
tensor will ge generated by sampling using the supplied random `generator`.
prompt_embeds (`torch.FloatTensor`, *optional*):
Pre-generated text embeddings. Can be used to e... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
return_dict (`bool`, *optional*, defaults to `True`):
Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
joint_attention_kwargs (`dict`, *optional*):
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as ... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
callback_on_step_end_tensor_inputs (`List`, *optional*):
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
`._callback... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
Examples:
Returns:
[`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
images.
"""
height = height or ... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# 2. Preprocess image
init_image = self.image_processor.preprocess(image, height=height, width=width)
init_image = init_image.to(dtype=torch.float32)
# 3. Define call parameters
if prompt is not None and isinstance(prompt, str):
batch_size = 1
elif prompt is not None... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
lora_scale = (
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
)
(
prompt_embeds,
pooled_prompt_embeds,
text_ids,
) = self.encode_prompt(
prompt=prompt,
prompt_2=prompt_2,
... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# 4.Prepare timesteps
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
mu = calculate_shift(
image_seq_len,
self.s... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
if num_inference_steps < 1:
raise ValueError(
f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline"
f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline."
)
latent_timestep = tim... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# handle guidance
if self.transformer.config.guidance_embeds:
guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
guidance = guidance.expand(latents.shape[0])
else:
guidance = None
# 6. Denoising loop
with self.progress_bar(... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
timestep = t.expand(latents.shape[0]).to(latents.dtype)
noise_pred = self.transformer(
hidden_states=latents,
timestep=timestep / 1000,
guidance=guidanc... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
if latents.dtype != latents_dtype:
if torch.backends.mps.is_available():
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
latents = latents.to(latents_dtype)
if callback_on_... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
if XLA_AVAILABLE:
xm.mark_step()
if output_type == "latent":
image = latents
else:
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
... | 172 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_img2img.py |
class FluxControlNetImg2ImgPipeline(DiffusionPipeline, FluxLoraLoaderMixin, FromSingleFileMixin):
r"""
The Flux controlnet pipeline for image-to-image generation.
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/ | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
Args:
transformer ([`FluxTransformer2DModel`]):
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
Tokenizer of class
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
tokenizer_2 (`T5TokenizerFast`):
Second Tokenizer of class
[T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5Toke... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
_optional_components = []
_callback_tensor_inputs = ["latents", "prompt_embeds"]
def __init__(
self,
scheduler: FlowMatchEulerDiscreteScheduler,
vae: AutoencoderKL,
text_encoder: CLIPTextModel,
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
self.register_modules(
vae=vae,
text_encoder=text_encoder,
text_encoder_2=text_encoder_2,
tokenizer=tokenizer,
tokenizer_2=tokenizer_2,
transformer=transformer,
scheduler=scheduler,
controlnet=controlnet,
)
s... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# Copied from diffusers.pipelines.flux.pipeline_flux.FluxPipeline._get_t5_prompt_embeds
def _get_t5_prompt_embeds(
self,
prompt: Union[str, List[str]] = None,
num_images_per_prompt: int = 1,
max_sequence_length: int = 512,
device: Optional[torch.device] = None,
dtype:... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
text_inputs = self.tokenizer_2(
prompt,
padding="max_length",
max_length=max_sequence_length,
truncation=True,
return_length=False,
return_overflowing_tokens=False,
return_tensors="pt",
)
text_input_ids = text_inputs.inp... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
dtype = self.text_encoder_2.dtype
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
_, seq_len, _ = prompt_embeds.shape
# duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, num_images... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
text_inputs = self.tokenizer(
prompt,
padding="max_length",
max_length=self.tokenizer_max_length,
truncation=True,
return_overflowing_tokens=False,
return_length=False,
return_tensors="pt",
)
text_input_ids = text_input... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# Use pooled output of CLIPTextModel
prompt_embeds = prompt_embeds.pooler_output
prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
# duplicate text embeddings for each generation per prompt, using mps friendly method
prompt_embeds = prompt_embeds.repeat(1, n... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
Args:
prompt (`str` or `List[str]`, *optional*):
prompt to be encoded
prompt_2 (`str` or `List[str]`, *optional*):
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
used in all text-encoders
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
If not provided, pooled text embeddings will be generated from `prompt` input argument.
lora_scale (`float`, *optional*):
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
"""
device = device or self._execution_device | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# set lora scale so that monkey patched LoRA
# function of text encoder can correctly access it
if lora_scale is not None and isinstance(self, FluxLoraLoaderMixin):
self._lora_scale = lora_scale
# dynamically adjust the LoRA scale
if self.text_encoder is not None and... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# We only use the pooled prompt output from the CLIPTextModel
pooled_prompt_embeds = self._get_clip_prompt_embeds(
prompt=prompt,
device=device,
num_images_per_prompt=num_images_per_prompt,
)
prompt_embeds = self._get_t5_prompt_embeds(
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if self.text_encoder_2 is not None:
if isinstance(self, FluxLoraLoaderMixin) and USE_PEFT_BACKEND:
# Retrieve the original scale by scaling back the LoRA layers
unscale_lora_layers(self.text_encoder_2, lora_scale)
dtype = self.text_encoder.dtype if self.text_encoder ... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_inpaint.StableDiffusion3InpaintPipeline._encode_vae_image
def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator):
if isinstance(generator, list):
image_latents = [
retrieve_late... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# Copied from diffusers.pipelines.stable_diffusion_3.pipeline_stable_diffusion_3_img2img.StableDiffusion3Img2ImgPipeline.get_timesteps
def get_timesteps(self, num_inference_steps, strength, device):
# get the original timestep using init_timestep
init_timestep = min(num_inference_steps * strength, n... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
def check_inputs(
self,
prompt,
prompt_2,
strength,
height,
width,
callback_on_step_end_tensor_inputs,
prompt_embeds=None,
pooled_prompt_embeds=None,
max_sequence_length=None,
):
if strength < 0 or strength > 1:
rais... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if callback_on_step_end_tensor_inputs is not None and not all(
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
):
raise ValueError(
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in cal... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if prompt is not None and prompt_embeds is not None:
raise ValueError(
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
" only forward one of the two."
)
elif prompt_2 is not None and prompt_embeds is not ... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}") | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if prompt_embeds is not None and pooled_prompt_embeds is None:
raise ValueError(
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
)
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
latent_image_id_height, latent_image_id_width, latent_image_id_channels = latent_image_ids.shape
latent_image_ids = latent_image_ids.reshape(
latent_image_id_height * latent_image_id_width, latent_image_id_channels
)
return latent_image_ids.to(device=device, dtype=dtype)
@stat... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# VAE applies 8x compression on images but we must also account for packing which requires
# latent height and width to be divisible by 2.
height = 2 * (int(height) // (vae_scale_factor * 2))
width = 2 * (int(width) // (vae_scale_factor * 2))
latents = latents.view(batch_size, height //... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# Copied from diffusers.pipelines.flux.pipeline_flux_img2img.FluxImg2ImgPipeline.prepare_latents
def prepare_latents(
self,
image,
timestep,
batch_size,
num_channels_latents,
height,
width,
dtype,
device,
generator,
latents=None... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
# VAE applies 8x compression on images but we must also account for packing which requires
# latent height and width to be divisible by 2.
height = 2 * (int(height) // (self.vae_scale_factor * 2))
width = 2 * (int(width) // (self.vae_scale_factor * 2))
shape = (batch_size, num_channels_l... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
image = image.to(device=device, dtype=dtype)
image_latents = self._encode_vae_image(image=image, generator=generator)
if batch_size > image_latents.shape[0] and batch_size % image_latents.shape[0] == 0:
# expand init_latents for batch_size
additional_image_per_prompt = batch_size... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
latents = self.scheduler.scale_noise(image_latents, timestep, noise)
latents = self._pack_latents(latents, batch_size, num_channels_latents, height, width)
return latents, latent_image_ids
# Copied from diffusers.p... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if image_batch_size == 1:
repeat_by = batch_size
else:
# image batch size is the same as prompt batch size
repeat_by = num_images_per_prompt
image = image.repeat_interleave(repeat_by, dim=0)
image = image.to(device=device, dtype=dtype)
if do_classif... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
@torch.no_grad()
@replace_example_docstring(EXAMPLE_DOC_STRING)
def __call__(
self,
prompt: Union[str, List[str]] = None,
prompt_2: Optional[Union[str, List[str]]] = None,
image: PipelineImageInput = None,
control_image: PipelineImageInput = None,
height: Optional... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
prompt_embeds: Optional[torch.FloatTensor] = None,
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
output_type: Optional[str] = "pil",
return_dict: bool = True,
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
callback_on_step_end: Optional[Callable[[int, int, D... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
Args:
prompt (`str` or `List[str]`, *optional*):
The prompt or prompts to guide the image generation.
prompt_2 (`str` or `List[str]`, *optional*):
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`.
image (`PIL.Image.Image` or `... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1.
num_inference_steps (`int`, *optional*, defaults to 28):
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
to the residual in the original transformer.
num_images_per_prompt (`int`, *optional*, ... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
Pre-generated pooled text embeddings.
output_type (`str`, *optional*, defaults to `"pil"`):
The output format o... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
The list of tensor inputs for the `callback_on_step_end` function.
max_sequence_length (`int`, *optional*, defaults to 512):
The maximum length of the sequence to be generated. | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
Examples:
Returns:
[`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
images.
"""
height = height or s... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
control_guidance_start = len(control_guidance_end) * [control_guidance_start]
elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
control_guidance_end = l... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
self.check_inputs(
prompt,
prompt_2,
strength,
height,
width,
callback_on_step_end_tensor_inputs,
prompt_embeds=prompt_embeds,
pooled_prompt_embeds=pooled_prompt_embeds,
max_sequence_length=max_sequence_length,
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
lora_scale = (
self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
)
(
prompt_embeds,
pooled_prompt_embeds,
text_ids,
) = self.encode_prompt(
prompt=prompt,
prompt_2=prompt_2,
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if isinstance(self.controlnet, FluxControlNetModel):
control_image = self.prepare_image(
image=control_image,
width=width,
height=height,
batch_size=batch_size * num_images_per_prompt,
num_images_per_prompt=num_images_per_prompt... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if control_mode is not None:
control_mode = torch.tensor(control_mode).to(device, dtype=torch.long)
control_mode = control_mode.reshape([-1, 1])
elif isinstance(self.controlnet, FluxMultiControlNetModel):
control_images = []
for control_image_ in control... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
height_control_image, width_control_image = control_image_.shape[2:]
control_image_ = self._pack_latents(
control_image_,
batch_size * num_images_per_prompt,
num_channels_latents,
height_control_image,
wi... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
image_seq_len = (int(height) // self.vae_scale_factor // 2) * (int(width) // self.vae_scale_factor // 2)
mu = calculate_shift(
image_seq_len,
self.scheduler.config.get("base_imag... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
latents, latent_image_ids = self.prepare_latents(
init_image,
latent_timestep,
batch_size * num_images_per_prompt,
num_channels_latents,
height,
width,
p... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
with self.progress_bar(total=num_inference_steps) as progress_bar:
for i, t in enumerate(timesteps):
if self.interrupt:
continue
timestep = t.expand(latents.shape[0]).to(latents.dtype)
if isinstance(self.controlnet, FluxMultiControlNetMod... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if isinstance(controlnet_keep[i], list):
cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
else:
controlnet_cond_scale = controlnet_conditioning_scale
if isinstance(controlnet_cond_scale, list):
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
hidden_states=latents,
controlnet_cond=control_image,
controlnet_mode=control_mode,
conditioning_scale=cond_scale,
timestep=timestep / 1000,
... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
noise_pred = self.transformer(
hidden_states=latents,
timestep=timestep / 1000,
guidance=guidance,
pooled_projections=pooled_prompt_embeds,
encoder_hidden_states=prompt_embeds,
controlnet_block_sample... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if callback_on_step_end is not None:
callback_kwargs = {}
for k in callback_on_step_end_tensor_inputs:
callback_kwargs[k] = locals()[k]
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
latents = ... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
if output_type == "latent":
image = latents
else:
latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
image = self.vae.decode(latents, return_dict=False)[... | 173 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_controlnet_image_to_image.py |
class FluxControlPipeline(
DiffusionPipeline,
FluxLoraLoaderMixin,
FromSingleFileMixin,
TextualInversionLoaderMixin,
):
r"""
The Flux pipeline for controllable text-to-image generation.
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/ | 174 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/flux/pipeline_flux_control.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.