BiliSakura commited on
Commit
2ab3895
·
verified ·
1 Parent(s): e687c2e

Delete PixNerd-XL-16-512/scheduling_pixnerd_flow_match.py

Browse files
PixNerd-XL-16-512/scheduling_pixnerd_flow_match.py DELETED
@@ -1,231 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from dataclasses import dataclass
4
- from typing import Any, Dict, List, Optional, Tuple, Union
5
-
6
- import torch
7
- from diffusers.configuration_utils import ConfigMixin, register_to_config
8
- from diffusers.schedulers.scheduling_utils import SchedulerMixin
9
- from diffusers.utils import BaseOutput
10
-
11
- @dataclass
12
- class PixNerdSchedulerOutput(BaseOutput):
13
- prev_sample: torch.Tensor
14
-
15
-
16
- class PixNerdFlowMatchScheduler(SchedulerMixin, ConfigMixin):
17
- """
18
- Diffusers-compatible scheduler wrapper for PixNerd's AdamLM flow-matching sampler.
19
- """
20
-
21
- config_name = "scheduler_config.json"
22
- order = 1
23
- init_noise_sigma = 1.0
24
-
25
- @staticmethod
26
- def _lagrange_coeffs(order: int, pre_ts: torch.Tensor, t_start: torch.Tensor, t_end: torch.Tensor) -> List[float]:
27
- ts = [float(v) for v in pre_ts[-order:].tolist()]
28
- a = float(t_start)
29
- b = float(t_end)
30
-
31
- if order == 1:
32
- return [1.0]
33
- if order == 2:
34
- t1, t2 = ts
35
- int1 = 0.5 / (t1 - t2) * ((b - t2) ** 2 - (a - t2) ** 2)
36
- int2 = 0.5 / (t2 - t1) * ((b - t1) ** 2 - (a - t1) ** 2)
37
- total = int1 + int2
38
- return [int1 / total, int2 / total]
39
- if order == 3:
40
- t1, t2, t3 = ts
41
- int1_denom = (t1 - t2) * (t1 - t3)
42
- int1 = ((1 / 3) * b**3 - 0.5 * (t2 + t3) * b**2 + (t2 * t3) * b) - (
43
- (1 / 3) * a**3 - 0.5 * (t2 + t3) * a**2 + (t2 * t3) * a
44
- )
45
- int1 = int1 / int1_denom
46
- int2_denom = (t2 - t1) * (t2 - t3)
47
- int2 = ((1 / 3) * b**3 - 0.5 * (t1 + t3) * b**2 + (t1 * t3) * b) - (
48
- (1 / 3) * a**3 - 0.5 * (t1 + t3) * a**2 + (t1 * t3) * a
49
- )
50
- int2 = int2 / int2_denom
51
- int3_denom = (t3 - t1) * (t3 - t2)
52
- int3 = ((1 / 3) * b**3 - 0.5 * (t1 + t2) * b**2 + (t1 * t2) * b) - (
53
- (1 / 3) * a**3 - 0.5 * (t1 + t2) * a**2 + (t1 * t2) * a
54
- )
55
- int3 = int3 / int3_denom
56
- total = int1 + int2 + int3
57
- return [int1 / total, int2 / total, int3 / total]
58
- if order == 4:
59
- t1, t2, t3, t4 = ts
60
- int1_denom = (t1 - t2) * (t1 - t3) * (t1 - t4)
61
- int1 = ((1 / 4) * b**4 - (1 / 3) * (t2 + t3 + t4) * b**3 + 0.5 * (t3 * t4 + t2 * t3 + t2 * t4) * b**2 - (t2 * t3 * t4) * b) - (
62
- (1 / 4) * a**4 - (1 / 3) * (t2 + t3 + t4) * a**3 + 0.5 * (t3 * t4 + t2 * t3 + t2 * t4) * a**2 - (t2 * t3 * t4) * a
63
- )
64
- int1 = int1 / int1_denom
65
- int2_denom = (t2 - t1) * (t2 - t3) * (t2 - t4)
66
- int2 = ((1 / 4) * b**4 - (1 / 3) * (t1 + t3 + t4) * b**3 + 0.5 * (t3 * t4 + t1 * t3 + t1 * t4) * b**2 - (t1 * t3 * t4) * b) - (
67
- (1 / 4) * a**4 - (1 / 3) * (t1 + t3 + t4) * a**3 + 0.5 * (t3 * t4 + t1 * t3 + t1 * t4) * a**2 - (t1 * t3 * t4) * a
68
- )
69
- int2 = int2 / int2_denom
70
- int3_denom = (t3 - t1) * (t3 - t2) * (t3 - t4)
71
- int3 = ((1 / 4) * b**4 - (1 / 3) * (t1 + t2 + t4) * b**3 + 0.5 * (t4 * t2 + t1 * t2 + t1 * t4) * b**2 - (t1 * t2 * t4) * b) - (
72
- (1 / 4) * a**4 - (1 / 3) * (t1 + t2 + t4) * a**3 + 0.5 * (t4 * t2 + t1 * t2 + t1 * t4) * a**2 - (t1 * t2 * t4) * a
73
- )
74
- int3 = int3 / int3_denom
75
- int4_denom = (t4 - t1) * (t4 - t2) * (t4 - t3)
76
- int4 = ((1 / 4) * b**4 - (1 / 3) * (t1 + t2 + t3) * b**3 + 0.5 * (t3 * t2 + t1 * t2 + t1 * t3) * b**2 - (t1 * t2 * t3) * b) - (
77
- (1 / 4) * a**4 - (1 / 3) * (t1 + t2 + t3) * a**3 + 0.5 * (t3 * t2 + t1 * t2 + t1 * t3) * a**2 - (t1 * t2 * t3) * a
78
- )
79
- int4 = int4 / int4_denom
80
- total = int1 + int2 + int3 + int4
81
- return [int1 / total, int2 / total, int3 / total, int4 / total]
82
- raise ValueError(f"Unsupported solver order: {order}.")
83
-
84
- @register_to_config
85
- def __init__(
86
- self,
87
- num_train_timesteps: int = 1000,
88
- num_inference_steps: int = 25,
89
- guidance_scale: float = 4.0,
90
- timeshift: float = 3.0,
91
- order: int = 2,
92
- guidance_interval_min: float = 0.0,
93
- guidance_interval_max: float = 1.0,
94
- last_step: Optional[float] = None,
95
- ) -> None:
96
- self.num_inference_steps = int(num_inference_steps)
97
- self.guidance_scale = float(guidance_scale)
98
- self.timeshift = float(timeshift)
99
- self.order = int(order)
100
- self.guidance_interval_min = float(guidance_interval_min)
101
- self.guidance_interval_max = float(guidance_interval_max)
102
- self.last_step = last_step
103
- self._reset_state()
104
-
105
- @classmethod
106
- def from_sampler_spec(cls, sampler_spec: Dict[str, Any]) -> "PixNerdFlowMatchScheduler":
107
- init_args = dict(sampler_spec.get("init_args", {}))
108
- return cls(
109
- num_inference_steps=int(init_args.get("num_steps", 25)),
110
- guidance_scale=float(init_args.get("guidance", 4.0)),
111
- timeshift=float(init_args.get("timeshift", 3.0)),
112
- order=int(init_args.get("order", 2)),
113
- guidance_interval_min=float(init_args.get("guidance_interval_min", 0.0)),
114
- guidance_interval_max=float(init_args.get("guidance_interval_max", 1.0)),
115
- last_step=init_args.get("last_step"),
116
- )
117
-
118
- def _reset_state(self) -> None:
119
- self.timesteps: Optional[torch.Tensor] = None
120
- self._timedeltas: Optional[torch.Tensor] = None
121
- self._solver_coeffs = None
122
- self._model_outputs = []
123
- self._step_index = 0
124
-
125
- @staticmethod
126
- def _shift_respace_fn(t: torch.Tensor, shift: float = 3.0) -> torch.Tensor:
127
- return t / (t + (1 - t) * shift)
128
-
129
- def _build_solver_state(
130
- self,
131
- num_inference_steps: int,
132
- timeshift: float,
133
- device: Optional[Union[str, torch.device]] = None,
134
- ) -> Tuple[torch.Tensor, torch.Tensor, List[List[float]]]:
135
- last_step = self.last_step
136
- if last_step is None:
137
- last_step = 1.0 / float(num_inference_steps)
138
-
139
- endpoints = torch.linspace(0.0, 1 - float(last_step), int(num_inference_steps), dtype=torch.float32)
140
- endpoints = torch.cat([endpoints, torch.tensor([1.0], dtype=torch.float32)], dim=0)
141
- timesteps = self._shift_respace_fn(endpoints, timeshift).to(device=device)
142
- timedeltas = (timesteps[1:] - timesteps[:-1]).to(device=device)
143
-
144
- solver_coeffs: List[List[float]] = [[] for _ in range(int(num_inference_steps))]
145
- for i in range(int(num_inference_steps)):
146
- order = min(self.order, i + 1)
147
- pre_ts = timesteps[: i + 1]
148
- coeffs = self._lagrange_coeffs(order, pre_ts, pre_ts[i], timesteps[i + 1])
149
- solver_coeffs[i] = coeffs
150
- return timesteps[:-1], timedeltas, solver_coeffs
151
-
152
- def set_timesteps(
153
- self,
154
- num_inference_steps: Optional[int] = None,
155
- device: Optional[Union[str, torch.device]] = None,
156
- timeshift: Optional[float] = None,
157
- guidance_scale: Optional[float] = None,
158
- order: Optional[int] = None,
159
- **kwargs: Any,
160
- ) -> None:
161
- if num_inference_steps is not None:
162
- self.num_inference_steps = int(num_inference_steps)
163
- if timeshift is not None:
164
- self.timeshift = float(timeshift)
165
- if guidance_scale is not None:
166
- self.guidance_scale = float(guidance_scale)
167
- if order is not None:
168
- self.order = int(order)
169
-
170
- timesteps, timedeltas, solver_coeffs = self._build_solver_state(
171
- self.num_inference_steps,
172
- self.timeshift,
173
- device=device,
174
- )
175
- self.timesteps = timesteps
176
- self._timedeltas = timedeltas
177
- self._solver_coeffs = solver_coeffs
178
- self._model_outputs = []
179
- self._step_index = 0
180
-
181
- def scale_model_input(self, sample: torch.Tensor, timestep: Optional[torch.Tensor] = None) -> torch.Tensor:
182
- return sample
183
-
184
- def classifier_free_guidance(self, model_output: torch.Tensor) -> torch.Tensor:
185
- if model_output.shape[0] % 2 != 0:
186
- raise ValueError("Classifier-free guidance expects concatenated unconditional/conditional batches.")
187
- uncond, cond = model_output.chunk(2, dim=0)
188
- return uncond + self.guidance_scale * (cond - uncond)
189
-
190
- def step(
191
- self,
192
- model_output: torch.Tensor,
193
- timestep: Union[torch.Tensor, float, int],
194
- sample: torch.Tensor,
195
- return_dict: bool = True,
196
- **kwargs: Any,
197
- ) -> Union[PixNerdSchedulerOutput, Tuple[torch.Tensor]]:
198
- if self.timesteps is None or self._timedeltas is None or self._solver_coeffs is None:
199
- raise RuntimeError("`set_timesteps` must be called before `step`.")
200
- if self._step_index >= len(self._solver_coeffs):
201
- raise RuntimeError("Scheduler step index exceeded configured timesteps.")
202
-
203
- coeffs = self._solver_coeffs[self._step_index]
204
- self._model_outputs.append(model_output)
205
- order = len(coeffs)
206
- pred = torch.zeros_like(model_output)
207
- recent = self._model_outputs[-order:]
208
- for coeff, output in zip(coeffs, recent):
209
- pred = pred + coeff * output
210
-
211
- prev_sample = sample + pred * self._timedeltas[self._step_index]
212
- self._step_index += 1
213
-
214
- if not return_dict:
215
- return (prev_sample,)
216
- return PixNerdSchedulerOutput(prev_sample=prev_sample)
217
-
218
- def add_noise(
219
- self,
220
- original_samples: torch.Tensor,
221
- noise: torch.Tensor,
222
- timesteps: torch.Tensor,
223
- ) -> torch.Tensor:
224
- alpha = timesteps.view(-1, 1, 1, 1)
225
- sigma = (1.0 - timesteps).view(-1, 1, 1, 1)
226
- return alpha * original_samples + sigma * noise
227
-
228
- __all__ = [
229
- "PixNerdFlowMatchScheduler",
230
- "PixNerdSchedulerOutput",
231
- ]