Spaces:
Sleeping
Sleeping
Update pk_workflow.py
Browse files293 unmodified lines29429529629729829957 unmodified lines357358359360361362293 unmodified linesscheduler._step_index += 1return prev_sampleclass use_schedule:"""Set each scheduler's shift for one request, and — for anything but `native` — force its sigma grid ontoone of `SCHEDULE_SIGMA_FUNCS`'s named schedules.57 unmodified linesdef stepped(model_output, timestep, sample, return_dict=True, _s=scheduler, _g=generator, **_kwargs):return (_er_sde_step(_s, _g, model_output, timestep, sample),)scheduler.step = steppedreturn self293 unmodified lines29429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348457 unmodified lines542543544545546547548549550551552553554555556557558559560561562293 unmodified linesscheduler._step_index += 1return prev_sampleclass _BatchedBrownianTree:"""Minimal port of k-diffusion's `BatchedBrownianTree` (single-seed case only — MiniMax-H3 requests run atbatch size 1). Wraps `torchsde.BrownianTree` so consecutive noise draws at adjacent sigma pairs arecorrelated through a shared stochastic path, as `dpmpp_2m_sde`/`dpmpp_3m_sde` require — independentper-step Gaussian noise (as used for `euler_ancestral`/`er_sde` above) is a materially different sampler."""def __init__(self, x, t0, t1, seed, cpu=False):import torchsdeself.cpu_tree = cpuif t0 > t1:t0, t1, self.sign = t1, t0, -1else:self.sign = 1w0 = torch.zeros_like(x)if self.cpu_tree:t0, w0, t1 = t0.detach().cpu(), w0.detach().cpu(), t1.detach().cpu()self.tree = torchsde.BrownianTree(t0, w0, t1, entropy=seed)def __call__(self, t0, t1):if t0 > t1:t0, t1, sign = t1, t0, -1else:sign = 1device, dtype = t0.device, t0.dtypeif self.cpu_tree:t0, t1 = t0.detach().cpu().float(), t1.detach().cpu().float()return self.tree(t0, t1).to(device=device, dtype=dtype) * (self.sign * sign)class _BrownianTreeNoiseSampler:"""Port of k-diffusion's `BrownianTreeNoiseSampler`. `cpu=False` matches the `*_gpu` sampler names — noiseis generated directly on the accelerator rather than the CPU-tree variant the non-`_gpu` names use."""def __init__(self, x, sigma_min, sigma_max, seed, cpu=False):self.tree = _BatchedBrownianTree(x, torch.as_tensor(sigma_min), torch.as_tensor(sigma_max), seed, cpu=cpu)def __call__(self, sigma, sigma_next):t0, t1 = torch.as_tensor(sigma), torch.as_tensor(sigma_next)return self.tree(t0, t1) / (t1 - t0).abs().sqrt()def _dpmpp_2m_sde_step(scheduler, model_output, timestep, sample, eta: float = 1.0, s_noise: float = 1.0):"""Ports k-diffusion's `sample_dpmpp_2m_sde` (`solver_type='midpoint'`, matching ComfyUI's `dpmpp_2m_sde_gpu`— the `_heun` variant is a different `solver_type` and is not ported here) onto one `MiniMaxH3Scheduler.step()`call. Single model evaluation per step; second-order accuracy comes from the previous step's denoisedestimate. History and the Brownian-tree noise sampler live on the scheduler instance, reset each request."""if scheduler._step_index is None:scheduler._step_index = scheduler.index_for_timestep(timestep) if scheduler._begin_index is None else scheduler._begin_indexi = scheduler._step_indexif not isinstance(timestep, torch.Tensor):timestep = torch.tensor(timestep, dtype=sample.dtype)sigma_from_timestep = 1 - timestep.to(device=sample.device, dtype=sample.dtype)while sigma_from_timestep.ndim < sample.ndim:sigma_from_timestep = sigma_from_timestep.unsqueeze(-1)denoised = sample + sigma_from_timestep * model_outputcompute_dtype = torch.float32 if sample.dtype in (torch.float16, torch.bfloat16) else sample.dtypesigmas = scheduler.sigmas.to(device=sample.device, dtype=compute_dtype)sigma, sigma_next = sigmas[i], sigmas[i + 1]x = sample.to(dtype=compute_dtype)denoised = denoised.to(dtype=compute_dtype)if i == 0 and float(sigma) >= 1.0:base = torch.tensor(1.0 - 1e-4, dtype=compute_dtype, device=sample.device)shift = float(scheduler.shift)sigma = shift * base / (1 + (shift - 1) * base)if scheduler._dpmpp_sde_noise_sampler is None:scheduler._dpmpp_sde_noise_sampler = _BrownianTreeNoiseSampler(x, sigmas[sigmas > 0].min(), sigmas.max(), seed=scheduler._dpmpp_sde_seed, cpu=False)def half_log_snr(s):return torch.log((1 - s) / s)if sigma_next == 0:prev_sample = denoisedelse:lambda_s, lambda_t = half_log_snr(sigma), half_log_snr(sigma_next)h = lambda_t - lambda_sh_eta = h * (eta + 1)alpha_next = 1 - sigma_nextprev_sample = (sigma_next / sigma) * (-h * eta).exp() * x + alpha_next * (-h_eta).expm1().neg() * denoisedold_denoised = scheduler._dpmpp_sde_old_denoisedh_last = scheduler._dpmpp_sde_h_lastif old_denoised is not None:r = h_last / hprev_sample = prev_sample + 0.5 * alpha_next * (-h_eta).expm1().neg() * (1 / r) * (denoised - old_denoised)if eta > 0 and s_noise > 0:noise = scheduler._dpmpp_sde_noise_sampler(sigma, sigma_next).to(device=x.device, dtype=compute_dtype)prev_sample = prev_sample + noise * sigma_next * (-2 * h * eta).expm1().neg().sqrt() * s_noisescheduler._dpmpp_sde_h_last = hscheduler._dpmpp_sde_old_denoised = denoisedprev_sample = prev_sample.to(dtype=sample.dtype)scheduler._step_index += 1return prev_sampledef _dpmpp_3m_sde_step(scheduler, model_output, timestep, sample, eta: float = 1.0, s_noise: float = 1.0):"""Ports k-diffusion's `sample_dpmpp_3m_sde` (matching ComfyUI's `dpmpp_3m_sde_gpu`) onto one`MiniMaxH3Scheduler.step()` call. Single model evaluation per step; third-order accuracy (once two priorsteps exist) comes from history carried on the scheduler instance, plus the same Brownian-tree noise as`_dpmpp_2m_sde_step`."""if scheduler._step_index is None:scheduler._step_index = scheduler.index_for_timestep(timestep) if scheduler._begin_index is None else scheduler._begin_indexi = scheduler._step_indexif not isinstance(timestep, torch.Tensor):timestep = torch.tensor(timestep, dtype=sample.dtype)sigma_from_timestep = 1 - timestep.to(device=sample.device, dtype=sample.dtype)while sigma_from_timestep.ndim < sample.ndim:sigma_from_timestep = sigma_from_timestep.unsqueeze(-1)denoised = sample + sigma_from_timestep * model_outputcompute_dtype = torch.float32 if sample.dtype in (torch.float16, torch.bfloat16) else sample.dtypesigmas = scheduler.sigmas.to(device=sample.device, dtype=compute_dtype)sigma, sigma_next = sigmas[i], sigmas[i + 1]x = sample.to(dtype=compute_dtype)denoised = denoised.to(dtype=compute_dtype)if i == 0 and float(sigma) >= 1.0:base = torch.tensor(1.0 - 1e-4, dtype=compute_dtype, device=sample.device)shift = float(scheduler.shift)sigma = shift * base / (1 + (shift - 1) * base)if scheduler._dpmpp_sde_noise_sampler is None:scheduler._dpmpp_sde_noise_sampler = _BrownianTreeNoiseSampler(x, sigmas[sigmas > 0].min(), sigmas.max(), seed=scheduler._dpmpp_sde_seed, cpu=False)def half_log_snr(s):return torch.log((1 - s) / s)if sigma_next == 0:prev_sample = denoisedelse:lambda_s, lambda_t = half_log_snr(sigma), half_log_snr(sigma_next)h = lambda_t - lambda_sh_eta = h * (eta + 1)alpha_next = 1 - sigma_nextprev_sample = (sigma_next / sigma) * (-h * eta).exp() * x + alpha_next * (-h_eta).expm1().neg() * denoiseddenoised_1 = scheduler._dpmpp_sde_old_denoiseddenoised_2 = scheduler._dpmpp_sde_old_denoised_2h_1 = scheduler._dpmpp_sde_h_lasth_2 = scheduler._dpmpp_sde_h_last_2if h_2 is not None:r0, r1 = h_1 / h, h_2 / hd1_0 = (denoised - denoised_1) / r0d1_1 = (denoised_1 - denoised_2) / r1d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)d2 = (d1_0 - d1_1) / (r0 + r1)phi_2 = h_eta.neg().expm1() / h_eta + 1phi_3 = phi_2 / h_eta - 0.5prev_sample = prev_sample + (alpha_next * phi_2) * d1 - (alpha_next * phi_3) * d2elif h_1 is not None:r = h_1 / hd = (denoised - denoised_1) / rphi_2 = h_eta.neg().expm1() / h_eta + 1prev_sample = prev_sample + (alpha_next * phi_2) * dif eta > 0 and s_noise > 0:noise = scheduler._dpmpp_sde_noise_sampler(sigma, sigma_next).to(device=x.device, dtype=compute_dtype)prev_sample = prev_sample + noise * sigma_next * (-2 * h * eta).expm1().neg().sqrt() * s_noisescheduler._dpmpp_sde_h_last_2 = h_1scheduler._dpmpp_sde_h_last = hscheduler._dpmpp_sde_old_denoised_2 = scheduler._dpmpp_sde_old_denoisedscheduler._dpmpp_sde_old_denoised = denoisedprev_sample = prev_sample.to(dtype=sample.dtype)scheduler._step_index += 1return prev_sampleclass use_schedule:"""Set each scheduler's shift for one request, and — for anything but `native` — force its sigma grid ontoone of `SCHEDULE_SIGMA_FUNCS`'s named schedules.57 unmodified linesdef stepped(model_output, timestep, sample, return_dict=True, _s=scheduler, _g=generator, **_kwargs):return (_er_sde_step(_s, _g, model_output, timestep, sample),)scheduler.step = steppedelif self.sampler_name in ("dpmpp_2m_sde_gpu", "dpmpp_3m_sde_gpu"):step_fn = _dpmpp_2m_sde_step if self.sampler_name == "dpmpp_2m_sde_gpu" else _dpmpp_3m_sde_stepfor offset, attr_name in enumerate(self.attr_names):scheduler = getattr(self.pipe, attr_name)scheduler._dpmpp_sde_old_denoised = Nonescheduler._dpmpp_sde_old_denoised_2 = Nonescheduler._dpmpp_sde_h_last = Nonescheduler._dpmpp_sde_h_last_2 = Nonescheduler._dpmpp_sde_noise_sampler = Nonescheduler._dpmpp_sde_seed = self.seed + offsetdef stepped(model_output, timestep, sample, return_dict=True, _s=scheduler, _f=step_fn, **_kwargs):return (_f(_s, model_output, timestep, sample),)scheduler.step = steppedreturn self
pk_workflow.py+200