Spaces:
Configuration error
Configuration error
Stable-X commited on
Commit ·
9a4072e
1
Parent(s): 19b2060
Fix scheduler and preprocessor bug
Browse filesFiles changed (4)
27 unmodified lines28293031323321 unmodified lines5556575859606137 unmodified lines9910010110210310410526 unmodified lines1321331341351361371387 unmodified lines14614714814915015122 unmodified lines174175176177178179180181151 unmodified lines33333433533633733833967 unmodified lines40740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351427 unmodified linesimport numpy as npimport spacesimport torch as torchfrom PIL import Imagefrom gradio_imageslider import ImageSliderfrom tqdm import tqdm21 unmodified linesdefault_video_num_inference_steps = 10default_video_processing_resolution = 768default_video_out_max_frames = 450def process_image_check(path_input):if path_input is None:37 unmodified linespath_output_dir = tempfile.mkdtemp()path_out_png = os.path.join(path_output_dir, f"{name_base}_normal_colored.png")yield Noneinput_image = Image.open(path_input)input_image = resize_image(input_image, default_image_processing_resolution)26 unmodified linespipe,path_input,out_max_frames=default_video_out_max_frames,target_fps=3,progress=gr.Progress(),):if path_input is None:7 unmodified linespath_output_dir = tempfile.mkdtemp()path_out_vis = os.path.join(path_output_dir, f"{name_base}_normal_colored.mp4")reader, writer = None, Nonetry:reader = imageio.get_reader(path_input)22 unmodified linespipe_out = pipe(frame_pil,match_input_resolution=False,)processed_frame = pipe.image_processor.visualize_normals( # noqapipe_out.prediction)[0]151 unmodified linesinputs=[video_input],outputs=[processed_frames, video_output_files],directory_name="examples_video",cache_examples=True,)with gr.Tab("Panorama"):67 unmodified linesserver_port=7860,)from einops import rearrangeclass DINOv2_Encoder:IMAGENET_DEFAULT_MEAN = [0.485, 0.456, 0.406]IMAGENET_DEFAULT_STD = [0.229, 0.224, 0.225]def __init__(self,model_name = 'dinov2_vitl14',freeze = True,antialias=True,device="cuda",size = 448,):super(DINOv2_Encoder).__init__()self.model = torch.hub.load('facebookresearch/dinov2', model_name)self.model.eval()self.device = deviceself.antialias = antialiasself.dtype = torch.float32self.mean = torch.Tensor(self.IMAGENET_DEFAULT_MEAN)self.std = torch.Tensor(self.IMAGENET_DEFAULT_STD)self.size = sizeif freeze:self.freeze()def freeze(self):for param in self.model.parameters():param.requires_grad = False@torch.no_grad()def encoder(self, x):'''x: [b h w c], range from (-1, 1), rbg'''x = self.preprocess(x).to(self.device, self.dtype)b, c, h, w = x.shapepatch_h, patch_w = h // 14, w // 14embeddings = self.model.forward_features(x)['x_norm_patchtokens']embeddings = rearrange(embeddings, 'b (h w) c -> b h w c', h = patch_h, w = patch_w)return rearrange(embeddings, 'b h w c -> b c h w')def preprocess(self, x):''' x'''# normalize to [0,1],x = torch.nn.functional.interpolate(x,size=(self.size, self.size),mode='bicubic',align_corners=True,antialias=self.antialias,)x = (x + 1.0) / 2.0# renormalize according to dinomean = self.mean.view(1, 3, 1, 1).to(x.device)std = self.std.view(1, 3, 1, 1).to(x.device)x = (x - mean) / stdreturn xdef to(self, device, dtype=None):if dtype is not None:self.dtype = dtypeself.model.to(device, dtype)self.mean.to(device, dtype)self.std.to(device, dtype)else:self.model.to(device)self.mean.to(device)self.std.to(device)return selfdef __call__(self, x, **kwargs):return self.encoder(x, **kwargs)def main():os.system("pip freeze")device = torch.device("cuda" if torch.cuda.is_available() else "cpu")x_start_pipeline = YOSONormalsPipeline.from_pretrained('Stable-X/yoso-normal-v0-1', trust_remote_code=True,t_start=300).to(device)dinov2_prior = DINOv2_Encoder(size=672)dinov2_prior.to(device)pipe = StableNormalPipeline.from_pretrained('Stable-X/stable-normal-v0-1', t_start=300, trust_remote_code=True,scheduler=HEURI_DDIMScheduler(prediction_type='sample',beta_start=0.00085, beta_end=0.0120,beta_schedule = "scaled_linear"))pipe.x_start_pipeline = x_start_pipelinepipe.prior = dinov2_priorpipe.to(device)try:import xformers27 unmodified lines2829303132333421 unmodified lines5657585960616237 unmodified lines10010110210310410526 unmodified lines1321331341351361371387 unmodified lines14614714814915015115222 unmodified lines175176177178179180181182183184185151 unmodified lines33733833934034134234367 unmodified lines41141241341441541641741841942042142242342442542642742842943043143227 unmodified linesimport numpy as npimport spacesimport torch as torchtorch.backends.cuda.matmul.allow_tf32 = Truefrom PIL import Imagefrom gradio_imageslider import ImageSliderfrom tqdm import tqdm21 unmodified linesdefault_video_num_inference_steps = 10default_video_processing_resolution = 768default_video_out_max_frames = 60def process_image_check(path_input):if path_input is None:37 unmodified linespath_output_dir = tempfile.mkdtemp()path_out_png = os.path.join(path_output_dir, f"{name_base}_normal_colored.png")input_image = Image.open(path_input)input_image = resize_image(input_image, default_image_processing_resolution)26 unmodified linespipe,path_input,out_max_frames=default_video_out_max_frames,target_fps=10,progress=gr.Progress(),):if path_input is None:7 unmodified linespath_output_dir = tempfile.mkdtemp()path_out_vis = os.path.join(path_output_dir, f"{name_base}_normal_colored.mp4")init_latents = Nonereader, writer = None, Nonetry:reader = imageio.get_reader(path_input)22 unmodified linespipe_out = pipe(frame_pil,match_input_resolution=False,latents=init_latents)if init_latents is None:init_latents = pipe_out.gaus_noiseprocessed_frame = pipe.image_processor.visualize_normals( # noqapipe_out.prediction)[0]151 unmodified linesinputs=[video_input],outputs=[processed_frames, video_output_files],directory_name="examples_video",cache_examples=False,)with gr.Tab("Panorama"):67 unmodified linesserver_port=7860,)def main():os.system("pip freeze")device = torch.device("cuda" if torch.cuda.is_available() else "cpu")x_start_pipeline = YOSONormalsPipeline.from_pretrained('weights/yoso-normal-v0-2', trust_remote_code=True, variant="fp16", torch_dtype=torch.float16).to(device)pipe = StableNormalPipeline.from_pretrained('weights/stable-normal-v0-1', trust_remote_code=True,variant="fp16", torch_dtype=torch.float16,scheduler=HEURI_DDIMScheduler(prediction_type='sample',beta_start=0.00085, beta_end=0.0120,beta_schedule = "scaled_linear"))pipe.x_start_pipeline = x_start_pipelinepipe.to(device)pipe.prior.to(device, torch.float16)try:import xformers
98 unmodified lines9910010110210310410557 unmodified lines16316416516616716816920 unmodified lines190191192193194195196197148 unmodified lines34634734834935035135288 unmodified lines44144244344444544644744844945052 unmodified lines50350450550650750850951051151251351451551651751851952052152252352452552652752852953013 unmodified lines54454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259310 unmodified lines60460560660760860998 unmodified linesprediction: Union[np.ndarray, torch.Tensor]latent: Union[None, torch.Tensor]class StableNormalPipeline(StableDiffusionControlNetPipeline):""" Pipeline for monocular normals estimation using the Marigold method: https://marigoldmonodepth.github.io.57 unmodified linesdefault_processing_resolution: Optional[int] = 768,prompt="The normal map",empty_text_embedding=None,t_start: Optional[int] = 401,):super().__init__(vae,20 unmodified linesself.prompt = promptself.prompt_embeds = Noneself.empty_text_embedding = empty_text_embeddingself.t_start= torch.tensor(t_start) # target_out latentsdef check_inputs(self,148 unmodified linesnum_inference_steps: Optional[int] = None,ensemble_size: int = 1,processing_resolution: Optional[int] = None,return_intermediate_result: bool = False,match_input_resolution: bool = True,resample_method_input: str = "bilinear",resample_method_output: str = "bilinear",88 unmodified linesimage, processing_resolution, resample_method_input, device, dtype) # [N,3,PPH,PPW]# 0. X_start latent obtainpredictor = self.x_start_pipeline(image, skip_preprocess=True)x_start_latent = predictor.latentgauss_latent = predictor.gauss_latent# 1. Check inputs.num_images = self.check_inputs(52 unmodified linesdino_features = self.dino_controlnet.dino_controlnet_cond_embedding(dino_features)dino_features = self.match_noisy(dino_features, x_start_latent)# 6. Encode input image into latent space. At this step, each of the `N` input images is represented with `E`# ensemble members. Each ensemble member is an independent diffused prediction, just initialized independently.# Latents of each such predictions across all input images and all ensemble members are represented in the# `pred_latent` variable. The variable `image_latent` is of the same shape: it contains each input image encoded# into latent space and replicated `E` times. The latents can be either generated (see `generator` to ensure# reproducibility), or passed explicitly via the `latents` argument. The latter can be set outside the pipeline# code. For example, in the Marigold-LCM video processing demo, the latents initialization of a frame is taken# as a convex combination of the latents output of the pipeline for the previous frame and a newly-sampled# noise. This behavior can be achieved by setting the `output_latent` argument to `True`. The latent space# dimensions are `(h, w)`. Encoding into latent space happens in batches of size `batch_size`.# Model invocation: self.vae.encoder.image_latent, pred_latent = self.prepare_latents(image, latents, generator, ensemble_size, batch_size) # [N*E,4,h,w], [N*E,4,h,w]del (image,)# 7. denoise sampling, using heuritic sampling proposed by Ye.self.scheduler.set_timesteps(num_inference_steps, device=device)cond_scale =controlnet_conditioning_scalepred_latent = x_start_latent13 unmodified linespred_latents = []down_block_res_samples, mid_block_res_sample = self.controlnet(image_latent.detach(),self.t_start,encoder_hidden_states=self.prompt_embeds,conditioning_scale=cond_scale,guess_mode=False,return_dict=False,)last_pred_latent = pred_latentfor i in range(4):_dino_down_block_res_samples = [dino_down_block_res_sample for dino_down_block_res_sample in dino_down_block_res_samples] # copy, avoid repeat quierymodel_output = self.dino_unet_forward(self.unet,pred_latent,self.t_start,encoder_hidden_states=self.prompt_embeds,down_block_additional_residuals=down_block_res_samples,mid_block_additional_residual=mid_block_res_sample,dino_down_block_additional_residuals= _dino_down_block_res_samples,return_dict=False,)[0] # [B,4,h,w]pred_latents.append(model_output)pred_latent = self.scheduler.add_noise(model_output, gauss_latent, self.t_start)pred_latent = 0.4 * pred_latent + 0.6 * last_pred_latentlast_pred_latent = pred_latentpred_latents = torch.cat(pred_latents, dim=0)del (image_latent,dino_features,)# decoderif return_intermediate_result:prediction = []for _pred_latent in pred_latents:_prediction = self.decode_prediction(_pred_latent.unsqueeze(dim=0))prediction.append(_prediction)prediction = torch.cat(prediction, dim=0)else:prediction = self.decode_prediction(pred_latents[-1].unsqueeze(dim=0))prediction = self.image_processor.unpad_image(prediction, padding) # [N*E,3,PH,PW]if match_input_resolution:prediction = self.image_processor.resize_antialias(prediction, original_resolution, resample_method_output, is_aa=False10 unmodified linesreturn StableNormalOutput(prediction=prediction,latent=pred_latent,)# Copied from diffusers.pipelines.marigold.pipeline_marigold_depth.MarigoldDepthPipeline.prepare_latents98 unmodified lines9910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718857 unmodified lines24624724824925025120 unmodified lines272273274275276277278148 unmodified lines42742842943043143288 unmodified lines52152252352452552652752852953053153253353452 unmodified lines58758858959059159259359459559659759859960013 unmodified lines61461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067110 unmodified lines68268368468568668768898 unmodified linesprediction: Union[np.ndarray, torch.Tensor]latent: Union[None, torch.Tensor]gaus_noise: Union[None, torch.Tensor]from einops import rearrangeclass DINOv2_Encoder(torch.nn.Module):IMAGENET_DEFAULT_MEAN = [0.485, 0.456, 0.406]IMAGENET_DEFAULT_STD = [0.229, 0.224, 0.225]def __init__(self,model_name = 'dinov2_vitl14',freeze = True,antialias=True,device="cuda",size = 448,):super(DINOv2_Encoder, self).__init__()self.model = torch.hub.load('facebookresearch/dinov2', model_name)self.model.eval().to(device)self.device = deviceself.antialias = antialiasself.dtype = torch.float32self.mean = torch.Tensor(self.IMAGENET_DEFAULT_MEAN)self.std = torch.Tensor(self.IMAGENET_DEFAULT_STD)self.size = sizeif freeze:self.freeze()def freeze(self):for param in self.model.parameters():param.requires_grad = False@torch.no_grad()def encoder(self, x):'''x: [b h w c], range from (-1, 1), rbg'''x = self.preprocess(x).to(self.device, self.dtype)b, c, h, w = x.shapepatch_h, patch_w = h // 14, w // 14embeddings = self.model.forward_features(x)['x_norm_patchtokens']embeddings = rearrange(embeddings, 'b (h w) c -> b h w c', h = patch_h, w = patch_w)return rearrange(embeddings, 'b h w c -> b c h w')def preprocess(self, x):''' x'''# normalize to [0,1],x = torch.nn.functional.interpolate(x,size=(self.size, self.size),mode='bicubic',align_corners=True,antialias=self.antialias,)x = (x + 1.0) / 2.0# renormalize according to dinomean = self.mean.view(1, 3, 1, 1).to(x.device)std = self.std.view(1, 3, 1, 1).to(x.device)x = (x - mean) / stdreturn xdef to(self, device, dtype=None):if dtype is not None:self.dtype = dtypeself.model.to(device, dtype)self.mean.to(device, dtype)self.std.to(device, dtype)else:self.model.to(device)self.mean.to(device)self.std.to(device)return selfdef __call__(self, x, **kwargs):return self.encoder(x, **kwargs)class StableNormalPipeline(StableDiffusionControlNetPipeline):""" Pipeline for monocular normals estimation using the Marigold method: https://marigoldmonodepth.github.io.57 unmodified linesdefault_processing_resolution: Optional[int] = 768,prompt="The normal map",empty_text_embedding=None,):super().__init__(vae,20 unmodified linesself.prompt = promptself.prompt_embeds = Noneself.empty_text_embedding = empty_text_embeddingself.prior = DINOv2_Encoder(size=672)def check_inputs(self,148 unmodified linesnum_inference_steps: Optional[int] = None,ensemble_size: int = 1,processing_resolution: Optional[int] = None,match_input_resolution: bool = True,resample_method_input: str = "bilinear",resample_method_output: str = "bilinear",88 unmodified linesimage, processing_resolution, resample_method_input, device, dtype) # [N,3,PPH,PPW]image_latent, gaus_noise = self.prepare_latents(image, latents, generator, ensemble_size, batch_size) # [N,4,h,w], [N,4,h,w]# 0. X_start latent obtainpredictor = self.x_start_pipeline(image, latents=gaus_noise,processing_resolution=processing_resolution, skip_preprocess=True)x_start_latent = predictor.latent# 1. Check inputs.num_images = self.check_inputs(52 unmodified linesdino_features = self.dino_controlnet.dino_controlnet_cond_embedding(dino_features)dino_features = self.match_noisy(dino_features, x_start_latent)del (image,)# 7. denoise sampling, using heuritic sampling proposed by Ye.t_start = self.x_start_pipeline.t_startself.scheduler.set_timesteps(num_inference_steps, t_start=t_start,device=device)cond_scale =controlnet_conditioning_scalepred_latent = x_start_latent13 unmodified linespred_latents = []last_pred_latent = pred_latentfor (t, prev_t) in self.progress_bar(zip(self.scheduler.timesteps,self.scheduler.prev_timesteps), leave=False, desc="Diffusion steps..."):_dino_down_block_res_samples = [dino_down_block_res_sample for dino_down_block_res_sample in dino_down_block_res_samples] # copy, avoid repeat quiery# controlnetdown_block_res_samples, mid_block_res_sample = self.controlnet(image_latent.detach(),t,encoder_hidden_states=self.prompt_embeds,conditioning_scale=cond_scale,guess_mode=False,return_dict=False,)# SG-DRNnoise = self.dino_unet_forward(self.unet,pred_latent,t,encoder_hidden_states=self.prompt_embeds,down_block_additional_residuals=down_block_res_samples,mid_block_additional_residual=mid_block_res_sample,dino_down_block_additional_residuals= _dino_down_block_res_samples,return_dict=False,)[0] # [B,4,h,w]pred_latents.append(noise)# ddim stepsout = self.scheduler.step(noise, t, prev_t, pred_latent, gaus_noise = gaus_noise, generator=generator, cur_step=cur_step+1 # NOTE that cur_step dirs to next_step)# [B,4,h,w]pred_latent = out.prev_samplecur_step += 1del (image_latent,dino_features,)pred_latent = pred_latents[-1] # using x0# decoderprediction = self.decode_prediction(pred_latent)prediction = self.image_processor.unpad_image(prediction, padding) # [N*E,3,PH,PW]prediction = self.image_processor.resize_antialias(prediction, original_resolution, resample_method_output, is_aa=False) # [N,3,H,W]if match_input_resolution:prediction = self.image_processor.resize_antialias(prediction, original_resolution, resample_method_output, is_aa=False) # [N,3,H,W]if match_input_resolution:prediction = self.image_processor.resize_antialias(prediction, original_resolution, resample_method_output, is_aa=False10 unmodified linesreturn StableNormalOutput(prediction=prediction,latent=pred_latent,gaus_noise=gaus_noise)# Copied from diffusers.pipelines.marigold.pipeline_marigold_depth.MarigoldDepthPipeline.prepare_latents
92 unmodified lines93949596979899402 unmodified lines50250350450550650750850951051111 unmodified lines5235245255265275285293 unmodified lines53353453553653753815 unmodified lines55455555655755855956024 unmodified lines585586587588589590591122 unmodified lines71471571671792 unmodified linesprediction: Union[np.ndarray, torch.Tensor]latent: Union[None, torch.Tensor]gauss_latent: Union[None, torch.Tensor]class YOSONormalsPipeline(StableDiffusionControlNetPipeline):402 unmodified lines# noise. This behavior can be achieved by setting the `output_latent` argument to `True`. The latent space# dimensions are `(h, w)`. Encoding into latent space happens in batches of size `batch_size`.# Model invocation: self.vae.encoder.image_latent, gauss_latent = self.prepare_latents(image, latents, generator, ensemble_size, batch_size) # [N*E,4,h,w], [N*E,4,h,w]del image11 unmodified lines# 7. YOSO samplinglatent_x_t = self.unet(gauss_latent,self.t_start,encoder_hidden_states=self.prompt_embeds,down_block_additional_residuals=down_block_res_samples,3 unmodified linesdel (image_latent,)15 unmodified linesreturn YosoNormalsOutput(prediction=prediction,latent=latent_x_t,gauss_latent=gauss_latent,)# Copied from diffusers.pipelines.marigold.pipeline_marigold_depth.MarigoldDepthPipeline.prepare_latents24 unmodified lines) # [N,4,h,w]image_latent = image_latent * self.vae.config.scaling_factorimage_latent = image_latent.repeat_interleave(ensemble_size, dim=0) # [N*E,4,h,w]pred_latent = torch.randn_like(image_latent)return image_latent, pred_latent122 unmodified lineselse:scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)timesteps = scheduler.timestepsreturn timesteps, num_inference_steps92 unmodified lines93949596979899402 unmodified lines50250350450550650750850951051151211 unmodified lines5245255265275285295303 unmodified lines53453553653753853954015 unmodified lines55655755855956056156224 unmodified lines587588589590591592593594595596597598599600601122 unmodified lines72472572672792 unmodified linesprediction: Union[np.ndarray, torch.Tensor]latent: Union[None, torch.Tensor]gaus_noise: Union[None, torch.Tensor]class YOSONormalsPipeline(StableDiffusionControlNetPipeline):402 unmodified lines# noise. This behavior can be achieved by setting the `output_latent` argument to `True`. The latent space# dimensions are `(h, w)`. Encoding into latent space happens in batches of size `batch_size`.# Model invocation: self.vae.encoder.image_latent, pred_latent = self.prepare_latents(image, latents, generator, ensemble_size, batch_size) # [N*E,4,h,w], [N*E,4,h,w]gaus_noise = pred_latent.detach().clone()del image11 unmodified lines# 7. YOSO samplinglatent_x_t = self.unet(pred_latent,self.t_start,encoder_hidden_states=self.prompt_embeds,down_block_additional_residuals=down_block_res_samples,3 unmodified linesdel (pred_latent,image_latent,)15 unmodified linesreturn YosoNormalsOutput(prediction=prediction,latent=latent_x_t,gaus_noise=gaus_noise,)# Copied from diffusers.pipelines.marigold.pipeline_marigold_depth.MarigoldDepthPipeline.prepare_latents24 unmodified lines) # [N,4,h,w]image_latent = image_latent * self.vae.config.scaling_factorimage_latent = image_latent.repeat_interleave(ensemble_size, dim=0) # [N*E,4,h,w]pred_latent = latentsif pred_latent is None:pred_latent = randn_tensor(image_latent.shape,generator=generator,device=image_latent.device,dtype=image_latent.dtype,) # [N*E,4,h,w]return image_latent, pred_latent122 unmodified lineselse:scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)timesteps = scheduler.timestepsreturn timesteps, num_inference_steps
11 unmodified lines1213141516171837 unmodified lines565758596061626315 unmodified lines798081828384858647 unmodified lines13413513613713813914014114214328 unmodified lines1721731741751761772 unmodified lines18018118218318418518618712 unmodified lines20020120220320420520620720820921011 unmodified linesclass HEURI_DDIMScheduler(DDIMScheduler, SchedulerMixin, ConfigMixin):def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):"""Sets the discrete timesteps used for the diffusion chain (to be run before inference).37 unmodified lines)timesteps = torch.from_numpy(timesteps).to(device)naive_sampling_step = num_inference_steps //2self.naive_sampling_step = naive_sampling_steptimesteps[:naive_sampling_step] = timesteps[naive_sampling_step] # refine on step 5 for 5 steps, then backward from step 615 unmodified linesuse_clipped_model_output: bool = False,generator=None,cur_step=None,gauss_latent=None,variance_noise: Optional[torch.Tensor] = None,return_dict: bool = True,) -> Union[DDIMSchedulerOutput, Tuple]:"""47 unmodified lines# - pred_prev_sample -> "x_t-1"# 1. get previous step value (=t-1)# trick from heuri_samplingif cur_step == self.naive_sampling_step and timestep == prev_timestep:timestep += self.gapprev_timestep = prev_timestep # NOTE naive sampling# 2. compute alphas, betas28 unmodified linesvariance = self._get_variance(timestep, prev_timestep)std_dev_t = eta * variance ** (0.5)if use_clipped_model_output:# the pred_epsilon is always re-derived from the clipped x_0 in Glidepred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)2 unmodified linespred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * pred_epsilon# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdfif gauss_latent == None:gauss_latent = torch.randn_like(pred_original_sample)prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_directionif eta > 0:12 unmodified linesprev_sample = prev_sample + varianceif cur_step < self.naive_sampling_step:prev_sample = self.add_noise(pred_original_sample, gauss_latent, timestep)if not return_dict:return (prev_sample,)return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)11 unmodified lines1213141516171837 unmodified lines5657585960616263646566676815 unmodified lines848586878889909147 unmodified lines13914014114214314414514614714814915028 unmodified lines1791801811821831841852 unmodified lines18818919019119219312 unmodified lines20620720820921021121221321421521621711 unmodified linesclass HEURI_DDIMScheduler(DDIMScheduler, SchedulerMixin, ConfigMixin):def set_timesteps(self, num_inference_steps: int, t_start: int, device: Union[str, torch.device] = None):"""Sets the discrete timesteps used for the diffusion chain (to be run before inference).37 unmodified lines)timesteps = torch.from_numpy(timesteps).to(device)naive_sampling_step = num_inference_steps //2# TODO for debug# naive_sampling_step = 0self.naive_sampling_step = naive_sampling_steptimesteps[:naive_sampling_step] = timesteps[naive_sampling_step] # refine on step 5 for 5 steps, then backward from step 615 unmodified linesuse_clipped_model_output: bool = False,generator=None,cur_step=None,variance_noise: Optional[torch.Tensor] = None,gaus_noise: Optional[torch.Tensor] = None,return_dict: bool = True,) -> Union[DDIMSchedulerOutput, Tuple]:"""47 unmodified lines# - pred_prev_sample -> "x_t-1"# 1. get previous step value (=t-1)# trick from heuri_samplingif cur_step == self.naive_sampling_step and timestep == prev_timestep:timestep += self.gapprev_timestep = prev_timestep # NOTE naive sampling# 2. compute alphas, betas28 unmodified linesvariance = self._get_variance(timestep, prev_timestep)std_dev_t = eta * variance ** (0.5)if use_clipped_model_output:# the pred_epsilon is always re-derived from the clipped x_0 in Glidepred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)2 unmodified linespred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * pred_epsilon# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdfprev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_directionif eta > 0:12 unmodified linesprev_sample = prev_sample + varianceif cur_step < self.naive_sampling_step:prev_sample = self.add_noise(pred_original_sample, torch.randn_like(pred_original_sample), timestep)if not return_dict:return (prev_sample,)return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
app.py+12-94
stablenormal/pipeline_stablenormal.py+129-50
stablenormal/pipeline_yoso_normal.py+16-6
stablenormal/scheduler/heuristics_ddimsampler.py+12-5