Compare commits

..
3 Commits
Author SHA1 Message Date
Reithan 60b5127cf4 Update to Math v0.6.0 (#12)
- [X] add math 0.6
- [X] update readme
- [X] add example images
- [X] upload permanent copy of graph image
2025-07-21 01:14:06 -07:00
Reithan e72afd4189 update note 2025-07-20 07:20:35 -07:00
Reithan 98a9b6d656 minor optimizations 2025-07-20 07:13:07 -07:00
7 changed files with 225 additions and 111 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 MiB

+171 -90
View File
@@ -19,7 +19,6 @@ _RAW_TO_ENUM = {
"sample": PredictionType.X0,
}
class NRS:
@classmethod
def INPUT_TYPES(s):
@@ -71,75 +70,119 @@ class NRS:
# 3) default ------------------------------------------------------
return PredictionType.UNKNOWN
def _pre_scale_conditioning(self, x_orig, sigma, cond, uncond):
def _convert_to_eps_space(self, x_orig, sig_root, sigma, cond, uncond):
x_div = None
eps_cond = cond
eps_uncond = uncond
if self.__pred_type == PredictionType.V:
# v → ε conversion
logging.debug(f"NRS._pre_scale_conditioning: generating x_div, cond, and uncond for v-pred")
sigma2_1 = (sigma ** 2 + 1.0)
x_div = x_orig / sigma2_1
root = sigma2_1.sqrt()
logging.debug(f"NRS._convert_to_eps_space: generating x_div, eps_cond, and eps_uncond for v-pred")
x_div = x_orig / (sigma ** 2 + 1)
eps_cond = ((x_div - (x_orig - cond)) * root) / (sigma)
eps_uncond = ((x_div - (x_orig - uncond)) * root) / (sigma)
eps_cond = ((x_div - (x_orig - cond)) * sig_root) / (sigma)
eps_uncond = ((x_div - (x_orig - uncond)) * sig_root) / (sigma)
elif self.__pred_type == PredictionType.EPS:
logging.debug(f"NRS._pre_scale_conditioning: already in eps, no pre-scale needed")
logging.debug(f"NRS._convert_to_eps_space: already in eps, no pre-scale needed")
pass # already in ε space
elif self.__pred_type == PredictionType.X0:
raise NotImplementedError("NRS._pre_scale_conditioning: x0-prediction not supported yet.")
raise NotImplementedError("NRS._convert_to_eps_space: x0-prediction not supported yet.")
else:
raise RuntimeError("NRS._pre_scale_conditioning: Could not determine prediction type for this model.")
raise RuntimeError("NRS._convert_to_eps_space: Could not determine prediction type for this model.")
return x_div, eps_cond, eps_uncond
def _post_scale_conditioning(self, x_orig, x_div, x_final, sigma):
def _finalize_from_eps_space(self, x_orig, x_div, x_final, sig_root, sigma):
nrs_result = x_final
if self.__pred_type == PredictionType.V:
# ε → v conversion
root = (sigma ** 2 + 1).sqrt()
logging.debug(f"NRS._post_scale_conditioning: generating cfg_result for v-pred")
return x_orig - (x_div - x_final * sigma / root)
logging.debug(f"NRS._finalize_from_eps_space: generating cfg_result for v-pred")
nrs_result = x_orig - (x_div - x_final * sigma / sig_root)
elif self.__pred_type == PredictionType.EPS:
# already in ε space
logging.debug(f"NRS._post_scale_conditioning: already in eps, no post-scale needed")
return x_final
logging.debug(f"NRS._finalize_from_eps_space: already in eps, no post-scale needed")
pass
elif self.__pred_type == PredictionType.X0:
raise NotImplementedError("NRS._post_scale_conditioning: x0-prediction not supported yet.")
raise NotImplementedError("NRS._finalize_from_eps_space: x0-prediction not supported yet.")
else:
raise RuntimeError("NRS._post_scale_conditioning: Could not determine prediction type for this model.")
raise RuntimeError("NRS._finalize_from_eps_space: Could not determine prediction type for this model.")
return nrs_result
def _convert_to_v_space(self, x_orig, sig_root, sigma, cond, uncond):
x_div = None
v_cond = cond
v_uncond = uncond
if self.__pred_type == PredictionType.V:
logging.debug(f"NRS._convert_to_v_space: already in v, no pre-scale needed")
pass # already in v space
elif self.__pred_type == PredictionType.EPS:
# ε → v conversion
logging.debug(f"NRS._convert_to_v_space: generating x_div, v_cond, and v_uncond for eps")
x_div = x_orig / (sigma ** 2 + 1)
factor = sigma / sig_root
v_cond = x_orig - (x_div - cond * factor)
v_uncond = x_orig - (x_div - uncond * factor)
elif self.__pred_type == PredictionType.X0:
raise NotImplementedError("NRS._convert_to_v_space: x0-prediction not supported yet.")
else:
raise RuntimeError("NRS._convert_to_v_space: Could not determine prediction type for this model.")
return x_div, v_cond, v_uncond
def _finalize_from_v_space(self, x_orig, x_div, x_final, sig_root, sigma):
nrs_result = x_final
if self.__pred_type == PredictionType.V:
# already in v space
logging.debug(f"NRS._finalize_from_v_space: already in v, no post-scale needed")
pass
elif self.__pred_type == PredictionType.EPS:
# v → ε conversion
logging.debug(f"NRS._finalize_from_v_space: generating cfg_result for eps")
nrs_result = (x_div - (x_orig - x_final)) * (sig_root / sigma)
elif self.__pred_type == PredictionType.X0:
raise NotImplementedError("NRS._finalize_from_v_space: x0-prediction not supported yet.")
else:
raise RuntimeError("NRS._finalize_from_v_space: Could not determine prediction type for this model.")
return nrs_result
def patch(self, model, skew, stretch, squash):
self.__pred_type = self._get_pred_type(model) if not hasattr(self, "__pred_type") else self.__pred_type
self.__OPERATION_SPACE = PredictionType.V
def nrs(args):
logging.debug(f"NRS.nrs: Skew: {skew}, Stretch: {stretch}, Squash: {squash}")
# self.__pred_type = self.__pred_type if self.__pred_type is not None else self._get_pred_type(model)
cond = args["cond"]
uncond = args["uncond"]
x_orig = args["input"]
self.__pred_type = self.__pred_type if self.__pred_type is not None else self._get_pred_type(model)
sigma = None
if self.__pred_type == PredictionType.V:
sigma = args["sigma"]
sigma = sigma.view(sigma.shape[:1] + (1,) * (cond.ndim - 1))
logging.debug(f"NRS.nrs: Skew: {skew}, Stretch: {stretch}, Squash: {squash}")
sigma = args["sigma"]
sigma = sigma.view(sigma.shape[:1] + (1,) * (cond.ndim - 1))
sig_root = (sigma ** 2 + 1).sqrt()
x_div, eps_cond, eps_uncond = self._pre_scale_conditioning(x_orig, sigma, cond, uncond)
nrs_cond, nrs_uncond = None, None
match self.__OPERATION_SPACE:
case PredictionType.V:
x_div, nrs_cond, nrs_uncond = self._convert_to_v_space(x_orig, sig_root, sigma, cond, uncond)
case PredictionType.EPS:
x_div, nrs_cond, nrs_uncond = self._convert_to_eps_space(x_orig, sig_root, sigma, cond, uncond)
case PredictionType.X0:
raise RuntimeError("NRS.nrs: x0-prediction not supported yet.")
case PredictionType.UNKNOWN:
raise RuntimeError("NRS.nrs: Could not determine prediction type for this operation.")
case _:
raise RuntimeError("NRS.nrs: Invalid PredictionType used.")
x_final = None
match "v0.5.0":
match "v0.6.0":
case "v1":
# displace cond by rejection of uncond on cond
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_on_c = (u_dot_c / c_dot_c) * eps_cond
u_rej_c = eps_uncond - u_on_c
displaced = (eps_cond - skew * u_rej_c)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c = (u_dot_c / c_dot_c) * nrs_cond
u_rej_c = nrs_uncond - u_on_c
displaced = (nrs_cond - skew * u_rej_c)
logging.debug(f"NRS.nrs: displaced")
# squash displaced vector towards len(cond) based on squash scale
@@ -149,18 +192,18 @@ class NRS:
logging.debug(f"NRS.nrs: squashed")
# stretch turned vector towards cond based on stretch scale
sq_dot_c = torch.sum(squashed * eps_cond, dim=-1, keepdim=True)
sq_on_c = (sq_dot_c / c_dot_c) * eps_cond
sq_dot_c = torch.sum(squashed * nrs_cond, dim=-1, keepdim=True)
sq_on_c = (sq_dot_c / c_dot_c) * nrs_cond
x_final = squashed + sq_on_c * stretch
logging.debug(f"NRS.nrs: final")
case "v2":
# displace cond by rejection of uncond on cond
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c_mag = (u_dot_c / c_dot_c)
u_on_c = u_on_c_mag * eps_cond
u_rej_c = eps_uncond - u_on_c
displaced = eps_cond + stretch * (eps_cond - torch.clamp(u_dot_c / c_dot_c, min=0, max=1) * eps_cond) - skew * u_rej_c
u_on_c = u_on_c_mag * nrs_cond
u_rej_c = nrs_uncond - u_on_c
displaced = nrs_cond + stretch * (nrs_cond - torch.clamp(u_dot_c / c_dot_c, min=0, max=1) * nrs_cond) - skew * u_rej_c
logging.debug(f"NRS.nrs: displaced & stretched")
# squash displaced vector towards len(cond) based on squash scale
@@ -170,12 +213,12 @@ class NRS:
logging.debug(f"NRS.nrs: final")
case "v3":
# displace cond by rejection of uncond on cond
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c_mag = (u_dot_c / c_dot_c)
u_on_c = u_on_c_mag * eps_cond
u_rej_c = eps_uncond - u_on_c
displaced = (eps_cond - skew * u_rej_c)
u_on_c = u_on_c_mag * nrs_cond
u_rej_c = nrs_uncond - u_on_c
displaced = (nrs_cond - skew * u_rej_c)
logging.debug(f"NRS.nrs: displaced")
# squash displaced vector towards len(cond) based on squash scale
@@ -189,81 +232,81 @@ class NRS:
x_final = displaced * squash_scale * stretch_scale
logging.debug(f"NRS.nrs: final")
case "v4":
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c_mag = (u_dot_c / c_dot_c)
u_on_c = u_on_c_mag * eps_cond
u_rej_c = eps_uncond - u_on_c
u_on_c = u_on_c_mag * nrs_cond
u_rej_c = nrs_uncond - u_on_c
rej_dor_rej = torch.sum(u_rej_c * u_rej_c, dim=-1, keepdim=True)
x_final = (eps_cond - squash * u_rej_c + stretch * eps_cond * ((rej_dor_rej/c_dot_c) ** 0.5))
x_final = (nrs_cond - squash * u_rej_c + stretch * nrs_cond * ((rej_dor_rej/c_dot_c) ** 0.5))
logging.debug(f"NRS.nrs: displaced")
case "v0.4.1":
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c_mag = (u_dot_c / c_dot_c)
u_on_c = u_on_c_mag * eps_cond
u_rej_c = eps_uncond - u_on_c
u_on_c = u_on_c_mag * nrs_cond
u_rej_c = nrs_uncond - u_on_c
rej_dor_rej = torch.sum(u_rej_c * u_rej_c, dim=-1, keepdim=True)
stretched = eps_cond + stretch * eps_cond * ((rej_dor_rej/c_dot_c) ** 0.5)
stretched = nrs_cond + stretch * nrs_cond * ((rej_dor_rej/c_dot_c) ** 0.5)
skewed = stretched - skew * u_rej_c
sk_dot_sk = torch.sum(skewed * skewed, dim=-1, keepdim=True)
squash_scale = (1 - squash) + squash * ((c_dot_c/sk_dot_sk) ** 0.5)
x_final = skewed * squash_scale
logging.debug(f"NRS.nrs: displaced")
case "v0.4.2":
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c_mag = (u_dot_c / c_dot_c)
u_on_c = u_on_c_mag * eps_cond
u_rej_c = eps_uncond - u_on_c
u_on_c = u_on_c_mag * nrs_cond
u_rej_c = nrs_uncond - u_on_c
proj_len = torch.sum(u_on_c * u_on_c, dim=-1, keepdim=True) ** 0.5
cond_len = c_dot_c ** 0.5
stretched = eps_cond * (1 + stretch * torch.abs(cond_len - proj_len) / cond_len)
stretched = nrs_cond * (1 + stretch * torch.abs(cond_len - proj_len) / cond_len)
skewed = stretched - skew * u_rej_c
sk_dot_sk = torch.sum(skewed * skewed, dim=-1, keepdim=True)
squash_scale = (1 - squash) + squash * cond_len / (sk_dot_sk ** 0.5)
x_final = skewed * squash_scale
logging.debug(f"NRS.nrs: displaced")
case "v0.4.3":
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c_mag = (u_dot_c / c_dot_c)
u_on_c = u_on_c_mag * eps_cond
u_rej_c = eps_uncond - u_on_c
u_on_c = u_on_c_mag * nrs_cond
u_rej_c = nrs_uncond - u_on_c
proj_len = torch.sum(u_on_c * u_on_c, dim=-1, keepdim=True) ** 0.5
cond_len = c_dot_c ** 0.5
stretched = eps_cond * (1 + stretch * (cond_len - proj_len) / cond_len)
stretched = nrs_cond * (1 + stretch * (cond_len - proj_len) / cond_len)
skewed = stretched - skew * u_rej_c
sk_dot_sk = torch.sum(skewed * skewed, dim=-1, keepdim=True)
squash_scale = (1 - squash) + squash * cond_len / (sk_dot_sk ** 0.5)
x_final = skewed * squash_scale
logging.debug(f"NRS.nrs: displaced")
case "v0.4.4":
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c_mag = (u_dot_c / c_dot_c)
u_on_c = u_on_c_mag * eps_cond
u_rej_c = eps_uncond - u_on_c
u_on_c = u_on_c_mag * nrs_cond
u_rej_c = nrs_uncond - u_on_c
cond_len = c_dot_c ** 0.5
proj_diff = eps_cond - u_on_c
proj_diff = nrs_cond - u_on_c
proj_diff_len = torch.sum(proj_diff * proj_diff, dim=-1, keepdim=True) ** 0.5
stretched = eps_cond * (1 + stretch * proj_diff_len / cond_len)
stretched = nrs_cond * (1 + stretch * proj_diff_len / cond_len)
skewed = stretched - skew * u_rej_c
sk_dot_sk = torch.sum(skewed * skewed, dim=-1, keepdim=True)
squash_scale = (1 - squash) + squash * cond_len / (sk_dot_sk ** 0.5)
x_final = skewed * squash_scale
logging.debug(f"NRS.nrs: displaced")
case "v0.4.5":
u_dot_c = torch.sum(eps_uncond * eps_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(eps_cond * eps_cond, dim=-1, keepdim=True)
u_dot_c = torch.sum(nrs_uncond * nrs_cond, dim=-1, keepdim=True)
c_dot_c = torch.sum(nrs_cond * nrs_cond, dim=-1, keepdim=True)
u_on_c_mag = (u_dot_c / c_dot_c)
u_on_c = u_on_c_mag * eps_cond
u_rej_c = eps_uncond - u_on_c
u_on_c = u_on_c_mag * nrs_cond
u_rej_c = nrs_uncond - u_on_c
cond_len = c_dot_c ** 0.5
proj_diff = eps_cond - u_on_c
proj_diff = nrs_cond - u_on_c
# Amplify Cond based on length compared to projection of uncond
stretched = eps_cond + (stretch * proj_diff)
stretched = nrs_cond + (stretch * proj_diff)
# Skew/Steer Conf based on rejection of uncond on cond
skewed = stretched - skew * u_rej_c
@@ -274,22 +317,23 @@ class NRS:
x_final = skewed * squash_scale
case "v0.5.0":
def _dot(a, b):
return (a*b).flatten(1).sum(dim=1, keepdim=True) # [B,C,W,H] => [B,1]
return (a*b).flatten(2).sum(dim=2, keepdim=True) # [B,C,W,H] => [B,C,1]
def _nrm2(v):
return _dot(v, v)
eps = torch.finfo(eps_cond.dtype).eps
c_dot_c = _nrm2(eps_cond) + eps # [B,1]
u_dot_c = _dot(eps_uncond, eps_cond) # [B,1]
eps = torch.finfo(nrs_cond.dtype).eps
c_dot_c = _nrm2(nrs_cond) + eps # [B,1]
u_dot_c = _dot(nrs_uncond, nrs_cond) # [B,1]
u_on_c = (u_dot_c / c_dot_c).view(-1, 1, 1, 1) * eps_cond # [B,1,1,1] * [B,C,H,W]
u_on_c = (u_dot_c / c_dot_c).unsqueeze(-1) * nrs_cond # [B,1,1,1] * [B,C,H,W]
# Amplify Cond based on length compared to projection of uncond
proj_diff = eps_cond - u_on_c
stretched = eps_cond + (stretch * proj_diff)
proj_diff = nrs_cond - u_on_c
stretched = nrs_cond + (stretch * proj_diff)
# Skew/Steer Conf based on rejection of uncond on cond
u_rej_c = eps_uncond - u_on_c
u_rej_c = nrs_uncond - u_on_c
skewed = stretched - (skew * u_rej_c)
# Squash final length back down to original length of cond
@@ -297,9 +341,46 @@ class NRS:
nrs_len = torch.sqrt(_nrm2(skewed)) + eps # [B,1]
squash_scale = (1 - squash) + (squash * (cond_len / nrs_len))
x_final = skewed * squash_scale.view(-1, 1, 1, 1)
x_final = skewed * squash_scale.unsqueeze(-1)
case "v0.6.0":
def _dot(a, b):
return (a*b).sum(dim=1, keepdim=True) # [B,C,W,H] => [B,1,W,H]
return self._post_scale_conditioning(x_orig, x_div, x_final, sigma)
def _nrm2(v):
return _dot(v, v)
eps = torch.finfo(nrs_cond.dtype).eps
c_dot_c = _nrm2(nrs_cond) + eps # [B,1]
u_dot_c = _dot(nrs_uncond, nrs_cond) # [B,1]
u_on_c = (u_dot_c / c_dot_c) * nrs_cond # [B,1,1,1] * [B,C,H,W]
# Amplify Cond based on length compared to projection of uncond
proj_diff = nrs_cond - u_on_c
stretched = nrs_cond + (stretch * proj_diff)
# Skew/Steer Conf based on rejection of uncond on cond
u_rej_c = nrs_uncond - u_on_c
skewed = stretched - (skew * u_rej_c)
# Squash final length back down to original length of cond
cond_len = cond.norm(dim=1, keepdim=True)
nrs_len = skewed.norm(dim=1, keepdim=True)
squash_scale = (1 - squash) + (squash * (cond_len / nrs_len))
x_final = skewed * squash_scale
match self.__OPERATION_SPACE:
case PredictionType.V:
return self._finalize_from_v_space(x_orig, x_div, x_final, sig_root, sigma)
case PredictionType.EPS:
return self._finalize_from_eps_space(x_orig, x_div, x_final, sig_root, sigma)
case PredictionType.X0:
raise RuntimeError("NRS.nrs: x0-prediction not supported yet.")
case PredictionType.UNKNOWN:
raise RuntimeError("NRS.nrs: Could not determine prediction type for this operation.")
case _:
raise RuntimeError("NRS.nrs: Invalid PredictionType used.")
m = model.clone()
m.set_model_sampler_cfg_function(nrs, True)
+52 -20
View File
@@ -6,39 +6,71 @@ NRS seeks to replace the 'naive' linear interpolation of Classifier Free Guidanc
2. NRS replaces CFG with 3 new knobs.
3. NRS lets you to create cooler outputs than CFG.
> [!TIP]
> Skip to the [Beginner How-To](#beginner-how-to) if you want to just get started.
### Math Demonstration
<details>
<summary>Expand for explanation of algorithm</summary>
<img align="right" src="https://github.com/user-attachments/assets/01fabaff-8499-45f6-adad-d54b2c2fb7f1" alt="Graph of NRS vs CFG" style="width: 40%; float: right;">
<img align="right" src="Examples/NRS_graph.png" alt="Graph of NRS vs CFG" style="width: 40%; float: right;">
### NRS is Applied in Three Steps:
1. **Skewing**: The conditioned output tensor is skewed away from the direction of the rejection of the unconditioned tensor on the conditioned tensor. This lengthens the tensor in a direction perpendicular to its direction without affecting the positive guidance. The tensor is displaced by the rejection multiplied by the Skew parameter.
2. **Stretching**: The skewed tensor is stretched towards the direction of the original conditioned tensor based on its difference from the projection of uncond on cond. The stretch is multiplied by the Stretch parameter.
3. **Squashing**: The skewed and stretched tensor is rescaled towards the original length of the conditioned tensor. 100% squashing outputs the original length of the conditioned tensor simply 'steered' towards the skewed & squashed version's direction.
0. ***V-Space**: Optional pre-NRS step* If the model is not using v-prediction, we transform the EPS `cond` and `uncond` into v-prediction space before continuing, then revert to eps-space before return.
1. **Skewing**: The conditioned output tensor is skewed away from the direction of the rejection of the unconditioned tensor on the conditioned tensor. This lengthens the tensor in a direction perpendicular to its direction without affecting the positive guidance. The tensor is displaced by the rejection multiplied by the Skew parameter.[^1]
2. **Stretching**: The skewed tensor is stretched towards the direction of the original conditioned tensor based on its difference from the projection of uncond on cond. The stretch is multiplied by the Stretch parameter.[^1]
3. **Squashing**: The skewed and stretched tensor is rescaled towards the original length of the conditioned tensor. 100% squashing outputs the original length of the conditioned tensor simply 'steered' towards the skewed & squashed version's direction.[^1]
[^1]: All operations are done per feature across the step's batch, width, and height.
[Interactive Graph on Math3D.org](https://www.math3d.org/aTJW4UZtCh)
</details>
## Parameters
Skew and Stretch are roughly similar to CFG, but decomposed, with `Stretch + 2 * Skew = 2 * CFG`, roughly.
Meaning, if you want to 'replicate' a simliar effect for a given CFG setting, you should set Skew equal to CFG, and Stretch to 1/2 CFG.
Squash should initially be set to 0%, then adjusted based on 'burn' of output.
## Examples of NRS Effects
**Skew**
![Skew Example](Examples/skew_array.png)
**Stretch**
![Stretch Example](Examples/stretch_array.png)
**Squash**
![Squash Example](Examples/squash_matrix.png)
<details>
<summary><small>Generation details for reproduction</small></summary>
- **Skew** changes the 'direction' of generation, which should result in changes to the content and composition of the image.
- **Stretch** changes to 'amplification' of generation, which should result in stronger prompt representation.
- **Squash** 'normalizes' the resulting guidance back towards the original amplitude. This results in a removal of 'burn-in' and artifacting of the output, transforming these defects into alternative guidance.
| Prompt | |
| ---------- | --- |
| Tool | [Stable Diffusion WebUI reForge](https://github.com/Panchovix/stable-diffusion-webui-reForge) |
| Sampler | DPM++ 2M |
| Scheduler | Align Your Steps |
| Steps | 25 |
| Dimensions | 912 x 624 |
| Seed | `1334103348` |
| Model | [Lobotomized Mix v1.5](https://civitai.com/models/1144932) |
| Embeddings | [Lazy Embeddings for ALL illustrious NoobAI...](https://civitai.com/models/1302719), [Smooth Embeddings](https://civitai.com/models/1065154) |
| Positive | lazypos, [Smooth_Quality\|SmoothNoob_Quality], BREAK<br>very awa, masterpiece, best quality, year 2024, newest, highres, absurdres,<br>1girl, samurai archer, cyberpunk cityscape, rain-soaked rooftop, neon reflection puddles, volumetric mist,<br>photorealistic, digital art,<br>dramatic rim lighting, shallow depth of field, low angle viewpoint |
| Negative | lazyloli, lazynsfw, BREAK<br>lazyhand, SmoothNegative_Hands-neg, BREAK<br>[Smooth_Negative-neg\|SmoothNoob_Negative-neg], BREAK<br>lowres, worst quality, worst aesthetic, bad quality, jpeg artifacts, scan artifacts,<br>blurry, deformed anatomy, bad hands, extra fingers, missing fingers, mutated hands,<br>watermark, logo, text, nsfw |
</details>
### Explanation of Effects
#### Skew
**Skew** changes the 'direction' of your generation, altering the image generation to 'steer' away from negative prompt elements as they conflict with your positive prompt. Increasing Skew will change scene composition, geometry, and scene elements to ensure that the final image aligns with the intention of your prompt pair.
#### Stretch
**Stretch** changes the intensity of generated elements that align more with your positive prompt than the negative. This 'hits the gas' on any elements that are more strongly aligned with your positive prompt than your negative, and 'hit the brakes' on the opposite.
#### Squash
**Squash** is the speed limit. At 0.0 Squash, each diffusion step receives the full intensity you set from Skew and Stretch, while 1.0 Squash ensures each step has only the original step size output by the model. This setting has no effect unless you have a non-zero Skew value. Squash will 'soften' the effects of Skew and Stretch as it's raised, but the 'removed' Skew and Stretch intensity is replaced by enhanced micro-detailing and 'burn'. Squash should generally be left low and used as a 'finishing' step after dialing in a decent Skew and Stretch value.
## Beginner How-To
1. Set Skew to your normal CFG Scale setting and Stretch to 1/2 your normal CFG Scale.
2. Set Squash to 0.0.
3. Test some outputs. Results should be similar in quality to CFG.
4. Adjust Skew up/down to change content and composition.
5. Adjust Stretch up/down to change strength of positive prompt aspects and colors.
6. Adjust Squash up to remove artifacts and color burn (these will tend to be replaced by additional details and elements).
1. Set Skew to your normal CFG Scale setting and Stretch to 1/2 your normal CFG Scale. Set Squash to 0.0.<br>
*Alternatively, try starting at 1/1/0.0 to get a baseline.*
2. Test some outputs. Results should be similar in quality to CFG.
3. Adjust Skew to change the intensity of your outputs adherence to your positive and negative prompts. This primarily effects composition of the output.
4. Adjust Stretch to intensify your positive prompt's aspects and colors where they differ from the negative prompt. This primarily effects color and texture.
5. Adjust Squash to soften Skew and Stretch's effects. The intensity removed from Skew and Stretch will generally become additional micro-detailing and elements.
**Tip**: You can experiment with negative values for Skew and Stretch as well, to see how the model is interpeting your negative prompt.
> [!TIP]
> You can experiment with negative values for each setting as well. This can be useful to understand how the model interpreting your negative prompt.
## Examples
> [!WARNING]
> Don't set NRS values to negatives if there are things in your negative prompt you **actually** don't want to see.
## Submitted User Examples
| User | CFG | NRS |
|---|---|---|
| --- | --- | --- |
| Mohnjiles from StabilityMatrix | ![CFG Example](Examples/mohnjiles_cfg.png) | ![NRS Example](Examples/mohnjiles_nrs.png) |
+2 -1
View File
@@ -4,7 +4,8 @@
This is the primary 'steering' knob. This will 'turn' the 'direction' the current denoising step is traveling in the latent space. If we define the 'default' (cond) direction as 'prior step -> cond' then we're just applying a 'lateral' skew to that direction to 'turn' it 'away' from the 'unintended' direction (uncond)
## STRETCH
This is the sister knob to Skew. This is the accelerator. We want to go 'faster' into the intended direction (cond) the less aligned it is with the unintended direction (uncond). Think of this like a combination of brakes + gas. If we're headed directly for a brick wall (uncond is in the same direction as cond), we want to apply no acceleration, or negative acceleration. If we're traveling directly away from danger (uncond is in the opposite direction of cond) then we want to stomp the gas and get as far away as we can. There's only 1 problem with this BASIC-level description: as we get further into generation, regardless of pos/neg promp, cond & uncon will naturally align to be the same vector. In the last stop of inference, cond and uncond will be basically identical if nothing has fucked up. So whatever math we apply here needs to take the progressive alignment of cond & uncond into account. That's why were/are scaling only on the projection difference right now, rather than the full projection.
This is the sister knob to Skew. This is the accelerator. We want to go 'faster' into the intended direction (cond) the less aligned it is with the unintended direction (uncond). Think of this like a combination of brakes + gas. If we're headed directly for a brick wall (uncond is in the same direction as cond), we want to apply no acceleration, or negative acceleration. If we're traveling directly away from danger (uncond is in the opposite direction of cond) then we want to stomp the gas and get as far away as we can. There's only 1 problem with this BASIC-level description: as we get further into generation, regardless of pos/neg promp, cond & uncon will naturally align to be the same vector[^1]. In the last stop of inference, cond and uncond will be basically identical if nothing has fucked up. So whatever math we apply here needs to take the progressive alignment of cond & uncond into account. That's why were/are scaling only on the projection difference right now, rather than the full projection.
[^1]: This is more true in eps than v-pred. Stretch is inherently more powerful in v-pred based models than eps models.
## SQUASH
This is out 'safety' knob. Think of this like a 'limiter' in a car. This sets the 'top speed' we can go to some multiple of the 'default' speed the model would 'like to' go. i.e. whatever length of directional vector the model produces prior to any skewing or stretching is treated as the 'default' length with Squash=1.0 ensuring we only every go that 'speed' and no more, while Squash=0.0 lets us go any speed we want based on the other 2 knobs. GENERALLY we'll be leaving Squash at 0.0 unless we need it for specific generations.