Spaces:
Paused
Paused
Update tqdm descriptions
Browse filesFiles changed (3)
- addit_flux_pipeline.py+159-164
- addit_methods.py+8-2
- app.py+7-7
16 unmodified lines171819202122152 unmodified lines175176177178179180220 unmodified lines4014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514 unmodified lines456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502290 unmodified lines793794795796797798188 unmodified lines98798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103590 unmodified lines112611271128112911301131196 unmodified lines13281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138716 unmodified lines# This work is licensed under the LICENSE file# located at the root directory.from typing import Any, Callable, Dict, List, Optional, Unionimport torchimport numpy as np152 unmodified linesis_img_src: bool = False,use_offset: bool = False,img_src_latents: Optional[List[torch.FloatTensor]] = None,):r"""Function invoked when calling the pipeline for generation.220 unmodified linesimg_src_latents.append((1.0 - sigma) * source_latents[0] + sigma * rand_noise)# 6. Denoising loopwith self.progress_bar(total=num_inference_steps) as progress_bar:for i, t in enumerate(timesteps):if self.interrupt:continue# broadcast to batch dimension in a way that's compatible with ONNX/Core MLtimestep = t.expand(latents.shape[0]).to(latents.dtype)# For denoising from source imageif is_img_src:latents[0] = img_src_latents[i]# For Structure Transferif (source_latents is not None) and i == structure_transfer_step:sigma = self.scheduler.sigmas[i]latents[1] = (1.0 - sigma) * source_latents[0] + sigma * noise[1]if is_auto_extend_scale and i == auto_extended_step:def f(gamma):self.attention_store.attention_ratios[i] = {}noise_pred = self.transformer(hidden_states=latents,timestep=timestep / 1000,guidance=guidance,pooled_projections=pooled_prompt_embeds,encoder_hidden_states=prompt_embeds,txt_ids=text_ids,img_ids=latent_image_ids,joint_attention_kwargs=self.joint_attention_kwargs,return_dict=False,proccesor_kwargs={"step_index": i, "extended_scale": gamma},)[0]scores_per_layer = self.attention_store.get_attention_ratios(step_indices=[i], display_imgs=False)source_sum, text_sum, target_sum = scores_per_layer['transformer_blocks']# We want to find the gamma that makes the ratio equal to Kratio = (target_sum / source_sum)return (ratio - target_auto_ratio)gamma_sol = brentq(f, 1.0, 1.2, xtol=0.01)print('Chosen gamma:', gamma_sol)extended_scale = gamma_solelse:noise_pred = self.transformer(hidden_states=latents,timestep=timestep / 1000,4 unmodified linesimg_ids=latent_image_ids,joint_attention_kwargs=self.joint_attention_kwargs,return_dict=False,proccesor_kwargs={"step_index": i, "extended_scale": extended_scale},)[0]# compute the previous noisy sample x_t -> x_t-1latents_dtype = latents.dtypelatents, x0 = self.scheduler.step(noise_pred, t, latents, return_dict=False, step_index=i)if use_offset and is_img_src and (i+1 < len(img_src_latents)):next_latent = img_src_latents[i+1]offset = (next_latent - latents[0])latents[1] = latents[1] + offset# blend latentsif i in blend_steps and (subject_token is not None) and (localization_model is not None):x0 = self._unpack_latents(x0, height, width, self.vae_scale_factor)x0 = (x0 / self.vae.config.scaling_factor) + self.vae.config.shift_factorimages = self.vae.decode(x0, return_dict=False)[0]images = self.image_processor.postprocess(images, output_type="pil")self.do_step_blend(images, latents, subject_token, localization_model, show_attention, i, blend_models)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/99272latents = latents.to(latents_dtype)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 = callback_outputs.pop("latents", latents)prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)# call the callback, if providedif i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):progress_bar.update()# if XLA_AVAILABLE:# xm.mark_step()if output_type == "latent":image = latents290 unmodified linescallback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,callback_on_step_end_tensor_inputs: List[str] = ["latents"],max_sequence_length: int = 512,):r"""Function invoked when calling the pipeline for generation.188 unmodified lineslatent_image_ids = latent_image_ids.expand(latents.shape[0], -1, -1)# 6. Denoising loopwith self.progress_bar(total=num_inference_steps) as progress_bar:for i, t in enumerate(timesteps):if self.interrupt:continue# broadcast to batch dimension in a way that's compatible with ONNX/Core MLtimestep = t.expand(latents.shape[0]).to(latents.dtype)noise_pred = self.transformer(hidden_states=latents,timestep=timestep / 1000,guidance=guidance,pooled_projections=pooled_prompt_embeds,encoder_hidden_states=prompt_embeds,txt_ids=text_ids,img_ids=latent_image_ids,joint_attention_kwargs=self.joint_attention_kwargs,return_dict=False,)[0]# compute the previous noisy sample x_t -> x_t-1latents_dtype = latents.dtypelatents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]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/99272latents = latents.to(latents_dtype)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 = callback_outputs.pop("latents", latents)prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)# call the callback, if providedif i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):progress_bar.update()# if XLA_AVAILABLE:# xm.mark_step()if output_type == "latent":image = latents90 unmodified linesmax_sequence_length: int = 512,fixed_point_iterations: int = 1,):r"""Function invoked when calling the pipeline for generation.196 unmodified lineslatents_list.append(latents)# 6. Denoising loopwith self.progress_bar(total=num_inference_steps * fixed_point_iterations) as progress_bar:for i, t in enumerate(timesteps):original_latents = latents.clone()for j in range(fixed_point_iterations):if self.interrupt:continueif j == 0:# broadcast to batch dimension in a way that's compatible with ONNX/Core MLtimestep = timesteps[i].expand(latents.shape[0]).to(latents.dtype)else:timestep = timesteps_one_start[i].expand(latents.shape[0]).to(latents.dtype)noise_pred = self.transformer(hidden_states=latents,# YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing)timestep=timestep / 1000,guidance=guidance,pooled_projections=pooled_prompt_embeds,encoder_hidden_states=prompt_embeds,txt_ids=text_ids,img_ids=latent_image_ids,joint_attention_kwargs=self.joint_attention_kwargs,return_dict=False,)[0]# compute the previous noisy sample x_t -> x_t-1latents_dtype = latents.dtype# noise_pred = -noise_predlatents = self.scheduler.step(noise_pred, t, original_latents, return_dict=False, step_index=i)[0]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/99272latents = latents.to(latents_dtype)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 = callback_outputs.pop("latents", latents)prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)# call the callback, if providedif i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):progress_bar.update()# if XLA_AVAILABLE:# xm.mark_step()latents_list.append(latents)# Offload all modelsself.maybe_free_model_hooks()16 unmodified lines17181920212223152 unmodified lines176177178179180181182183184220 unmodified lines4054064074084094104114124134144154164174184194204214224234244254264274284294 unmodified lines434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501290 unmodified lines792793794795796797798799800188 unmodified lines98999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103290 unmodified lines112311241125112611271128112911301131196 unmodified lines132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138216 unmodified lines# This work is licensed under the LICENSE file# located at the root directory.from tqdm import tqdmfrom typing import Any, Callable, Dict, List, Optional, Unionimport torchimport numpy as np152 unmodified linesis_img_src: bool = False,use_offset: bool = False,img_src_latents: Optional[List[torch.FloatTensor]] = None,# TQDMtqdm_desc: str = "Denoising",):r"""Function invoked when calling the pipeline for generation.220 unmodified linesimg_src_latents.append((1.0 - sigma) * source_latents[0] + sigma * rand_noise)# 6. Denoising loopfor i, t in enumerate(tqdm(timesteps, desc=tqdm_desc)):if self.interrupt:continue# broadcast to batch dimension in a way that's compatible with ONNX/Core MLtimestep = t.expand(latents.shape[0]).to(latents.dtype)# For denoising from source imageif is_img_src:latents[0] = img_src_latents[i]# For Structure Transferif (source_latents is not None) and i == structure_transfer_step:sigma = self.scheduler.sigmas[i]latents[1] = (1.0 - sigma) * source_latents[0] + sigma * noise[1]if is_auto_extend_scale and i == auto_extended_step:def f(gamma):self.attention_store.attention_ratios[i] = {}noise_pred = self.transformer(hidden_states=latents,timestep=timestep / 1000,4 unmodified linesimg_ids=latent_image_ids,joint_attention_kwargs=self.joint_attention_kwargs,return_dict=False,proccesor_kwargs={"step_index": i, "extended_scale": gamma},)[0]scores_per_layer = self.attention_store.get_attention_ratios(step_indices=[i], display_imgs=False)source_sum, text_sum, target_sum = scores_per_layer['transformer_blocks']# We want to find the gamma that makes the ratio equal to Kratio = (target_sum / source_sum)return (ratio - target_auto_ratio)gamma_sol = brentq(f, 1.0, 1.2, xtol=0.01)print('Chosen gamma:', gamma_sol)extended_scale = gamma_solelse:noise_pred = self.transformer(hidden_states=latents,timestep=timestep / 1000,guidance=guidance,pooled_projections=pooled_prompt_embeds,encoder_hidden_states=prompt_embeds,txt_ids=text_ids,img_ids=latent_image_ids,joint_attention_kwargs=self.joint_attention_kwargs,return_dict=False,proccesor_kwargs={"step_index": i, "extended_scale": extended_scale},)[0]# compute the previous noisy sample x_t -> x_t-1latents_dtype = latents.dtypelatents, x0 = self.scheduler.step(noise_pred, t, latents, return_dict=False, step_index=i)if use_offset and is_img_src and (i+1 < len(img_src_latents)):next_latent = img_src_latents[i+1]offset = (next_latent - latents[0])latents[1] = latents[1] + offset# blend latentsif i in blend_steps and (subject_token is not None) and (localization_model is not None):x0 = self._unpack_latents(x0, height, width, self.vae_scale_factor)x0 = (x0 / self.vae.config.scaling_factor) + self.vae.config.shift_factorimages = self.vae.decode(x0, return_dict=False)[0]images = self.image_processor.postprocess(images, output_type="pil")self.do_step_blend(images, latents, subject_token, localization_model, show_attention, i, blend_models)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/99272latents = latents.to(latents_dtype)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 = callback_outputs.pop("latents", latents)prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)# if XLA_AVAILABLE:# xm.mark_step()if output_type == "latent":image = latents290 unmodified linescallback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,callback_on_step_end_tensor_inputs: List[str] = ["latents"],max_sequence_length: int = 512,# TQDMtqdm_desc: str = "Denoising",):r"""Function invoked when calling the pipeline for generation.188 unmodified lineslatent_image_ids = latent_image_ids.expand(latents.shape[0], -1, -1)# 6. Denoising loopfor i, t in enumerate(tqdm(timesteps, desc=tqdm_desc)):if self.interrupt:continue# broadcast to batch dimension in a way that's compatible with ONNX/Core MLtimestep = t.expand(latents.shape[0]).to(latents.dtype)noise_pred = self.transformer(hidden_states=latents,timestep=timestep / 1000,guidance=guidance,pooled_projections=pooled_prompt_embeds,encoder_hidden_states=prompt_embeds,txt_ids=text_ids,img_ids=latent_image_ids,joint_attention_kwargs=self.joint_attention_kwargs,return_dict=False,)[0]# compute the previous noisy sample x_t -> x_t-1latents_dtype = latents.dtypelatents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]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/99272latents = latents.to(latents_dtype)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 = callback_outputs.pop("latents", latents)prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)# if XLA_AVAILABLE:# xm.mark_step()if output_type == "latent":image = latents90 unmodified linesmax_sequence_length: int = 512,fixed_point_iterations: int = 1,# TQDMtqdm_desc: str = "Denoising",):r"""Function invoked when calling the pipeline for generation.196 unmodified lineslatents_list.append(latents)# 6. Denoising loopfor i, t in enumerate(tqdm(timesteps, desc=tqdm_desc)):original_latents = latents.clone()for j in range(fixed_point_iterations):if self.interrupt:continueif j == 0:# broadcast to batch dimension in a way that's compatible with ONNX/Core MLtimestep = timesteps[i].expand(latents.shape[0]).to(latents.dtype)else:timestep = timesteps_one_start[i].expand(latents.shape[0]).to(latents.dtype)noise_pred = self.transformer(hidden_states=latents,# YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing)timestep=timestep / 1000,guidance=guidance,pooled_projections=pooled_prompt_embeds,encoder_hidden_states=prompt_embeds,txt_ids=text_ids,img_ids=latent_image_ids,joint_attention_kwargs=self.joint_attention_kwargs,return_dict=False,)[0]# compute the previous noisy sample x_t -> x_t-1latents_dtype = latents.dtype# noise_pred = -noise_predlatents = self.scheduler.step(noise_pred, t, original_latents, return_dict=False, step_index=i)[0]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/99272latents = latents.to(latents_dtype)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 = callback_outputs.pop("latents", latents)prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)# if XLA_AVAILABLE:# xm.mark_step()latents_list.append(latents)# Offload all modelsself.maybe_free_model_hooks()
54 unmodified lines55565758596029 unmodified lines90919293949545 unmodified lines1411421431441451461479 unmodified lines15715815916016116216354 unmodified linesis_img_src=is_img_src,img_src_latents=img_src_latents,use_offset=use_offset,)if display_output:29 unmodified linesnum_inference_steps=30,seed=[seed_src],output_type="both",)source_image = source_image[0]45 unmodified linesstrength=0.1,guidance_scale=3.5,output_type="latent",generator=torch.Generator(device=pipe.device).manual_seed(0)).images# Optional inversion step9 unmodified linesnum_inference_steps=30,guidance_scale=1,fixed_point_iterations=2,generator=torch.Generator(device=pipe.device).manual_seed(0))img_src_latents = [x[0] for x in latents_list][::-1]54 unmodified lines55565758596061626329 unmodified lines9394959697989945 unmodified lines1451461471481491501511529 unmodified lines16216316416516616716816954 unmodified linesis_img_src=is_img_src,img_src_latents=img_src_latents,use_offset=use_offset,# TQDMtqdm_desc="Running Addit: Generating Edited Image",)if display_output:29 unmodified linesnum_inference_steps=30,seed=[seed_src],output_type="both",tqdm_desc="Generating Source Image",)source_image = source_image[0]45 unmodified linesstrength=0.1,guidance_scale=3.5,output_type="latent",generator=torch.Generator(device=pipe.device).manual_seed(0),tqdm_desc="Encoding Source Image",).images# Optional inversion step9 unmodified linesnum_inference_steps=30,guidance_scale=1,fixed_point_iterations=2,generator=torch.Generator(device=pipe.device).manual_seed(0),tqdm_desc="Inverting Source Image",)img_src_latents = [x[0] for x in latents_list][::-1]
215 unmodified lines2162172182192202212222233 unmodified lines22722822923023123223323448 unmodified lines28328428528628728828927 unmodified lines317318319320321322323324215 unmodified lines)gen_prompt_target = gr.Textbox(label="Target Prompt",placeholder="A photo of a cat wearing a red hat sitting on the couch",value="A photo of a cat wearing a red hat sitting on the couch")gen_subject_token = gr.Textbox(label="Subject Token",3 unmodified lines)with gr.Accordion("Advanced Settings", open=False):gen_seed_src = gr.Number(label="Source Seed", value=6311, precision=0)gen_seed_obj = gr.Number(label="Object Seed", value=1, precision=0)gen_extended_scale = gr.Slider(label="Extended Scale",minimum=1.0,48 unmodified linesgr.Examples(examples=[["A photo of a man sitting on a bench", "A photo of a man sitting on a bench with a dog", "dog"],["A photo of a cat sitting on the couch", "A photo of a cat wearing a red hat sitting on the couch", "hat"],["A car driving through an empty street", "A pink car driving through an empty street", "car"]],inputs=[27 unmodified lines)with gr.Accordion("Advanced Settings", open=False):real_seed_src = gr.Number(label="Source Seed", value=6311, precision=0)real_seed_obj = gr.Number(label="Object Seed", value=1, precision=0)real_extended_scale = gr.Slider(label="Extended Scale",minimum=1.0,215 unmodified lines2162172182192202212222233 unmodified lines22722822923023123223323448 unmodified lines28328428528628728828927 unmodified lines317318319320321322323324215 unmodified lines)gen_prompt_target = gr.Textbox(label="Target Prompt",placeholder="A photo of a cat wearing a blue hat sitting on the couch",value="A photo of a cat wearing a blue hat sitting on the couch")gen_subject_token = gr.Textbox(label="Subject Token",3 unmodified lines)with gr.Accordion("Advanced Settings", open=False):gen_seed_src = gr.Number(label="Source Seed", value=1, precision=0)gen_seed_obj = gr.Number(label="Object Seed", value=42, precision=0)gen_extended_scale = gr.Slider(label="Extended Scale",minimum=1.0,48 unmodified linesgr.Examples(examples=[["A photo of a man sitting on a bench", "A photo of a man sitting on a bench with a dog", "dog"],["A photo of a cat sitting on the couch", "A photo of a cat wearing a blue hat sitting on the couch", "hat"],["A car driving through an empty street", "A pink car driving through an empty street", "car"]],inputs=[27 unmodified lines)with gr.Accordion("Advanced Settings", open=False):real_seed_src = gr.Number(label="Source Seed", value=1, precision=0)real_seed_obj = gr.Number(label="Object Seed", value=0, precision=0)real_extended_scale = gr.Slider(label="Extended Scale",minimum=1.0,
addit_flux_pipeline.py+159-164
addit_methods.py+8-2
app.py+7-7