File size: 46,384 Bytes
6daffc2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 | """CFG and path-drop guidance (PDG): which forwards each step runs and how
their velocities combine.
Every denoiser forward is a ``BranchCall``: a text branch (the prompt, or the
negative prompt / learned null text), a routing path (``DFlowPath``) and the
image self-attention logit gain of that forward. ``GuidanceSettings`` is
validated once; ``build_guidance_plan`` resolves it against the run's schedule
into one ``GuidanceStep`` per schedule point (``0 .. steps``), so the per-step
code is a table lookup plus tensor arithmetic. ``GuidancePlan.guided_velocity``
takes a callable ``evaluate(call) -> velocity`` and returns the guided velocity.
The main forward always uses the prompt; its gain is
``GuidanceSettings.self_attention_gain`` (0 on the CFG steps of the alternating
modes). Guidance forwards use ``guidance_self_attention_gain``. PDG reference
forwards also carry ``PdgGuidance.suffix_caption_bias``: an additive
attention-logit bias on the prompt's keys in the suffix layers (0: none).
Single-reference steps return ``v_ref + s (v_main - v_ref)`` (or its APG
projection); the combined modes return
``v_main + 0.5 (s_cfg (v_main - v_cfg) + s_pdg (v_main - v_pdg))``, where the
scales are extra strengths (a quantile-ramp PDG scale has 1 subtracted). A
PDG scale of 1 (0 in the combined modes) skips the PDG forward. Guidance
rescale pulls the guided norm toward the main norm.
"""
from __future__ import annotations
import itertools
import math
from bisect import bisect_right
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from enum import StrEnum
import numpy as np
import torch
from torch import Tensor
from .schedules import ScheduleCdf, TimeSchedule, build_timesteps
from .types import DFlowPath
SELF_ATTENTION_GAIN_MIN = -0.5
SELF_ATTENTION_GAIN_MAX = 0.1
DEFAULT_SELF_ATTENTION_GAIN = -0.03
DEFAULT_PDG_SCALE = 2.5
# Release default: the PDG reference reads the prompt less in its suffix layers.
DEFAULT_SUFFIX_CAPTION_BIAS = -4.0
SUFFIX_CAPTION_BIAS_MIN = -10.0
SUFFIX_CAPTION_BIAS_MAX = 0.0
# A PDG scale within this distance of its neutral value skips the PDG forward.
_NEUTRAL_SCALE_TOLERANCE = 1.0e-6
# The LINEAR_LOGSNR curve interpolates between these logSNR anchors.
_CURVE_LOGSNR_NOISY = -15.0
_CURVE_LOGSNR_CLEAN = 15.0
_BEZIER_SAMPLES = 4096
# Radial APG band edges in cycles per latent pixel: DC, (0, 1/32], (1/32, 1/8],
# (1/8, 1/4] and above 1/4.
PROJECTION_BAND_EDGES: tuple[float, ...] = (0.0, 1 / 32, 1 / 8, 1 / 4)
PROJECTION_BAND_COUNT = len(PROJECTION_BAND_EDGES) + 1
class BranchText(StrEnum):
"""Text a forward is conditioned on.
POSITIVE: the prompt.
NEGATIVE: the negative prompt, or the learned null text when there is none.
"""
POSITIVE = "positive"
NEGATIVE = "negative"
class GuidanceBranch(StrEnum):
"""A denoiser forward a guidance step may need: text branch and path."""
POSITIVE_FULL = "positive_full"
POSITIVE_PATH_DROP = "positive_path_drop"
POSITIVE_THREE_QUARTER = "positive_three_quarter"
NEGATIVE_FULL = "negative_full"
NEGATIVE_PATH_DROP = "negative_path_drop"
NEGATIVE_THREE_QUARTER = "negative_three_quarter"
@staticmethod
def of(text: BranchText, path: DFlowPath) -> GuidanceBranch:
"""Return the branch of a text branch and a path."""
return GuidanceBranch(f"{text.value}_{path.value}")
@property
def text(self) -> BranchText:
"""The text branch of this forward."""
return BranchText(self.value.split("_", 1)[0])
@property
def path(self) -> DFlowPath:
"""The routing path of this forward."""
return DFlowPath(self.value.split("_", 1)[1])
@dataclass(frozen=True)
class BranchCall:
"""One denoiser forward: branch, image self-attention logit gain and the
suffix layers' prompt-key logit bias (0: none)."""
branch: GuidanceBranch
self_attention_gain: float
suffix_caption_bias: float
class PdgMode(StrEnum):
"""Path-drop guidance policies (the reference is the same network with its
middle layers skipped).
FULL: middle dropped, prompt text.
FULL_CONTRASTIVE: middle dropped, negative text.
THREE_QUARTER: one image token per 2x2 group through the middle, prompt.
ALTERNATE_CONTRASTIVE_POSITIVE: FULL_CONTRASTIVE on even steps, FULL on odd.
ALTERNATE_PDG_FIRST / ALTERNATE_CFG_FIRST: contrastive full PDG and CFG on
alternate steps of the PDG window, starting with PDG / CFG.
ALTERNATE_POSITIVE_PDG_FIRST / ALTERNATE_POSITIVE_CFG_FIRST: the same with
prompt-text PDG.
COMBINED_CFG_PDG: CFG and contrastive PDG every step, differentials averaged.
PDG_WITH_ALTERNATING_CFG: contrastive PDG every step, plus CFG (averaged) on
odd steps.
CFG_TO_PDG: CFG before the PDG window, prompt-text full PDG inside it.
"""
FULL = "full"
FULL_CONTRASTIVE = "full_contrastive"
THREE_QUARTER = "three_quarter"
ALTERNATE_CONTRASTIVE_POSITIVE = "alternate_contrastive_positive"
ALTERNATE_PDG_FIRST = "alternate_pdg_first"
ALTERNATE_CFG_FIRST = "alternate_cfg_first"
ALTERNATE_POSITIVE_PDG_FIRST = "alternate_positive_pdg_first"
ALTERNATE_POSITIVE_CFG_FIRST = "alternate_positive_cfg_first"
COMBINED_CFG_PDG = "combined_cfg_pdg"
PDG_WITH_ALTERNATING_CFG = "pdg_with_alternating_cfg"
CFG_TO_PDG = "cfg_to_pdg"
@property
def uses_cfg(self) -> bool:
"""Whether the mode runs CFG forwards (and needs a CFG scale)."""
match self:
case (
PdgMode.ALTERNATE_PDG_FIRST
| PdgMode.ALTERNATE_CFG_FIRST
| PdgMode.ALTERNATE_POSITIVE_PDG_FIRST
| PdgMode.ALTERNATE_POSITIVE_CFG_FIRST
| PdgMode.COMBINED_CFG_PDG
| PdgMode.PDG_WITH_ALTERNATING_CFG
| PdgMode.CFG_TO_PDG
):
return True
case (
PdgMode.FULL
| PdgMode.FULL_CONTRASTIVE
| PdgMode.THREE_QUARTER
| PdgMode.ALTERNATE_CONTRASTIVE_POSITIVE
):
return False
case _ as unreachable:
raise ValueError(f"Unsupported PDG mode: {unreachable}")
@property
def alternates_with_cfg(self) -> bool:
"""Whether PDG and CFG alternate inside the PDG window."""
return self in _ALTERNATING_MODES
@property
def averages_cfg(self) -> bool:
"""Whether CFG and PDG differentials are averaged on shared steps."""
return self in (PdgMode.COMBINED_CFG_PDG, PdgMode.PDG_WITH_ALTERNATING_CFG)
def text_at(self, step: int) -> BranchText:
"""Text of this mode's PDG reference on ``step``."""
match self:
case PdgMode.ALTERNATE_CONTRASTIVE_POSITIVE:
return BranchText.NEGATIVE if step % 2 == 0 else BranchText.POSITIVE
case (
PdgMode.FULL_CONTRASTIVE
| PdgMode.ALTERNATE_PDG_FIRST
| PdgMode.ALTERNATE_CFG_FIRST
| PdgMode.COMBINED_CFG_PDG
| PdgMode.PDG_WITH_ALTERNATING_CFG
):
return BranchText.NEGATIVE
case (
PdgMode.FULL
| PdgMode.THREE_QUARTER
| PdgMode.CFG_TO_PDG
| PdgMode.ALTERNATE_POSITIVE_PDG_FIRST
| PdgMode.ALTERNATE_POSITIVE_CFG_FIRST
):
return BranchText.POSITIVE
case _ as unreachable:
raise ValueError(f"Unsupported PDG mode: {unreachable}")
@property
def uses_negative(self) -> bool:
"""Whether any step of this mode conditions on the negative text."""
return self.uses_cfg or BranchText.NEGATIVE in (
self.text_at(0),
self.text_at(1),
)
_ALTERNATING_MODES = frozenset(
{
PdgMode.ALTERNATE_PDG_FIRST,
PdgMode.ALTERNATE_CFG_FIRST,
PdgMode.ALTERNATE_POSITIVE_PDG_FIRST,
PdgMode.ALTERNATE_POSITIVE_CFG_FIRST,
}
)
def _alternation_uses_pdg(mode: PdgMode, step: int) -> bool:
"""Whether an alternating mode runs PDG (not CFG) on ``step``."""
match mode:
case PdgMode.ALTERNATE_PDG_FIRST | PdgMode.ALTERNATE_POSITIVE_PDG_FIRST:
return step % 2 == 0
case PdgMode.ALTERNATE_CFG_FIRST | PdgMode.ALTERNATE_POSITIVE_CFG_FIRST:
return step % 2 == 1
case _ as unsupported:
raise ValueError(f"{unsupported} does not alternate PDG and CFG.")
def _validate_scale(value: float, name: str) -> None:
"""Require a finite, non-negative guidance value.
Raises:
ValueError: Otherwise.
"""
if not math.isfinite(value) or value < 0.0:
raise ValueError(f"{name} must be finite and >= 0, got {value}.")
def _validate_gain(value: float, name: str) -> None:
"""Require a self-attention gain in [-0.5, 0.1].
Raises:
ValueError: Otherwise.
"""
if not (
math.isfinite(value)
and SELF_ATTENTION_GAIN_MIN <= value <= SELF_ATTENTION_GAIN_MAX
):
raise ValueError(
f"{name} must lie in [{SELF_ATTENTION_GAIN_MIN}, "
f"{SELF_ATTENTION_GAIN_MAX}], got {value}."
)
@dataclass(frozen=True)
class StepWindow:
"""Inclusive solver-step window; ``stop_step`` None is the last step.
Raises:
ValueError: For a negative start or a stop before the start.
"""
start_step: int = 0
stop_step: int | None = None
def __post_init__(self) -> None:
"""Validate the bounds that do not depend on the step count."""
if self.start_step < 0:
raise ValueError(f"start_step must be >= 0, got {self.start_step}.")
if self.stop_step is not None and self.stop_step < self.start_step:
raise ValueError(
f"stop_step {self.stop_step} is before start_step {self.start_step}."
)
def resolve(self, steps: int, name: str) -> tuple[int, int]:
"""Return (start, stop) for a run of ``steps`` updates.
Raises:
ValueError: If the window does not fit inside the run.
"""
stop = steps - 1 if self.stop_step is None else self.stop_step
if stop >= steps or self.start_step > stop:
raise ValueError(
f"The {name} window [{self.start_step}, {stop}] does not fit in "
f"{steps} steps (indices 0 to {steps - 1})."
)
return self.start_step, stop
@dataclass(frozen=True)
class CfgGuidance:
"""Classifier-free guidance against the negative text.
Attributes:
enabled: Run CFG inside ``window``. The alternating, combined and
CFG-to-PDG PDG modes run CFG forwards of their own and need
``scale`` even when this is False.
scale: Guidance scale (1 is no guidance); None when unused.
window: Steps where plain CFG applies.
Raises:
ValueError: For a negative scale or CFG enabled without a scale.
"""
enabled: bool = False
scale: float | None = None
window: StepWindow = field(default_factory=StepWindow)
def __post_init__(self) -> None:
"""Validate the scale."""
if self.scale is not None:
_validate_scale(self.scale, "CfgGuidance.scale")
if self.enabled and self.scale is None:
raise ValueError("CfgGuidance.scale is required when CFG is enabled.")
@dataclass(frozen=True)
class ConstantPdgScale:
"""The same PDG scale at every step."""
scale: float = DEFAULT_PDG_SCALE
def __post_init__(self) -> None:
"""Validate the scale."""
_validate_scale(self.scale, "ConstantPdgScale.scale")
@dataclass(frozen=True)
class RampPdgScale:
"""PDG scale linear in the schedule's CDF quantile from ``start_scale`` at the
noisy end to ``end_scale`` after ``length`` of the distribution, then held.
On the standard schedules step ``i`` of ``N`` sits at quantile ``1 - i/N``,
so ``length`` is the fraction of the steps (0.3: until step 15 of 50). The
scale is read at every evaluation's actual time.
"""
start_scale: float = 4.5
end_scale: float = DEFAULT_PDG_SCALE
length: float = 0.3
def __post_init__(self) -> None:
"""Validate scales and length.
Raises:
ValueError: For negative scales or a length outside (0, 1].
"""
_validate_scale(self.start_scale, "RampPdgScale.start_scale")
_validate_scale(self.end_scale, "RampPdgScale.end_scale")
if not (math.isfinite(self.length) and 0.0 < self.length <= 1.0):
raise ValueError(
f"RampPdgScale.length must lie in (0, 1], got {self.length}."
)
def scale_at_quantile(self, quantile: float) -> float:
"""Interpolate the two knots (1, start) and (1 - length, end)."""
knots = ((1.0, self.start_scale), (1.0 - self.length, self.end_scale))
q = min(1.0, max(knots[-1][0], quantile))
index = min(bisect_right(knots, -q, key=lambda knot: -knot[0]), len(knots) - 1)
high, low = knots[max(index - 1, 0)], knots[index]
fraction = (high[0] - q) / (high[0] - low[0])
return high[1] + fraction * (low[1] - high[1])
class EndpointCurveKind(StrEnum):
"""Shape of a per-step PDG curve from the noisy-end scale to the clean-end one.
LINEAR: linear in the step index.
LINEAR_LOGSNR: linear in the step's log-SNR between -15 and +15.
POWER: (step / steps) ** power.
S_CURVE: logistic in the step position, normalised to the endpoints.
"""
LINEAR = "linear"
LINEAR_LOGSNR = "linear_logsnr"
POWER = "power"
S_CURVE = "s_curve"
@dataclass(frozen=True)
class EndpointPdgCurve:
"""A per-step PDG scale from ``noisy_scale`` (first point) to ``clean_scale``
(last point).
Raises:
ValueError: For negative scales, a non-positive power or sharpness, or
a knee outside [0, 1].
"""
kind: EndpointCurveKind = EndpointCurveKind.POWER
noisy_scale: float = 2.0
clean_scale: float = DEFAULT_PDG_SCALE
power: float = 3.0
s_curve_knee: float = 0.5
s_curve_sharpness: float = 8.0
def __post_init__(self) -> None:
"""Validate every parameter."""
_validate_scale(self.noisy_scale, "EndpointPdgCurve.noisy_scale")
_validate_scale(self.clean_scale, "EndpointPdgCurve.clean_scale")
for name, value in (
("power", self.power),
("s_curve_sharpness", self.s_curve_sharpness),
):
if not (math.isfinite(value) and value > 0.0):
raise ValueError(f"EndpointPdgCurve.{name} must be > 0, got {value}.")
if not (math.isfinite(self.s_curve_knee) and 0.0 <= self.s_curve_knee <= 1.0):
raise ValueError(
f"EndpointPdgCurve.s_curve_knee must lie in [0, 1], got "
f"{self.s_curve_knee}."
)
@dataclass(frozen=True)
class BezierPdgCurve:
"""A per-step PDG scale ``1 + multiplier * y(t)`` with ``y`` a cubic Bezier
over flow time from ``(edge, clean_y)`` to ``(1 - edge, noisy_y)``.
Raises:
ValueError: For negative values, an edge outside (0, 0.5), handles
outside [edge, 1 - edge] or a clean handle after the noisy one.
"""
multiplier: float = 3.0
clean_y: float = 0.205
clean_handle_t: float = 0.010
clean_handle_y: float = 0.408
noisy_handle_t: float = 0.995
noisy_handle_y: float = 0.275
noisy_y: float = 0.523
edge: float = 0.005
def __post_init__(self) -> None:
"""Validate every control point."""
for name, value in (
("multiplier", self.multiplier),
("clean_y", self.clean_y),
("clean_handle_y", self.clean_handle_y),
("noisy_handle_y", self.noisy_handle_y),
("noisy_y", self.noisy_y),
):
_validate_scale(value, f"BezierPdgCurve.{name}")
if not (math.isfinite(self.edge) and 0.0 < self.edge < 0.5):
raise ValueError(
f"BezierPdgCurve.edge must lie in (0, 0.5), got {self.edge}."
)
for name, value in (
("clean_handle_t", self.clean_handle_t),
("noisy_handle_t", self.noisy_handle_t),
):
if not (math.isfinite(value) and self.edge <= value <= 1.0 - self.edge):
raise ValueError(
f"BezierPdgCurve.{name} must lie in [edge, 1 - edge], got {value}."
)
if self.clean_handle_t > self.noisy_handle_t:
raise ValueError("BezierPdgCurve.clean_handle_t must be <= noisy_handle_t.")
type PdgScaleSchedule = (
ConstantPdgScale | RampPdgScale | EndpointPdgCurve | BezierPdgCurve
)
@dataclass(frozen=True)
class PdgGuidance:
"""Path-drop guidance: policy, scale schedule, step window and the
reference's suffix caption bias.
Attributes:
suffix_caption_bias: Additive attention-logit bias on the prompt's
token keys (the learned suffix tokens excluded) in the six suffix
layers of every PDG reference forward; negative values make the
reference read the prompt less. 0 turns it off; the supported
range is ``[SUFFIX_CAPTION_BIAS_MIN, SUFFIX_CAPTION_BIAS_MAX]``.
Raises:
ValueError: For a quantile ramp with CFG_TO_PDG, or a suffix caption
bias outside the supported range.
"""
mode: PdgMode = PdgMode.FULL
scale: PdgScaleSchedule = field(default_factory=ConstantPdgScale)
window: StepWindow = field(default_factory=StepWindow)
suffix_caption_bias: float = DEFAULT_SUFFIX_CAPTION_BIAS
def __post_init__(self) -> None:
"""Reject the ramp with the step-window crossover mode and a bias
outside the supported range."""
if not (
math.isfinite(self.suffix_caption_bias)
and SUFFIX_CAPTION_BIAS_MIN
<= self.suffix_caption_bias
<= SUFFIX_CAPTION_BIAS_MAX
):
raise ValueError(
"suffix_caption_bias must lie in "
f"[{SUFFIX_CAPTION_BIAS_MIN}, {SUFFIX_CAPTION_BIAS_MAX}], got "
f"{self.suffix_caption_bias}."
)
if self.mode is PdgMode.CFG_TO_PDG and isinstance(self.scale, RampPdgScale):
raise ValueError(
"CFG_TO_PDG switches on the step window; use a constant or "
"per-step PDG scale with it, not a quantile ramp."
)
class ProjectionMode(StrEnum):
"""Adaptive projected guidance (APG) on the x0-space guidance update.
OFF: plain guidance.
GLOBAL: one projection per sample.
PER_BAND: one projection per sample and radial frequency band.
"""
OFF = "off"
GLOBAL = "global"
PER_BAND = "per_band"
@dataclass(frozen=True)
class ProjectedGuidance:
"""APG: the guided x0 is ``x0_main + (w - 1)(D_perp + parallel_weight D_par)``
with ``D = x0_main - x0_reference`` split against ``x0_main``.
Attributes:
mode: OFF, GLOBAL or PER_BAND.
parallel_weight: Weight kept on the parallel part (1 is plain guidance).
first_band: PER_BAND only: bands below it stay unprojected (0 is the
mean colour, 1 the coarsest structure).
Raises:
ValueError: For a weight outside [0, 1] or an invalid first band.
"""
mode: ProjectionMode = ProjectionMode.OFF
parallel_weight: float = 1.0
first_band: int = 0
def __post_init__(self) -> None:
"""Validate weight and band."""
if not (
math.isfinite(self.parallel_weight) and 0.0 <= self.parallel_weight <= 1.0
):
raise ValueError(
"ProjectedGuidance.parallel_weight must lie in [0, 1], got "
f"{self.parallel_weight}."
)
if not 0 <= self.first_band < PROJECTION_BAND_COUNT:
raise ValueError(
f"ProjectedGuidance.first_band must lie in [0, "
f"{PROJECTION_BAND_COUNT - 1}], got {self.first_band}."
)
if self.mode is not ProjectionMode.PER_BAND and self.first_band != 0:
raise ValueError("ProjectedGuidance.first_band needs PER_BAND mode.")
class SparseStepSchedule(StrEnum):
"""Which steps run the main and CFG forwards on the three-quarter path.
PREFIX: the first ``percent`` of the steps.
CYCLIC: ``percent`` of the steps spread evenly (50: every other step).
"""
PREFIX = "prefix"
CYCLIC = "cyclic"
@dataclass(frozen=True)
class SparseMiddleSteps:
"""Speed option: run the main (and CFG) forwards with one image token per
2x2 group through the middle on some steps; PDG then drops the full middle.
Raises:
ValueError: For a percent outside [0, 100].
"""
percent: float = 0.0
schedule: SparseStepSchedule = SparseStepSchedule.PREFIX
def __post_init__(self) -> None:
"""Validate the percent."""
if not (math.isfinite(self.percent) and 0.0 <= self.percent <= 100.0):
raise ValueError(
f"SparseMiddleSteps.percent must lie in [0, 100], got {self.percent}."
)
def active(self, step: int, steps: int) -> bool:
"""Whether ``step`` (0-based, of ``steps``) is sparse."""
if self.percent <= 0.0:
return False
match self.schedule:
case SparseStepSchedule.PREFIX:
count = math.ceil((self.percent / 100.0) * float(steps))
return step < max(0, min(steps, count))
case SparseStepSchedule.CYCLIC:
before = math.floor((float(step) * self.percent) / 100.0)
after = math.floor((float(step + 1) * self.percent) / 100.0)
return after > before
case _ as unreachable:
raise ValueError(f"Unsupported sparse step schedule: {unreachable}")
@dataclass(frozen=True)
class GuidanceSettings:
"""Complete guidance configuration (defaults: the release's default preset).
Attributes:
pdg: Path-drop guidance, or None for none.
cfg: Classifier-free guidance.
self_attention_gain: Image self-attention logit gain of the main forward.
guidance_self_attention_gain: Gain of the guidance forwards.
projection: APG on single-reference steps.
rescale: Guidance rescale in [0, 1] (0 off); exclusive with APG.
sparse_middle: Sparse middle steps on the main and CFG forwards.
Raises:
ValueError: On inconsistent or out-of-range settings.
"""
pdg: PdgGuidance | None = field(default_factory=PdgGuidance)
cfg: CfgGuidance = field(default_factory=CfgGuidance)
self_attention_gain: float = DEFAULT_SELF_ATTENTION_GAIN
guidance_self_attention_gain: float = 0.0
projection: ProjectedGuidance = field(default_factory=ProjectedGuidance)
rescale: float = 0.0
sparse_middle: SparseMiddleSteps = field(default_factory=SparseMiddleSteps)
def __post_init__(self) -> None:
"""Validate gains, CFG needs, APG and rescale."""
_validate_gain(self.self_attention_gain, "self_attention_gain")
_validate_gain(
self.guidance_self_attention_gain, "guidance_self_attention_gain"
)
if self.pdg is not None and self.pdg.mode.uses_cfg and self.cfg.scale is None:
raise ValueError(f"PDG mode {self.pdg.mode.value} needs cfg.scale.")
if (
self.cfg.scale is not None
and not self.cfg.enabled
and not (self.pdg is not None and self.pdg.mode.uses_cfg)
):
raise ValueError(
"cfg.scale is set but neither CFG nor a CFG-using PDG mode is on."
)
if not (math.isfinite(self.rescale) and 0.0 <= self.rescale <= 1.0):
raise ValueError(f"rescale must lie in [0, 1], got {self.rescale}.")
if self.projection.mode is not ProjectionMode.OFF:
self._validate_projection()
def _validate_projection(self) -> None:
"""APG needs guidance, excludes rescale and the averaged modes.
Raises:
ValueError: Otherwise.
"""
if self.pdg is None and not self.cfg.enabled:
raise ValueError("Projected guidance needs CFG or PDG on.")
if self.rescale > 0.0:
raise ValueError("Projected guidance and guidance rescale are exclusive.")
if self.pdg is not None and self.pdg.mode.averages_cfg:
raise ValueError(
f"Projected guidance needs a single reference; {self.pdg.mode.value} "
"averages two."
)
@property
def uses_negative(self) -> bool:
"""Whether any forward conditions on the negative (or null) text."""
return self.cfg.enabled or (
self.pdg is not None and self.pdg.mode.uses_negative
)
@dataclass(frozen=True)
class UnguidedStep:
"""Only the main forward."""
main: BranchCall
@dataclass(frozen=True)
class SingleReferenceStep:
"""``v_ref + scale (v_main - v_ref)`` (or its APG projection)."""
main: BranchCall
reference: BranchCall
scale: float
@dataclass(frozen=True)
class AveragedStep:
"""``v_main + 0.5 (cfg_scale (v_main - v_cfg) + pdg_scale (v_main - v_pdg))``;
``pdg`` None (neutral PDG scale) uses ``v_pdg = v_main``."""
main: BranchCall
cfg: BranchCall
pdg: BranchCall | None
cfg_scale: float
pdg_scale: float
type GuidanceStep = UnguidedStep | SingleReferenceStep | AveragedStep
def _sigmoid(value: float) -> float:
"""Numerically stable logistic function."""
if value >= 0.0:
return 1.0 / (1.0 + math.exp(-value))
exp_value = math.exp(value)
return exp_value / (1.0 + exp_value)
def _positions(count: int) -> list[float]:
"""Evenly spaced positions in [0, 1] (``[0.0]`` for one point)."""
if count == 1:
return [0.0]
return [float(index) / float(count - 1) for index in range(count)]
def _endpoint_weights(
curve: EndpointPdgCurve, count: int, times: Sequence[float]
) -> list[float]:
"""Interpolation weights (0 noisy, 1 clean) of an endpoint curve.
Raises:
ValueError: For fewer than two points or a degenerate S-curve.
"""
if count < 2:
raise ValueError(f"A {curve.kind.value} PDG curve needs at least two points.")
positions = _positions(count)
match curve.kind:
case EndpointCurveKind.LINEAR:
return positions
case EndpointCurveKind.POWER:
return [position**curve.power for position in positions]
case EndpointCurveKind.LINEAR_LOGSNR:
span = _CURVE_LOGSNR_CLEAN - _CURVE_LOGSNR_NOISY
weights = []
for time in times:
clamped = min(max(time, 1e-12), 1.0 - 1e-12)
log_snr = -2.0 * (math.log(clamped) - math.log1p(-clamped))
weights.append(
min(max((log_snr - _CURVE_LOGSNR_NOISY) / span, 0.0), 1.0)
)
return weights
case EndpointCurveKind.S_CURVE:
raw = [
_sigmoid((position - curve.s_curve_knee) * curve.s_curve_sharpness)
for position in positions
]
if raw[-1] - raw[0] <= 1e-12:
raise ValueError("s_curve_sharpness is too small to normalise.")
return [(value - raw[0]) / (raw[-1] - raw[0]) for value in raw]
case _ as unreachable:
raise ValueError(f"Unsupported endpoint curve: {unreachable}")
def _bezier_values(curve: BezierPdgCurve, count: int) -> list[float]:
"""Per-point ``1 + multiplier * y`` of a Bezier curve, noisy point first."""
u = np.linspace(0.0, 1.0, _BEZIER_SAMPLES, dtype=np.float64)
v = 1.0 - u
basis = (v * v * v, 3.0 * v * v * u, 3.0 * v * u * u, u * u * u)
xs = (curve.edge, curve.clean_handle_t, curve.noisy_handle_t, 1.0 - curve.edge)
ys = (curve.clean_y, curve.clean_handle_y, curve.noisy_handle_y, curve.noisy_y)
x_values = basis[0] * xs[0] + basis[1] * xs[1] + basis[2] * xs[2] + basis[3] * xs[3]
y_values = basis[0] * ys[0] + basis[1] * ys[1] + basis[2] * ys[2] + basis[3] * ys[3]
order = np.argsort(x_values)
query = np.asarray([1.0 - position for position in _positions(count)])
interpolated = np.interp(query, x_values[order], y_values[order])
return [1.0 + curve.multiplier * float(value) for value in interpolated.tolist()]
def per_step_pdg_scales(
curve: EndpointPdgCurve | BezierPdgCurve,
*,
schedule: TimeSchedule,
log_snr_shift: float,
) -> tuple[float, ...]:
"""Return a per-step curve's PDG scale at each of the ``steps + 1`` points,
rounded to float32 (as the training code stores them).
LINEAR_LOGSNR reads the shifted schedule's times without the noisy-endpoint
cap.
"""
count = schedule.steps + 1
match curve:
case BezierPdgCurve():
values = _bezier_values(curve, count)
case EndpointPdgCurve():
times = build_timesteps(
schedule,
log_snr_shift=log_snr_shift,
finite_noisy_endpoint=False,
device=torch.device("cpu"),
).tolist()
weights = _endpoint_weights(curve, count, times)
noisy, clean = curve.noisy_scale, curve.clean_scale
values = [noisy + (clean - noisy) * weight for weight in weights]
case _ as unreachable:
raise ValueError(f"Unsupported PDG curve: {unreachable}")
return tuple(torch.tensor(values, dtype=torch.float32, device="cpu").tolist())
@dataclass(frozen=True)
class _PlanInputs:
"""Run-level values the per-step resolution reads."""
settings: GuidanceSettings
steps: int
times: tuple[float, ...]
cdf: ScheduleCdf
pdg_values: tuple[float, ...] | None
cfg_window: tuple[int, int] | None
pdg_window: tuple[int, int] | None
@dataclass(frozen=True)
class _Activity:
"""Which guidance runs on one step and the PDG reference path."""
cfg: bool
pdg: bool
pdg_path: DFlowPath
def _concrete_pdg_path(mode: PdgMode) -> DFlowPath:
"""The reference path of a single-reference PDG mode."""
return (
DFlowPath.THREE_QUARTER
if mode is PdgMode.THREE_QUARTER
else DFlowPath.PATH_DROP
)
def _inside(step: int, window: tuple[int, int] | None) -> bool:
"""Whether ``step`` lies in an inclusive window (None: never)."""
return window is not None and window[0] <= step <= window[1]
def _resolve_activity(inputs: _PlanInputs, step: int) -> _Activity:
"""Resolve which of CFG and PDG run on ``step`` (clamped step index)."""
cfg_window = _inside(step, inputs.cfg_window)
pdg_window = _inside(step, inputs.pdg_window)
pdg = inputs.settings.pdg
if pdg is None:
return _Activity(cfg_window, False, DFlowPath.PATH_DROP)
mode = pdg.mode
if pdg_window and mode.alternates_with_cfg:
uses_pdg = _alternation_uses_pdg(mode, step)
return _Activity(not uses_pdg, uses_pdg, DFlowPath.PATH_DROP)
if mode is PdgMode.CFG_TO_PDG:
if pdg_window:
return _Activity(False, True, DFlowPath.PATH_DROP)
start = inputs.pdg_window[0] if inputs.pdg_window is not None else 0
return _Activity(step < start, False, DFlowPath.PATH_DROP)
if pdg_window and mode is PdgMode.PDG_WITH_ALTERNATING_CFG:
return _Activity(step % 2 == 1, True, DFlowPath.PATH_DROP)
if pdg_window and mode is PdgMode.COMBINED_CFG_PDG:
return _Activity(True, True, DFlowPath.PATH_DROP)
return _Activity(cfg_window, pdg_window, _concrete_pdg_path(mode))
def _pdg_scale(inputs: _PlanInputs, index: int) -> float:
"""The absolute PDG scale at schedule point ``index``."""
pdg = inputs.settings.pdg
if pdg is None:
raise ValueError("PDG scale requested without PDG.")
match pdg.scale:
case ConstantPdgScale(scale=scale):
return scale
case RampPdgScale() as ramp:
return ramp.scale_at_quantile(
inputs.cdf.quantile_at_time(inputs.times[index])
)
case EndpointPdgCurve() | BezierPdgCurve():
if inputs.pdg_values is None:
raise ValueError("Per-step PDG values were not prepared.")
return inputs.pdg_values[index]
case _ as unreachable:
raise ValueError(f"Unsupported PDG scale: {unreachable}")
def _cfg_scale(settings: GuidanceSettings) -> float:
"""The CFG scale of an active CFG forward."""
if settings.cfg.scale is None:
raise ValueError("A CFG forward is active but cfg.scale is None.")
return settings.cfg.scale
def _resolve_step(inputs: _PlanInputs, index: int) -> GuidanceStep:
"""Resolve the forwards and combination of schedule point ``index``."""
settings = inputs.settings
step = min(index, inputs.steps - 1)
activity = _resolve_activity(inputs, step)
cfg_on, pdg_on = activity.cfg, activity.pdg
mode = settings.pdg.mode if settings.pdg is not None else None
averaged = cfg_on and pdg_on and mode is not None and mode.averages_cfg
ramp = settings.pdg is not None and isinstance(settings.pdg.scale, RampPdgScale)
pdg_scale = _pdg_scale(inputs, index) if pdg_on else 0.0
neutral = 0.0 if averaged and not ramp else 1.0
if pdg_on and math.isclose(
pdg_scale, neutral, rel_tol=0.0, abs_tol=_NEUTRAL_SCALE_TOLERANCE
):
pdg_on = False
alternating_cfg = (
cfg_on and not pdg_on and mode is not None and mode.alternates_with_cfg
)
main_gain = 0.0 if alternating_cfg else settings.self_attention_gain
guidance_gain = 0.0 if alternating_cfg else settings.guidance_self_attention_gain
sparse = settings.sparse_middle.active(step, inputs.steps)
dense_path = DFlowPath.THREE_QUARTER if sparse else DFlowPath.FULL
pdg_path = DFlowPath.PATH_DROP if sparse else activity.pdg_path
caption_bias = settings.pdg.suffix_caption_bias if settings.pdg is not None else 0.0
main = BranchCall(
GuidanceBranch.of(BranchText.POSITIVE, dense_path), main_gain, 0.0
)
if not (cfg_on or pdg_on):
return UnguidedStep(main)
cfg_call = BranchCall(
GuidanceBranch.of(BranchText.NEGATIVE, dense_path), guidance_gain, 0.0
)
if averaged:
pdg_call = (
BranchCall(
GuidanceBranch.of(BranchText.NEGATIVE, pdg_path),
guidance_gain,
caption_bias,
)
if pdg_on
else None
)
pdg_extra = _pdg_scale(inputs, index) - (1.0 if ramp else 0.0)
return AveragedStep(main, cfg_call, pdg_call, _cfg_scale(settings), pdg_extra)
if not pdg_on or mode is None:
return SingleReferenceStep(main, cfg_call, _cfg_scale(settings))
text = mode.text_at(step)
reference = BranchCall(
GuidanceBranch.of(text, pdg_path), guidance_gain, caption_bias
)
return SingleReferenceStep(main, reference, pdg_scale)
def _band_masks(height: int, width: int, device: torch.device) -> Tensor:
"""Radial ``[bands, H, W]`` FFT masks of ``PROJECTION_BAND_EDGES``."""
fy = torch.fft.fftfreq(height, device=device)
fx = torch.fft.fftfreq(width, device=device)
radius = torch.sqrt(fy[:, None].square() + fx[None, :].square())
masks = [radius == 0.0]
for low, high in itertools.pairwise(PROJECTION_BAND_EDGES):
masks.append((radius > low) & (radius <= high))
masks.append(radius > PROJECTION_BAND_EDGES[-1])
return torch.stack(masks).to(dtype=torch.float32)
def _parallel_part(
delta: Tensor, reference: Tensor, projection: ProjectedGuidance
) -> Tensor:
"""The part of ``delta`` parallel to ``reference`` (float32 ``[B, C, H, W]``),
per sample or per sample and band from ``first_band`` on."""
eps = torch.finfo(torch.float32).eps
match projection.mode:
case ProjectionMode.GLOBAL:
dims = (1, 2, 3)
coefficient = (delta * reference).sum(dims, keepdim=True) / (
reference.square().sum(dims, keepdim=True) + eps
)
return coefficient * reference
case ProjectionMode.PER_BAND:
masks = _band_masks(
int(delta.shape[-2]), int(delta.shape[-1]), delta.device
)
fd = torch.fft.fft2(delta, norm="ortho")
fr = torch.fft.fft2(reference, norm="ortho")
parallel = torch.zeros_like(fr)
for mask in masks[projection.first_band :]:
band = fr * mask
coefficient = (fd * band.conj()).real.sum((1, 2, 3), keepdim=True) / (
band.abs().square().sum((1, 2, 3), keepdim=True) + eps
)
parallel = parallel + coefficient * band
return torch.fft.ifft2(parallel, norm="ortho").real
case ProjectionMode.OFF:
raise ValueError("An OFF projection has no parallel part.")
case _ as unreachable:
raise ValueError(f"Unsupported projection mode: {unreachable}")
def projected_guidance_velocity(
*,
main: Tensor,
reference: Tensor,
state: Tensor,
time: Tensor,
scale: float,
projection: ProjectedGuidance,
) -> Tensor:
"""APG in velocity units: ``v_main + (w - 1)(dv - (1 - parallel_weight)
dv_par)``, ``dv = v_main - v_ref`` and ``dv_par`` its part parallel to
``x0_main = x_t - t v_main``."""
t_view = time.to(device=main.device, dtype=torch.float32).view(
(-1,) + (1,) * (main.dim() - 1)
)
x0_main = state.to(dtype=torch.float32) - t_view * main.to(dtype=torch.float32)
delta = (main - reference).to(dtype=torch.float32)
parallel = _parallel_part(delta, x0_main, projection)
update = (scale - 1.0) * (delta - (1.0 - projection.parallel_weight) * parallel)
return (main.to(dtype=torch.float32) + update).to(dtype=main.dtype)
def rescale_guided_velocity(
*, guided: Tensor, reference: Tensor, rescale: float
) -> Tensor:
"""Interpolate ``guided`` toward its per-sample rescale to ``reference``'s norm."""
if rescale == 0.0:
return guided
flat = (int(guided.shape[0]), -1)
guided32 = guided.to(dtype=torch.float32)
guided_norm = guided32.reshape(flat).norm(dim=1, keepdim=True)
reference_norm = (
reference.to(dtype=torch.float32).reshape(flat).norm(dim=1, keepdim=True)
)
view = (int(guided.shape[0]),) + (1,) * (guided.dim() - 1)
eps = torch.finfo(torch.float32).eps
rescaled = guided32 * (
reference_norm.view(view) / guided_norm.clamp_min(eps).view(view)
)
return torch.lerp(guided32, rescaled, rescale).to(dtype=guided.dtype)
type BranchEvaluator = Callable[[BranchCall], Tensor]
@dataclass(frozen=True)
class GuidancePlan:
"""Per-schedule-point guidance of one run (``build_guidance_plan``).
Attributes:
steps: One ``GuidanceStep`` per schedule point, index 0 the noisy end.
projection: APG of the single-reference steps.
rescale: Guidance rescale.
"""
steps: tuple[GuidanceStep, ...]
projection: ProjectedGuidance
rescale: float
def calls(self, index: int) -> tuple[BranchCall, ...]:
"""The forwards point ``index`` runs, in evaluation order."""
match self.steps[index]:
case UnguidedStep(main=main):
return (main,)
case SingleReferenceStep(main=main, reference=reference):
return (main, reference)
case AveragedStep(main=main, cfg=cfg, pdg=None):
return (main, cfg)
case AveragedStep(main=main, cfg=cfg, pdg=BranchCall() as pdg):
return (main, cfg, pdg)
case _ as unreachable:
raise ValueError(f"Unsupported guidance step: {unreachable}")
def guided_velocity(
self, index: int, state: Tensor, time: Tensor, evaluate: BranchEvaluator
) -> Tensor:
"""Run point ``index``'s forwards through ``evaluate`` (main first) and
return the guided velocity in ``state``'s dtype.
Args:
index: Schedule point (the solver's ``step_index``).
state: The solver state ``x_t`` (APG reads it).
time: Float32 ``[B]`` times of the point.
evaluate: Runs one forward at ``(state, time)``.
"""
step = self.steps[index]
main = evaluate(step.main)
match step:
case UnguidedStep():
return main.to(dtype=state.dtype)
case SingleReferenceStep(reference=reference, scale=scale):
guided = self._single(main, evaluate(reference), state, time, scale)
case AveragedStep() as averaged:
cfg = evaluate(averaged.cfg)
pdg = main if averaged.pdg is None else evaluate(averaged.pdg)
guided = main + 0.5 * (
averaged.cfg_scale * (main - cfg)
+ averaged.pdg_scale * (main - pdg)
)
case _ as unreachable:
raise ValueError(f"Unsupported guidance step: {unreachable}")
if self.rescale > 0.0:
guided = rescale_guided_velocity(
guided=guided, reference=main, rescale=self.rescale
)
return guided.to(dtype=state.dtype)
def _single(
self, main: Tensor, reference: Tensor, state: Tensor, time: Tensor, scale: float
) -> Tensor:
"""Combine one reference with the main velocity (plain or APG)."""
if self.projection.mode is ProjectionMode.OFF:
return reference + scale * (main - reference)
return projected_guidance_velocity(
main=main,
reference=reference,
state=state,
time=time,
scale=scale,
projection=self.projection,
)
def build_guidance_plan(
settings: GuidanceSettings,
*,
schedule: TimeSchedule,
log_snr_shift: float,
timesteps: Sequence[float],
) -> GuidancePlan:
"""Resolve ``settings`` for one run.
Args:
settings: Validated guidance settings.
schedule: The run's schedule family and step count.
log_snr_shift: The effective shift the schedule was built with.
timesteps: Host copy of the solver's schedule (``steps + 1`` floats,
with the noisy-endpoint cap if the solver uses it); the ramp reads
its quantiles at these times.
Returns:
One ``GuidanceStep`` per schedule point.
Raises:
ValueError: If a window does not fit, ``timesteps`` has the wrong
length, or CFG is on with a PDG mode that has no CFG steps and the
two windows overlap (PDG would silently take those steps).
"""
steps = schedule.steps
if len(timesteps) != steps + 1:
raise ValueError(
f"timesteps has {len(timesteps)} points; the schedule has {steps + 1}."
)
pdg = settings.pdg
pdg_values = None
if pdg is not None:
match pdg.scale:
case EndpointPdgCurve() | BezierPdgCurve() as curve:
pdg_values = per_step_pdg_scales(
curve, schedule=schedule, log_snr_shift=log_snr_shift
)
case ConstantPdgScale() | RampPdgScale():
pass
case _ as unreachable:
raise ValueError(f"Unsupported PDG scale: {unreachable}")
cfg_window = (
settings.cfg.window.resolve(steps, "CFG") if settings.cfg.enabled else None
)
pdg_window = pdg.window.resolve(steps, "PDG") if pdg is not None else None
_reject_shadowed_cfg(settings, cfg_window, pdg_window)
inputs = _PlanInputs(
settings=settings,
steps=steps,
times=tuple(float(time) for time in timesteps),
cdf=ScheduleCdf(schedule, log_snr_shift),
pdg_values=pdg_values,
cfg_window=cfg_window,
pdg_window=pdg_window,
)
return GuidancePlan(
steps=tuple(_resolve_step(inputs, index) for index in range(steps + 1)),
projection=settings.projection,
rescale=settings.rescale,
)
def _reject_shadowed_cfg(
settings: GuidanceSettings,
cfg_window: tuple[int, int] | None,
pdg_window: tuple[int, int] | None,
) -> None:
"""Reject CFG that a PDG mode without CFG steps would silently replace.
Raises:
ValueError: If CFG is on, the PDG mode runs no CFG forwards and the
CFG and PDG windows share a step.
"""
pdg = settings.pdg
if cfg_window is None or pdg_window is None or pdg is None or pdg.mode.uses_cfg:
return
first = max(cfg_window[0], pdg_window[0])
last = min(cfg_window[1], pdg_window[1])
if first <= last:
raise ValueError(
f"CFG and PDG mode {pdg.mode.value} are both active on steps "
f"{first}-{last}; PDG would take those steps. Use a PDG mode that "
"includes CFG (combined_cfg_pdg, alternate_*, pdg_with_alternating_cfg, "
"cfg_to_pdg) or make the step windows disjoint."
)
# The three-quarter routing keeps one token of each 2x2 latent group, so the
# token grid needs even sides: image sides that are multiples of this.
THREE_QUARTER_SIZE_MULTIPLE = 32
def check_three_quarter_size(
settings: GuidanceSettings, width: int, height: int
) -> None:
"""Reject an image size the three-quarter routing cannot run at.
Raises:
ValueError: If PDG mode ``three_quarter`` or sparse middle steps are
on and a side is not a multiple of ``THREE_QUARTER_SIZE_MULTIPLE``.
"""
three_quarter = settings.pdg is not None and (
settings.pdg.mode is PdgMode.THREE_QUARTER
)
if not (three_quarter or settings.sparse_middle.percent > 0.0):
return
if width % THREE_QUARTER_SIZE_MULTIPLE or height % THREE_QUARTER_SIZE_MULTIPLE:
raise ValueError(
"PDG mode three_quarter and sparse middle steps need a width and "
f"height that are multiples of {THREE_QUARTER_SIZE_MULTIPLE}; got "
f"{width}x{height}."
)
|