11 Commits
Author SHA1 Message Date
blepping e36623a5f1 Add round and step to node FLOAT inputs that did not have it 2025-01-30 06:41:34 -07:00
blepping ca3ee58750 Internal cleanups and refactoring.
Some integration improvements.
Bump date in changelog
2025-01-30 06:10:36 -07:00
blepping a31eb6940b Better approach to integration with external nodes
Documentation updates
Other cleanups
2024-12-22 10:36:23 -07:00
blepping 3222b02318 Momentum sampler refactor/improvements (I hope) 2024-12-12 15:16:42 -07:00
blepping dcfea85e9c Add SonarResizedNoise node 2024-12-12 11:39:14 -07:00
blepping 3ba9f2e3d1 More distributions! 2024-12-11 17:57:30 -07:00
blepping b5be44720c Distro noise improvements, add SonarAdvancedDistroNoise node 2024-12-11 11:14:48 -07:00
blepping 30b37e98c2 Generalized distribution noise for most torch.distributions 2024-12-09 21:16:35 -07:00
blepping a951ad7392 Fix Brownian arg passing 2024-12-06 09:25:05 -07:00
blepping 27126d9f93 Add WaveletFilteredNoise node, other fixes 2024-12-05 15:41:15 -07:00
blepping 7365a9f30b Refactor noise generation
Try to make option passing and CPU/GPU noise selection work
Add advanced custom noise node that allows for parameter passing
Add wavelet noise type
2024-12-05 13:17:27 -07:00
27 changed files with 3376 additions and 10057 deletions
-2
View File
@@ -25,7 +25,6 @@ composite and otherwise manipulate noise see:
* [Advanced Power Noise](docs/advanced_power_noise.md) - examples and descriptions of the advanced power noise node. * [Advanced Power Noise](docs/advanced_power_noise.md) - examples and descriptions of the advanced power noise node.
* [Advanced Noise Nodes](docs/advanced_noise_nodes.md) - examples and descriptions of advanced noise nodes (schedule, composite, etc). * [Advanced Noise Nodes](docs/advanced_noise_nodes.md) - examples and descriptions of advanced noise nodes (schedule, composite, etc).
* [FreeU Extreme](docs/frux.md) - a build your own FreeU kit that allows advanced filtering, blending, scheduling of effects as well as targetting input and middle blocks. * [FreeU Extreme](docs/frux.md) - a build your own FreeU kit that allows advanced filtering, blending, scheduling of effects as well as targetting input and middle blocks.
* [Wavelet CFG](docs/waveletcfg.md) - replacement CFG function that lets you set different CFG scales for high/low frequency parts of the latent. You can even do stuff like use a different CFG scale for horizontal versus vertical.
## Sonar Description ## Sonar Description
@@ -155,7 +154,6 @@ My version was initially based on this Sonar sampler implementation for Diffuser
* Original `SonarPowerNoise` contributed by [elias-gaeros](https://github.com/elias-gaeros/). Additionally, he provided a lot of guidance with refactoring it to allow separate filtering and other enhancements and answered a multitude of dumb questions. To say those changes are only co-authored is probably giving myself too much credit. Thank you! Your patience and help is very much appreciated. * Original `SonarPowerNoise` contributed by [elias-gaeros](https://github.com/elias-gaeros/). Additionally, he provided a lot of guidance with refactoring it to allow separate filtering and other enhancements and answered a multitude of dumb questions. To say those changes are only co-authored is probably giving myself too much credit. Thank you! Your patience and help is very much appreciated.
* New 1/f (onef) and power law (white, grey, violet, velvet) noise types referenced from https://github.com/WASasquatch/PowerNoiseSuite * New 1/f (onef) and power law (white, grey, violet, velvet) noise types referenced from https://github.com/WASasquatch/PowerNoiseSuite
* Wavelet noise idea (and some of the default settings) from https://github.com/ClownsharkBatwing/RES4LYF * Wavelet noise idea (and some of the default settings) from https://github.com/ClownsharkBatwing/RES4LYF
* Pattern break algorithm adapted from https://github.com/Extraltodeus/noise_latent_perlinpinpin
## Errata ## Errata
+9 -17
View File
@@ -1,23 +1,15 @@
import sys from .py import freeu_extreme, nodes, powernoise, sonar
from . import py # noqa: F401
from .py import nodes, sonar
def blep_init():
bi = sys.modules.get("_blepping_integrations", {})
if "sonar" in bi:
return
bi["sonar"] = sys.modules[__name__]
sys.modules["_blepping_integrations"] = bi
sonar.add_samplers() sonar.add_samplers()
blep_init()
NODE_CLASS_MAPPINGS = nodes.NODE_CLASS_MAPPINGS NODE_CLASS_MAPPINGS = nodes.NODE_CLASS_MAPPINGS | {
"SonarPowerNoise": powernoise.SonarPowerNoiseNode,
"SonarPowerFilterNoise": powernoise.SonarPowerFilterNoiseNode,
"SonarPowerFilter": powernoise.SonarPowerFilterNode,
"SonarPreviewFilter": powernoise.SonarPreviewFilterNode,
"FreeUExtremeConfig": freeu_extreme.FreeUExtremeConfigNode,
"FreeUExtreme": freeu_extreme.FreeUExtremeNode,
}
NODE_DISPLAY_NAME_MAPPINGS = nodes.NODE_DISPLAY_NAME_MAPPINGS NODE_DISPLAY_NAME_MAPPINGS = nodes.NODE_DISPLAY_NAME_MAPPINGS
NODE_DISPLAY_NAME_MAPPINGS = getattr(nodes, "NODE_DISPLAY_NAME_MAPPINGS", {})
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"] __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
-76
View File
@@ -2,82 +2,6 @@
Note, only relatively significant changes to user-visible functionality will be included here. Most recent changes at the top. Note, only relatively significant changes to user-visible functionality will be included here. Most recent changes at the top.
## 20250808
Aside from the `sigmoid` quantile mode change and `SonarShuffledNoise`, these changes should not break workflows. Let me know if you experience anything unusual.
* The `sigmoid` quantile norm mode was renamed to `sigmoid_keepsign` since that's what it was doing. There is a replacement `sigmoid` quantile norm mode that doesn't care about sign.
* Quantile normalization can now take a negative quantile to consider values closest to zero the "extremes". Note: Experimental feature that may not be implemented correctly/subject to change.
* `SonarShuffledNoise` node reworked. Unfortunately, this will break workflows. If anyone has a burning need for the old version, let me know and I can bring it back as a separate node. The new approach should be better in general though.
* Fixed momentum sampler init parameter passing.
* Added more Voronoi noise octave modes.
* Added replace_2pt/3pt (and variants) quantile norm result modes that use multiple replacement values.
## 20250805
Once again, large set of changes/internal reorganization which may break stuff. If you run into problems or experience anything weird, please create an issue.
* Added a `SonarResizedNoiseAdv` node that allows more control (and is more useful for models like ACE-Steps where you might want to deal with absolute sizes).
* Added a `SonarWaveletCFG` node which allows you use different CFG values for different frequencies.
* Added a `SonarCustomNoiseParameters` node that lets you set some parameters as well as override seed/device/dtype.
* Added `replace`, `replace_keepsign` and `replace_avoidsign` quantile norm modes.
* `SonarBlendedNoise` now has a `custom_noise_mask` input. When connected, it will generate noise with that, put it on a 0-1 scale and use that to control the blend.
* Added a `SonarAdvancedVoronoiNoise` node.
## 20250705
This is a large set of changes. Please let me know anything doesn't seem to be working properly.
* Reorganized the node structure. This is an internal change and shouldn't affect users but please let me know if you notice anything weird.
* Added a `SonarLatentOperationAdvanced` node which allows more control over when individual latent operations are active and their effects get blended.
* Added a `SonarSplitNoiseChain` node. Can be useful if you want to have an item in the chain be a blended.
* Added a `SonarLatentOperationNoise` node that can be used to inject noise. You can also use the guided noise node to turn a reference into "noise".
* Expanded the functionality of the `SonarWaveletFilteredNoise` node. You can now attach two custom noise inputs to use for the high/low frequency parts of the wavelet as well as blend the wavelets.
* Added a `SonarNormalizeNoiseToScale` node that lets you normalize noise to specific value ranges.
* Added a `SonarPerDimNoise` node that lets you do stuff like call a noise sampler once per batch item (can be useful for 3D Perlin noise).
* Fixed an issue where the normalization parameter wasn't respected. This may change seeds.
* Added a `SonarLatentOperationFilteredNoise` node that allows you to run noise through a `LATENT_OPERATION`.
* Added a `SonarLatentOperationSetSeed` node that can be used to set the seed (mainly useful for running latent operations that add noise outside of sampling).
* Added a `SonarScatternetFilteredNoise` node that uses a scatternet to filter noise. Similar to wavelet filtering. Note: Very experimental, way not work properly.
* Fixed an issue with pattern break noise, this may change seeds for workflows using that noise type.
## 20250627
* Added `SonarRippleFilteredNoise` node.
* Added `SonarApplyLatentOperationCFG` node, similar to the built-in `ApplyLatentOperationCFG` node with scheduling and a lot of different application modes.
* Added a `SonarLatentOperationQuantileFilter` node that can be used to apply the quantile normalization functioen to the latent during sampling.
* A bunch more quantile normalization modes.
* Fixed broken quantile normalization dimension handling. Unfortunately this will likely change seeds.
## 20250612
* Reimplemented Collatz noise with many new features. Unfortunately this breaks existing workflows. If anyone misses the old version, let me know and I can add it back in (might do that anyway).
* Added actual wavelet noise based on https://en.wikipedia.org/wiki/Wavelet_noise .
* Added `reverse_zero`, `scale_down`, `tanh`, `tanh_outliers`, `sigmoid` and `sigmoid_outliers` quantile normalization limit modes.
## 20250602
* Fixed broken calculation for Collatz noise.
* Added `SonarPatternBreakNoise` node that allows breaking patterns in the noise.
* Added `SonarShuffledNoise` node that allows shuffling elements along user-specified dimensions.
* Added a strategy option to the `SonarQuantileFilteredNoise` node.
* Added variants to Collatz noise. Variant one is maybe similar to the original iteration.
* Added `SonarNoiseImage` node that allows generating noisy images or adding noise to existing images.
## 20250528
* Added `override_sigma`, `override_sigma_next`, `override_sigma_min` and `override_sigma_max` options that can be set in the `SonarCustomNoiseAdv` node YAML options. This enables using noise generators that require a sigma in stuff like initial noise (for example, Brownian). You will need to manually find and set the correct values yourself.
* Added Collatz noise based on the Collatz conjecture. Very experimental, very slow, likely to change and quite possibly just plain bad. But you can try it.
## 20250505
* Added `SonarQuantileFilteredNoise` node.
* Better compatibility with older Python versions.
## 20250227
* Add 5D latent (video models) support for most custom noise types.
## 20250130 ## 20250130
*Note*: May change seeds. *Note*: May change seeds.
-62
View File
@@ -156,12 +156,6 @@ yh_scales: null
*** ***
## `SonarQuantileFilteredNoise`
Allows quantile normalizing of arbitrary noise generators, works like the `SonarAdvancedDistroNoise` node (see below).
***
### `SonarAdvancedDistroNoise` ### `SonarAdvancedDistroNoise`
See: https://pytorch.org/docs/stable/distributions.html See: https://pytorch.org/docs/stable/distributions.html
@@ -448,59 +442,3 @@ Only provided if [ComfyUI-bleh](https://github.com/blepping/ComfyUI-bleh) is ava
``` ```
to flip the sign on the noise and then roll dimension -2 (height) by 50%. to flip the sign on the noise and then roll dimension -2 (height) by 50%.
### `SonarAdvancedVoronoiNoise`
This node can create multi-octave 3D Voronoi noise (also known as Worley noise). See: https://en.wikipedia.org/wiki/Worley_noise
Similar to Pyramid and other weird noise types, this noise generally will require mixing with something more normal. The default settings actually just about work with SDXL.
The node has many options for calculating the distance between the feature points and for processing the output. The modes are entered as a string, you can hover over the widget to get a brief list of possible modes. Both distance and result modes support some common features:
* You can enter a comma-separated list of modes. This allows using a different mode per octave. If there are more octaves than you have modes defined, the mode will wrap. In other words, if you're generating three octaves and you define two modes then the third octave will use the first mode you defined.
* You can enter a `+` (plus symbol) separated list of modes. The modes will be calculated and the result will be the average. Distance modes all have the common parameter `dscale` which defaults to 1 and can be overridden. Result modes use `rscale`. See below for a description on passing parameters.
* It's possible to pass parameters to distance and result modes. Example with a result mode: `diff:idx1=0:idx2=1:rscale=0.5`
Some modes act as wrappers to other modes. All modes will just ignore parameters they don't understand. Each time a submode is called, one level of "_" at the beginning of parameter names is stripped off. It's not user-friendly but this does allow passing parameters to submodes. Since unknown parameters are ignored, you only need to bother with this if the mode that's calling the submode will use that parameter. Dumb example: `gradient_magnitude:name1=diff:name2=gradient_magnitude:_name1=f4:_name2=f4`. `gradient_magnitude` takes two submodes that it calls (specified with `name1` and `name2`). The top-level `gradient_magnitude` will consume the `name1` and `name2` parameters, strip one level of underscores off the parameter names and call the submodes.
#### Distance Modes
Modes listed with the defaults for parameters they support. These modes also support `dscale` which defaults to 1 and can be used to manually adjust the scale of the mode result.
* `euclidean`
* `manhatten`
* `chebyshev`
* `minkowsi:p=3.0`
* `quadratic`
* `angle:idx=2` - idxs here range from 0 to 2.
* `angle_tanh:idx=2` - Same as `angle` but scales the result with tanh.
* `angle_sigmoid:idx=2` - Same as `angle` but scales the result with the sigmoid function.
* `fuzz:name=euclidean:fuzz=0.25` - Acts as a wrapper for another mode (specified with `name`). Will perturb the result by `fuzz` percent of the absolute maximum value. Or more simply, randomizes values by +/- `fuzz` percentage so if you set `fuzz=1` you will essentially get pure noise.
* `fractal_norm:scale=0.1:multiplier=10.0:mode=sin:name=euclidean` - This acts as a wrapper for another mode. `mode` may be one of `sin`, `cos`. It will adjust the input to the mode it wraps by `scale * sin(input * multiplier)` (assuming `mode=sin`).
* `weight:h=1.0:w=1.0:z=0.25:name=euclidean` - This acts as a wrapper for another mode and allows you to scale height/width/z (depth) before calling it.
#### Result Modes
Modes listed with the defaults for parameters they support. These modes also support `rscale` which defaults to 1 and can be used to manually adjust the scale of the mode result.
* `f1` - distance to the closest cell.
* `f2`, `f3`, `f4` - Same as `f1` but for the second closest, third closest, etc. Goes up to `f4`.
* `f:idx=0` - Allows specifying `f` modes over `f4`. Note that `idx` is zero-based so 0 corresponds to `f1`.
* `inv_f1` (through `inv_f4`). For `inv_f1`, the result is `1 / f1` (with a tiny value added to avoid divide by zero).
* `inv_f:idx=0` - Like the `f` mode using the formula described above.
* `diff:idx1=0:idx2=1` - Zero based indexes where 0 corresponds to `f1`, etc. For the default (`f1` and `f2`) the result is `f2 - f1`.
* `diff2:idx1=0:idx2=1` - Similar to `diff` described above, however the result is divided by the two `f` results (plus a tiny addition to avoid divide by zero). For example with the defaults this works out to `(f2 - f1) / (f2 + f1)`.
* `cellid` - Returns a discrete value for the area of each cell (diffusion models hate this). You will need to dilute the Voronoi noise a lot to actually use this. It could also possibly be used for masking.
* `median_distance`
* `fuzz:name=f1:fuzz=0.25` - Works the same as `fuzz` in distance modes. See the description there.
* `fractal_norm:scale=0.1:multiplier=10.0:mode=sin:name=diff` - This acts as a wrapper for another mode. `mode` may be one of `sin`, `cos`. It will adjust the input to the mode it wraps by `scale * sin(input * multiplier)` (assuming `mode=sin`).
* `ridge:name=diff:exp=-1.0` - Wraps another mode and may enhance cell borders (doesn't seem super useful).
* `softmin:temperature=50.0` - Passes the result through softmin and can be used to smooth the output from distance modes like `angle` that may experience abrupt changes as you move through `z`. It also supports a `use_sorted` parameter that will apply this adjustment to the sorted values as well if it's present and set to anything. Higher temperatures will result in less of a smoothing effect.
* `gradient_magnitude:name1=f4:name2=f4:padding_mode=replicate` - Wraps two other modes. Seems pretty nice for adding detail when using low numbers of feature points. `padding_mode` can be set to modes that PyTorch's `pad` function supports.
#### Depth
The node has several `z`-related parameters. `z` here refers to the depth dimension and will (currently) only apply if you're using the same noise sampler more than once. So generally not for initial noise, unless you're doing something unusual.
When `z_max` is set to 0 the feature points will be reset each time the noise sampler is called. Otherwise it will track the current `z` (depth) and increment it by whatever you specify each time the noise sampler is called. `SonarPerDimNoise` can be useful here if you want depth over dimensions like batch or channels.
-2
View File
@@ -18,8 +18,6 @@ noise of that type. However you can either schedule the noise type to kick in at
* `onef_pinkishgreenish` (50/50 mix of `onef_pinkish` and `onef_greenish`.) * `onef_pinkishgreenish` (50/50 mix of `onef_pinkish` and `onef_greenish`.)
* `velvet` * `velvet`
* `violet` * `violet`
* `voronoi_mix` - A mix of Voronoi (60%) and Gaussian noise types.
* `voronoi_fuzz` - Voronoi noise with distance mode `fuzz:name=angle_tanh:fuzz=0.1`.
* `white` * `white`
## Brownian ## Brownian
-241
View File
@@ -1,241 +0,0 @@
# Wavelet CFG
A CFG function that lets you use different CFG values for different frequencies.
Node: `SonarWaveletCFG`
## Requirements
You will need to have the `pytorch_wavelets` package installed in your Python environment to use this.
Link: https://github.com/fbcotter/pytorch_wavelets
## YAML crash course
You can skip past this if you already know YAML. Since wavelet CFG definitions are defined with YAML rules,
I am putting this section near the beginning.
First, JSON is valid YAML, so if you know JSON you can use that if you prefer. Since JSON is valid YAML, this also means the structure of YAML documents is the same as a JSON document.
YAML looks like this:
```yaml
# Comments start with the hash symbol.
# YAML will guess the type if you don't do stuff like quote strings, so the item below
# will be "value".
key1_name: value
# The value of a key can also be a set of keys (usually called an object)
# YAML uses indentation to control block grouping.
key2_name:
# A comment
subkey1_name: 123
# A list of three items, two integers and a string.
some_list: [1, 2, "hello"]
# You can also specify lists like this:
some_other_list:
- 1
- 2
- hello
# It's legal to specify the same key multiple times. This just overwrites
# whatever the previous value was.
subkey1_name: 345
```
YAML item types:
* String: `"hello there"` or `hello there` (you may need to quote when there are special characters).
* Integer: `123`
* Floating point value: `1.23`
* Object, may be specified in-line like JSON: `{ key: value, key: value }`. Be careful to separate the value from the colon after the key or it may be interpreted incorrectly. It may be a good idea to quote string values if you're using this syntax (and it's necessary if they have special characters or spaces).
* List, may be specified in-line like JSON: `[1, 2, "hello there"]`
* Null: `null`. If you want the string "null" then you'd need to quote it.
* Boolean: `true` and `false`.
#### Advanced YAML
YAML also has a number of advanced features like references. You can use this to avoid repeating the same information multiple times. For example:
```yaml
single_value: &single_ref_name [1, 2, 3]
# This is the same as other_value: [1, 2, 3]
other_value: *single_ref_name
# You can also do this with objects.
reference_block: &ref_name
key: value
other_key: other_value
whatever:
# This sets the "whatever" object to be the same as "reference_block"
# Note that you can't just do "whatever: *ref_name" to get that effect here.
<<: *ref_name
# And you can just overwrite the keys you want to change:
key: 123
# At this point, "whatever" is { key: 123, other_key: other_value }
```
## Usage
Unfortunately, this isn't very user-friendly and needs to be configured with YAML. This is a relatively basic description of
usage. To see all possible options, look at the default configuration definition in the node.
General information on wavelets from the library I'm using to do wavelet transforms: https://pytorch-wavelets.readthedocs.io/en/latest/index.html
Trimmed down, the default config looks like this:
```yaml
# This block is used to set the CFG scales.
diff:
# Scale for the low-frequency band.
yl_scale: 5.0
# Scale for the high-frequency bands.
yh_scales: 3.0
# Sets the wavelet type. DB4 is a good general-purpose wavelet to use.
wave: db4
# Sets the wavelet level.
level: 5
# Set to true if you want to get detailed information dumped to your console.
verbose: false
```
Wavelets decompose the value into a low frequency value and a set of high-frequency bands. The number of high-frequency
will be equal to the wavelet level, so in this example you will have one low-frequency band and five high-frequency
bands to work with. The high-frequency bands are further decomposed into three parts which can also be targeted
individually: horizontal, vertical, diagonal.
The `diff` (or `difference`, whichever you prefer) block is where you set the CFG scales. It's called `difference`
because CFG is defined as `uncond + (cond - uncond) * cfg_scale` (`cond` is the positive prompt, `uncond` is
negative). So CFG is just the difference between `cond` and `uncond`, multiplied by the CFG scale.
The example configuration here is using CFG 5 for the low frequency band and CFG 3 for the high frequency bands. It is
possible to get even more specific that that. Since we're using `level: 5` here, that means there are five frequency
bands that can all be set individually. The high-frequency bands are ordered from fine to coarse detail levels. Example:
```yaml
diff:
yl_scale: 5.0
# Can also be written: yh_scales: [5.0, 3.0, fill]
yh_scales:
# Highest/finest band.
- 5.0
# Decreasing order of detail/frequency.
- 3.0
- fill
```
The special value `fill` will just repeat the value before it to fill the rest of the bands. Note that if
you don't specify the bands or fill then the bands you don't set will use `1.0`. For example with five
bands, `[5.0, 3.0, fill]` is the same as `[5.0, 3.0, 3.0, 3.0, 3.0]` while `[5.0, 3.0]` is the same
as `[5.0, 3.0, 1.0, 1.0, 1.0]`. You can only use one `fill` per `yh_scales` definition.
As mentioned, it's also possible to target horizontal, vertical and diagonal bands. You can do this
by using a list instead of numeric value for a band definition. **Note**: You need to specify all
three bands, `fill` isn't valid here. Example:
```yaml
diff:
yl_scale: 5.0
# Can also be written: yh_scales: [5.0, 3.0, fill]
yh_scales:
- [3.0, 3.0, 5.0]
- 3.0
- fill
```
This example uses CFG 3.0 for horizontal and vertical in finest high-frequency band and CFG 5.0 for
diagonal. The remaining high-frequency bands use CFG 3.0.
## Scheduling CFG
It's also possible to transition from one set of CFG scales to another over time. The wavelet scales
block has an alternative definition format:
```yaml
diff:
# One of linear, logarithmic, exponential, half_cosine, sine
# Sine mode will hit the peak scales_after values in the middle of the range.
schedule: linear
# One of: sampling, enabled_sampling, sigmas, enabled_sigmas, step, enabled_steps
schedule_mode: enabled_sampling
# When enabled, flips the schedule percentage. This happens before the schedule is applied
# or any offset/multiplier stuff. If you want to flip the final result you can do something like
# schedule_offset_after: -1.0 and schedule_multiplier_after: -1.0
reverse_schedule: false
scales_start:
yl_scale: 5.0
yh_scales: 3.0
scales_end:
yl_scale: 2.0
yh_scales: 5.0
```
The way interpolating scales works is we determine a value between 0.0 and 1.0 based on `schedule` and
`schedule_mode` and then do linear interpolation (LERP) between the values in `scales_start` and `scales_end`.
LERP is just `value_1 * (1.0 - ratio) + value_2 * ratio` so when `ratio` is 1 you get 100% `value_2`,
when it's 0.5 you get half of each and when it's 0 you get 100% of `value_1`.
**Note**: If you have both `scales_start` and toplevel `yl_scale`/`yh_scales` definitions, the
scales in `scales_start` will take precedence.
#### `schedule`
Current schedule types: `linear`, `logarithmic`, `exponential`, `half_cosine`, `sine`
Linear just changes by the same amount over time, with the exception
of `sine`, the other possible values are similar except the change forms a curve (where it may be slow at first and then
accelerate or vice versa). Experiment with them to see what you prefer. `sine` has a somewhat different effect, the
percentage of `scales_end` will increase and peak in the middle of the range, then decrease.
#### `schedule_mode`
Current modes: `sampling`, `enabled_sampling`, `sigmas`, `enabled_sigmas`, `step`, `enabled_steps`
* `sampling`: Sampling is a percentage that starts at 0.0 and ends at 1.0 (assuming you're doing txt2img). This isn't really related
to the schedule or steps.
* `sigmas`: This calculates the difference between the starting sigma and ending sigma as a percentage.
* `step`: Not very well tested and may not work (especially with multi-step samplers). The percentage in this case is the percentage
steps
The `_enabled` variants calculate the percentage based on the range that wavelet CFG is enabled for (in other words,
the range betwmeen `start_sigma` and `end_sigma`). I'd suggest not using them as it's a lot easier to predict what values
will be used when the schedule start/end points aren't also changing.
***
In addition to the values described here, there are number of other advanced configuration options that can be used
to add/subtract and offset to the calculated percentage value, multiply it, etc. These advanced parameters can be
used to do stuff like speed up the transition between config values, keep them within a certain range with minimum/maximum
thresholds, etc. See the default YAML config definition in the node to see what is possible.
## Scheduling rules
Rules may be scheduled using this syntax:
```yaml
rules:
- start_sigma: -1.0
end_sigma: 5.0
diff:
yl_scale: 5.0
yh_scales: 3.0
- start_sigma: -1.0
end_sigma: 0.0
diff:
yl_scale: 2.0
yh_scales: 5.0
```
Values from the top-level are valid within a rule. The definitions from the node are added as the first rule,
so if you want to only configure stuff in a `rules` block you can just set the start sigma in the node to `0.0` (
which will never match). Rules are checked in order and the first matching one is used.
An alternative method of scheduling rules is to just chain multiple `SonarWaveletCFG` nodes. If you set the fallback
mode to `existing` it is also possible to blend the current result with the next matching one (or normal CFG as the
case may be).
+4 -11
View File
@@ -32,11 +32,8 @@ class Integrations:
return self.modules.get(key) return self.modules.get(key)
@staticmethod @staticmethod
def get_custom_node(module_name: str, key: str) -> ModuleType | None: def get_custom_node(name: str) -> ModuleType | None:
bi_module = sys.modules.get("_blepping_integrations", {}).get(key) module_key = f"custom_nodes.{name}"
if bi_module is not None:
return bi_module
module_key = f"custom_nodes.{module_name}"
with contextlib.suppress(StopIteration): with contextlib.suppress(StopIteration):
spec = importlib.util.find_spec(module_key) spec = importlib.util.find_spec(module_key)
if spec is None: if spec is None:
@@ -70,7 +67,7 @@ class Integrations:
return return
self.initialized = True self.initialized = True
for ih in self.handlers: for ih in self.handlers:
module = self.get_custom_node(ih.module_name, ih.key) module = self.get_custom_node(ih.module_name)
if module is None: if module is None:
continue continue
if ih.handler is not None: if ih.handler is not None:
@@ -120,11 +117,7 @@ class IntegratedNode(type):
def __new__(cls: type, name: str, bases: tuple, attrs: dict) -> object: def __new__(cls: type, name: str, bases: tuple, attrs: dict) -> object:
obj = type.__new__(cls, name, bases, attrs) obj = type.__new__(cls, name, bases, attrs)
if hasattr(obj, "INPUT_TYPES") and not getattr( if hasattr(obj, "INPUT_TYPES"):
obj.INPUT_TYPES,
"_NO_REPLACE",
False,
):
obj.INPUT_TYPES = partial(cls.wrap_INPUT_TYPES, obj.INPUT_TYPES) obj.INPUT_TYPES = partial(cls.wrap_INPUT_TYPES, obj.INPUT_TYPES)
return obj return obj
+187 -98
View File
@@ -2,8 +2,8 @@ from __future__ import annotations
import torch import torch
from .. import utils from . import utils
from .base import SonarInputTypes, SonarLazyInputTypes from .external import IntegratedNode
from .powernoise import PowerFilter from .powernoise import PowerFilter
@@ -29,81 +29,156 @@ def ffilter(x, pfilter, normalization_factor=1.0, cfg_idx=None, filter_cache=Non
return x_filt.to(x.dtype, non_blocking=True) return x_filt.to(x.dtype, non_blocking=True)
class FreeUExtremeConfigNode: class FreeUExtremeConfigNode(metaclass=IntegratedNode):
DESCRIPTION = "Allows setting configuration for FreeU Extreme." DESCRIPTION = "Allows setting configuration for FreeU Extreme."
RETURN_TYPES = ("FRUX_CONFIG",) RETURN_TYPES = ("FRUX_CONFIG",)
FUNCTION = "go" FUNCTION = "go"
CATEGORY = "model_patches" CATEGORY = "model_patches"
INPUT_TYPES = SonarLazyInputTypes( @classmethod
lambda: SonarInputTypes() def INPUT_TYPES(cls):
.req_bool_stage_1( return {
default=True, "required": {
tooltip="Controls whether this configuration applies to stage 1.", "stage_1": (
) "BOOLEAN",
.req_bool_stage_2( {
default=False, "default": True,
tooltip="Controls whether this configuration applies to stage 2.", "tooltip": "Controls whether this configuration applies to stage 1.",
) },
.req_bool_stage_3( ),
default=False, "stage_2": (
tooltip="Controls whether this configuration applies to stage 3.", "BOOLEAN",
) {
.req_field_target( "default": False,
("backbone", "skip", "both"), "tooltip": "Controls whether this configuration applies to stage 2.",
default="backbone", },
tooltip="Controls whether this filter applies to backbone or skip layers (or both).", ),
) "stage_3": (
.req_floatpct_start( "BOOLEAN",
default=0.0, {
tooltip="Start time as percentage of sampling this configuration applies to. Inclusive.", "default": False,
) "tooltip": "Controls whether this configuration applies to stage 3.",
.req_floatpct_end( },
default=1.0, ),
tooltip="End time as percentage of sampling this configuration applies to. Inclusive.", "target": (
) ("backbone", "skip", "both"),
.req_floatpct_slice( {
default=1.0, "tooltip": "Controls whether this filter applies to backbone or skip layers (or both).",
tooltip="Percentage of the layer the FreeU effect is applied to.", },
) ),
.req_floatpct_slice_offset( "start": (
default=0.0, "FLOAT",
tooltip="Offset as a percentage the layer is applied to. For example if slice is 0.25 and slice_offset is 0.25 then the filter will apply to the range 25% through 50%.", {
) "default": 0.0,
.req_float_filter_norm( "min": 0.0,
default=0.0, "max": 1.0,
min=-10.0, "step": 0.1,
max=10.0, "round": False,
tooltip="Normalization factor applied to the filter. 1.0 means 100% normalized.", "tooltip": "Start time as percentage of sampling this configuration applies to. Inclusive.",
) },
.req_float_scale( ),
default=1.0, "end": (
tooltip="Strength of the effects applied by this configuration.", "FLOAT",
) {
.req_float_blend( "default": 1.0,
default=1.0, "min": 0.0,
tooltip="Blends the filtered result based on the specified strength where 1.0 means 100% filtered.", "max": 1.0,
) "step": 0.1,
.req_selectblend_blend_mode( "round": False,
tooltip="Mode used when blending. Generally only has an effect when blend is set to values other than 0 or 1", "tooltip": "End time as percentage of sampling this configuration applies to. Inclusive.",
) },
.req_bool_hidden_mean( ),
default=True, "slice": (
tooltip="You can think of this as FreeU V2 mode.", "FLOAT",
) {
.req_bool_final( "default": 1.0,
default=True, "min": 0.0,
tooltip="When enabled, other configurations won't be considered if this one matched. Otherwise, multiple configurations/filter effects can be stacked.", "max": 1.0,
) "step": 0.1,
.opt_field_sonar_power_filter_opt( "round": False,
"SONAR_POWER_FILTER", "tooltip": "Percentage of the layer the FreeU effect is applied to.",
tooltip="Optionally attach a Power Filter here to set filtering parameters.", },
) ),
.opt_field_frux_config_opt( "slice_offset": (
"FRUX_CONFIG", "FLOAT",
tooltip="Optionally attach another configuration node here.", {
), "default": 0.0,
) "min": 0.0,
"max": 1.0,
"step": 0.1,
"round": False,
"tooltip": "Offset as a percentage the layer is applied to. For example if slice is 0.25 and slice_offset is 0.25 then the filter will apply to the range 25% through 50%.",
},
),
"filter_norm": (
"FLOAT",
{
"default": 0.0,
"min": -10.0,
"max": 10.0,
"step": 0.1,
"round": False,
"tooltip": "Normalization factor applied to the filter. 1.0 means 100% normalized.",
},
),
"scale": (
"FLOAT",
{
"default": 1,
"min": -100.0,
"max": 100.0,
"step": 0.1,
"round": False,
"tooltip": "Strength of the effects applied by this configuration.",
},
),
"blend": (
"FLOAT",
{
"default": 1.0,
"min": -10.0,
"max": 10.0,
"step": 0.1,
"round": False,
"tooltip": "Blends the filtered result based on the specified strength where 1.0 means 100% filtered.",
},
),
"blend_mode": (
tuple(utils.BLENDING_MODES.keys()),
{
"tooltip": "Mode used when blending. Generally only has an effect when blend is set to values other than 0 or 1",
},
),
"hidden_mean": (
"BOOLEAN",
{
"default": True,
"tooltip": "You can think of this as FreeU V2 mode.",
},
),
"final": (
"BOOLEAN",
{
"default": True,
"tooltip": "When enabled, other configurations won't be considered if this one matched. Otherwise, multiple configurations/filter effects can be stacked.",
},
),
},
"optional": {
"sonar_power_filter_opt": (
"SONAR_POWER_FILTER",
{
"tooltip": "Optionally attach a Power Filter here to set filtering parameters.",
},
),
"frux_config_opt": (
"FRUX_CONFIG",
{
"tooltip": "Optionally attach another configuration node here.",
},
),
},
}
@classmethod @classmethod
def go(cls, **kwargs: dict): def go(cls, **kwargs: dict):
@@ -255,31 +330,51 @@ class FreeUExtremeConfig:
return f"<FRUXConfig: {meh}>" return f"<FRUXConfig: {meh}>"
class FreeUExtremeNode: class FreeUExtremeNode(metaclass=IntegratedNode):
DESCRIPTION = "Main FreeU Extreme node. Allows patching a model with the FreeU (V2) effect with more control." DESCRIPTION = "Main FreeU Extreme node. Allows patching a model with the FreeU (V2) effect with more control."
RETURN_TYPES = ("MODEL",) RETURN_TYPES = ("MODEL",)
FUNCTION = "go" FUNCTION = "go"
CATEGORY = "model_patches" CATEGORY = "model_patches"
INPUT_TYPES = ( @classmethod
SonarInputTypes() def INPUT_TYPES(cls):
.req_model(tooltip="Model to patch.") return {
.req_bool_cpu_fft( "required": {
tooltip="Controls whether to perform FFT calculations on the CPU. May be necessary for some GPUs that don't have native support for FFT )operations at the cost of performance.", "model": (
) "MODEL",
.opt_field_input_config( {
"FRUX_CONFIG", "tooltip": "Model to patch.",
tooltip="Allows specifying configuration for input blocks.", },
) ),
.opt_field_middle_config( "cpu_fft": (
"FRUX_CONFIG", "BOOLEAN",
tooltip="Allows specifying configuration for middle blocks.", {
) "default": False,
.opt_field_output_config( "tooltip": "Controls whether to perform FFT calculations on the CPU. May be necessary for some GPUs that don't have native support for FFT operations at the cost of performance.",
"FRUX_CONFIG", },
tooltip="Allows specifying configuration for output blocks.", ),
) },
) "optional": {
"input_config": (
"FRUX_CONFIG",
{
"tooltip": "Allows specifying configuration for input blocks.",
},
),
"middle_config": (
"FRUX_CONFIG",
{
"tooltip": "Allows specifying configuration for middle blocks.",
},
),
"output_config": (
"FRUX_CONFIG",
{
"tooltip": "Allows specifying configuration for output blocks.",
},
),
},
}
@classmethod @classmethod
def go( def go(
@@ -332,9 +427,3 @@ class FreeUExtremeNode:
if ocfg: if ocfg:
m.set_model_output_block_patch(out_patch) m.set_model_output_block_patch(out_patch)
return (m,) return (m,)
NODE_CLASS_MAPPINGS = {
"FreeUExtremeConfig": FreeUExtremeConfigNode,
"FreeUExtreme": FreeUExtremeNode,
}
-209
View File
@@ -1,209 +0,0 @@
from __future__ import annotations
import math
import random
from typing import TYPE_CHECKING
import torch
from . import utils
if TYPE_CHECKING:
from types import Sequence
class SonarLatentOperation:
EXTENDED_LATENT_OPERATION = True
def __init__(
self,
*,
start_sigma: float = math.inf,
end_sigma: float = 0.0,
op=None,
):
self.start_sigma = start_sigma if start_sigma >= 0 else math.inf
self.end_sigma = end_sigma
self.op = op
def enabled(self, sigma: torch.Tensor | float | None = None) -> bool:
if isinstance(sigma, torch.Tensor):
sigma = sigma.detach().max().cpu().item()
return sigma is None or self.end_sigma <= sigma <= self.start_sigma
def call_op(
self,
t: torch.Tensor,
*args: list,
op=None,
**kwargs: dict,
) -> torch.Tensor:
if op is None:
op = self.op
if op is None:
return t
if not getattr(op, "EXTENDED_LATENT_OPERATION", False):
return op(latent=t)
return op(*args, latent=t, **kwargs)
def __call__(
self,
latent: torch.Tensor,
*,
sigma: torch.Tensor | float | None = None,
**kwargs: dict,
) -> torch.Tensor:
if not self.enabled(sigma=sigma):
return latent
return self.call_op(latent, sigma=sigma, **kwargs)
class SonarLatentOperationAdvanced(SonarLatentOperation):
def __init__(
self,
*,
blend_mode: str,
blend_strength: float,
input_multiplier: float,
output_multiplier: float,
difference_multiplier: float,
ops: Sequence,
op_alt=None,
**kwargs: dict,
) -> None:
super().__init__(**kwargs)
self.blend_function = utils.BLENDING_MODES[blend_mode]
self.blend_strength = blend_strength
self.input_multiplier = input_multiplier
self.output_multiplier = output_multiplier
self.difference_multiplier = difference_multiplier
self.op_alt = op_alt
self.ops = ops
def __call__(
self,
latent: torch.Tensor,
*,
sigma: torch.Tensor | float | None = None,
**kwargs: dict,
) -> torch.Tensor:
t = latent
enabled = self.enabled(sigma)
if not enabled:
return (
t
if self.op_alt is None
else self.call_op(t, sigma=sigma, op=self.op_alt, **kwargs)
)
output = t * self.input_multiplier if self.input_multiplier != 1.0 else t
for op in self.ops:
output = self.call_op(output, sigma=sigma, op=op, **kwargs)
diff = (
output * self.output_multiplier if self.output_multiplier == 1.0 else output
) - t
if self.difference_multiplier != 1.0:
diff *= self.difference_multiplier
return self.blend_function(t, diff, self.blend_strength)
class SonarLatentOperationNoise(SonarLatentOperation):
def __init__(
self,
*args: list,
custom_noise,
scale_to_sigma: bool = False,
cpu_noise: bool = False,
normalize: bool = True,
lazy_noise_sampler: bool = False,
**kwargs: dict,
):
super().__init__(*args, **kwargs)
self.custom_noise = custom_noise
self.normalize = normalize
self.scale_to_sigma = scale_to_sigma
self.cpu_noise = cpu_noise
self.lazy_noise_sampler = lazy_noise_sampler
self.noise_sampler = None
self.cache_id = None
def __call__(
self,
latent: torch.Tensor,
*,
sigma: torch.Tensor | float | None = None,
**kwargs: dict,
) -> torch.Tensor:
t = latent
enabled = self.enabled(sigma)
if not enabled:
return t
if isinstance(sigma, float):
sigma = t.new_full((1,), sigma)
make_ns = not self.lazy_noise_sampler or self.noise_sampler is None
sigma_min = sigma_max = sigma_next = None
sample_sigmas = (
kwargs.get("raw_args", {})
.get("model_options", {})
.get("transformer_options", {})
.get("sample_sigmas")
)
if sample_sigmas is not None and sigma is not None:
guessed_step = (sample_sigmas - sigma).abs().argmin().detach().item()
guessed_sigma = sample_sigmas[guessed_step].max().detach().item()
if guessed_sigma == sigma and guessed_step + 1 < len(sample_sigmas):
sigma_next = sample_sigmas[guessed_step + 1]
if self.lazy_noise_sampler and not make_ns:
cache_id = (
id(sample_sigmas) if isinstance(sample_sigmas, torch.Tensor) else None
)
make_ns = cache_id is None or cache_id != self.cache_id
self.cache_id = cache_id
if make_ns and sample_sigmas is not None:
sigmas_min = sample_sigmas[sample_sigmas > 0]
sigma_min = (
sigmas_min.min().detach().item() if torch.any(sigmas_min) else 0.0
)
del sigmas_min
sigma_max = sample_sigmas.max().detach().item()
ns = (
self.custom_noise.make_noise_sampler(
t,
sigma_min=sigma_min,
sigma_max=sigma_max,
normalized=self.normalize,
seed=torch.randint(1, 1 << 31, (), device="cpu").item(),
cpu=self.cpu_noise,
)
if make_ns
else self.noise_sampler
)
if make_ns and self.lazy_noise_sampler:
self.noise_sampler = ns
noise = ns(sigma, sigma if sigma_next is None else sigma_next)
if self.scale_to_sigma and sigma is not None:
noise *= sigma
noise += t
return noise
class SonarLatentOperationSetSeed(SonarLatentOperation):
def __init__(self, *args: list, seed: int, restore_rng_state: bool, **kwargs: dict):
super().__init__(*args, **kwargs)
self.seed = seed
self.restore_rng_state = restore_rng_state
def __call__(self, *args: list, **kwargs: dict) -> torch.Tensor:
if self.restore_rng_state:
pyrandst = random.getstate()
torchrandst = torch.random.get_rng_state()
else:
pyrandst = torchrandst = None
try:
torch.manual_seed(self.seed)
random.seed(self.seed)
result = super().__call__(*args, **kwargs)
finally:
if self.restore_rng_state:
torch.random.set_rng_state(torchrandst)
random.setstate(pyrandst)
return result
+2551
View File
File diff suppressed because it is too large Load Diff
-30
View File
@@ -1,30 +0,0 @@
from . import (
base,
freeu_extreme,
integrations,
latent_operations,
misc,
momentum_samplers,
noise_filters,
noise_types,
powernoise,
)
NODE_CLASS_MAPPINGS = {
"SonarCustomNoise": base.SonarCustomNoiseNode,
"SonarCustomNoiseAdv": base.SonarCustomNoiseAdvNode,
}
NODE_DISPLAY_NAME_MAPPINGS = {}
for nm in (
freeu_extreme,
integrations,
latent_operations,
misc,
momentum_samplers,
noise_filters,
noise_types,
powernoise,
):
NODE_CLASS_MAPPINGS |= getattr(nm, "NODE_CLASS_MAPPINGS", {})
NODE_DISPLAY_NAME_MAPPINGS |= getattr(nm, "NODE_DISPLAY_NAME_MAPPINGS", {})
-290
View File
@@ -1,290 +0,0 @@
from __future__ import annotations
import abc
from typing import Any
from .. import noise, utils
from ..external import MODULES, IntegratedNode
from .base_inputtypes import InputCollection, InputTypes, LazyInputTypes
try:
from comfy_execution import validation as comfy_validation
if not hasattr(comfy_validation, "validate_node_input"):
raise NotImplementedError # noqa: TRY301
HAVE_COMFY_UNION_TYPE = comfy_validation.validate_node_input("B", "A,B")
except (ImportError, NotImplementedError):
HAVE_COMFY_UNION_TYPE = False
except Exception as exc: # noqa: BLE001
HAVE_COMFY_UNION_TYPE = False
print(
f"** ComfyUI-sonar: Warning, caught unexpected exception trying to detect ComfyUI union type support. Disabling. Exception: {exc}",
)
NOISE_INPUT_TYPES = frozenset(("SONAR_CUSTOM_NOISE", "OCS_NOISE"))
if not HAVE_COMFY_UNION_TYPE:
class Wildcard(str): # noqa: FURB189
__slots__ = ("whitelist",)
@classmethod
def __new__(cls, s, *args: list, whitelist=None, **kwargs: dict):
result = super().__new__(s, *args, **kwargs)
result.whitelist = whitelist
return result
def __ne__(self, other):
return False if self.whitelist is None else other not in self.whitelist
WILDCARD_NOISE = Wildcard("*", whitelist=NOISE_INPUT_TYPES)
else:
WILDCARD_NOISE = ",".join(NOISE_INPUT_TYPES)
NOISE_INPUT_TYPES_HINT = (
f"The following input types are supported: {', '.join(NOISE_INPUT_TYPES)}"
)
class SonarInputCollection(InputCollection):
def __init__(self, *args: list, **kwargs: dict):
super().__init__(*args, **kwargs)
self._DELEGATE_KEYS = self._DELEGATE_KEYS | frozenset(( # noqa: PLR6104
"customnoise",
"floatpct",
"normalizetristate",
"selectblend",
"selectnoise",
"selectscalemode",
"yaml",
))
def yaml(
self,
name: str = "yaml_parameters",
*,
tooltip="Allows specifying custom parameters via YAML. Note: When specifying paramaters this way, there is generally not much error checking.",
placeholder="# YAML or JSON here",
dynamicPrompts=False, # noqa: N803
multiline=True,
**kwargs: dict,
):
return self.field(
name,
"STRING",
tooltip=tooltip,
placeholder=placeholder,
dynamicPrompts=dynamicPrompts,
multiline=multiline,
**kwargs,
)
def selectblend(
self,
name: str = "blend_mode",
*,
default="lerp",
insert_modes=(),
tooltip="Mode used for blending. If you have ComfyUI-bleh then you will have access to many more blend modes.",
**kwargs: dict,
) -> InputCollection:
if not MODULES.initialized:
raise RuntimeError(
"Attempt to get blending modes before integrations were initialized",
)
return self.field(
name,
(*insert_modes, *utils.BLENDING_MODES.keys()),
default=default,
tooltip=tooltip,
**kwargs,
)
def selectscalemode(
self,
name: str,
*,
default="nearest-exact",
insert_modes=(),
tooltip="Mode used for scaling. If you have ComfyUI-bleh then you will have access to many more scale modes.",
**kwargs: dict,
) -> InputCollection:
if not MODULES.initialized:
raise RuntimeError(
"Attempt to get scale modes before integrations were initialized",
)
return self.field(
name,
(*insert_modes, *utils.UPSCALE_METHODS),
default=default,
tooltip=tooltip,
**kwargs,
)
def selectnoise(
self,
name: str,
*,
default="gaussian",
insert_types=(),
tooltip="Sets the type of noise.",
**kwargs: dict,
) -> InputCollection:
return self.field(
name,
(*insert_types, *noise.NoiseType.get_names()),
default=default,
tooltip=tooltip,
**kwargs,
)
def customnoise(
self,
name: str,
add_hint: bool = True, # noqa: FBT001
tooltip="Allows connecting a custom noise chain.",
**kwargs: dict,
) -> InputCollection:
if add_hint:
tooltip = f"{tooltip}\n{NOISE_INPUT_TYPES_HINT}"
return self.field(name, WILDCARD_NOISE, tooltip=tooltip, **kwargs)
def normalizetristate(
self,
name: str,
*,
default="default",
tooltip="Controls whether noise is normalized to 1.0 strength.",
**kwargs: dict,
):
return self.field(
name,
("default", "forced", "disabled"),
default=default,
tooltip=tooltip,
**kwargs,
)
def floatpct(self, name: str, *, min=0.0, max=1.0, **kwargs: dict): # noqa: A002
return self.float(name=name, min=min, max=max, **kwargs)
class SonarInputTypes(InputTypes):
_NO_REPLACE = True
def __init__(self, *args: list, **kwargs: dict):
super().__init__(
*args,
collection_class=SonarInputCollection,
**kwargs,
)
class SonarLazyInputTypes(LazyInputTypes):
_NO_REPLACE = True
def __init__(self, *args: list, initializers=(MODULES.initialize,), **kwargs: dict):
super().__init__(
*args,
initializers=initializers,
**kwargs,
)
class SonarCustomNoiseNodeBase(metaclass=IntegratedNode):
DESCRIPTION = "A custom noise item."
RETURN_TYPES = ("SONAR_CUSTOM_NOISE",)
OUTPUT_TOOLTIPS = ("A custom noise chain.",)
CATEGORY = "advanced/noise"
FUNCTION = "go"
@abc.abstractmethod
def get_item_class(self):
raise NotImplementedError
INPUT_TYPES = SonarLazyInputTypes(
lambda *, include_rescale=True, include_chain=True: SonarInputTypes()
.req_float_factor(
default=1.0,
tooltip="Scaling factor for the generated noise of this type.",
)
.req_float_rescale(
_skip=not include_rescale,
default=0.0,
min=0.0,
tooltip="When non-zero, this custom noise item and other custom noise items items connected to it will have their factor scaled to add up to the specified rescale value. When set to 0, rescaling is disabled.",
)
.opt_customnoise_sonar_custom_noise_opt(
_skip=not include_chain,
tooltip="Optional input for more custom noise items.",
),
initializers=(),
)
def go(
self,
factor=1.0,
rescale=0.0,
sonar_custom_noise_opt=None,
**kwargs: dict[str, Any],
):
nis = (
sonar_custom_noise_opt.clone()
if sonar_custom_noise_opt
else noise.CustomNoiseChain()
)
if factor != 0:
nis.add(self.get_item_class()(factor, **kwargs))
return (nis if rescale == 0 else nis.rescaled(rescale),)
class NoiseChainInputTypes(SonarInputTypes):
def __init__(self, *, parent=SonarCustomNoiseNodeBase, **kwargs: dict):
super().__init__(parent=parent, **kwargs)
class NoiseNoChainInputTypes(SonarInputTypes):
def __init__(
self,
*,
parent=SonarCustomNoiseNodeBase,
parent_args=(),
parent_kwargs=None,
**kwargs: dict,
):
super().__init__(
parent=parent,
parent_args=parent_args,
parent_kwargs={"include_chain": False, "include_rescale": False}
| (parent_kwargs if parent_kwargs is not None else {}),
**kwargs,
)
class SonarCustomNoiseNode(SonarCustomNoiseNodeBase):
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseChainInputTypes().req_selectnoise_noise_type(
tooltip="Sets the type of noise to generate.",
),
)
@classmethod
def get_item_class(cls):
return noise.CustomNoiseItem
class SonarCustomNoiseAdvNode(SonarCustomNoiseNode):
DESCRIPTION = "A custom noise item allowing advanced YAML parameter input."
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseChainInputTypes(parent=SonarCustomNoiseNode).opt_yaml(
tooltip="Allows specifying custom parameters via YAML. Note: When specifying paramaters this way, there is generally little to no error checking.",
),
)
class SonarNormalizeNoiseNodeMixin:
@staticmethod
def get_normalize(val: str) -> bool | None:
return None if val == "default" else val == "forced"
-263
View File
@@ -1,263 +0,0 @@
# ruff: noqa: A002
from __future__ import annotations
from copy import deepcopy
from functools import partial
from typing import Callable, TypeVar
class InputCollection:
_DELEGATE_KEYS = frozenset((
"bool",
"boolean",
"clip",
"conditioning",
"field",
"float",
"image",
"int",
"latent",
"model",
"sampler",
"seed",
"sigmas",
"string",
"vae",
))
def __init__(self, **kwargs: dict):
self.fields = kwargs
def __getattr__(self, key: str):
splitkey = key.split("_", 1)
if len(splitkey) == 1 or splitkey[0] not in self._DELEGATE_KEYS:
errstr = f"Unknown attribute {key} for InputCollection"
raise AttributeError(errstr)
meth = getattr(self, splitkey[0])
return partial(meth, splitkey[1]) if len(splitkey) == 2 else meth
def to_dict(self):
return deepcopy(self.fields)
def clone(self):
return InputCollection(**self.to_dict())
def __len__(self) -> int:
return len(self.fields)
def __contains__(self, key: str) -> bool:
return key in self.fields
def field(
self,
name: str,
type: str | tuple,
*,
_skip: bool = False,
**kwargs: dict,
) -> InputCollection:
if not _skip:
self.fields[name] = (type,) if not kwargs else (type, kwargs)
return self
def string(
self,
name: str,
**kwargs: dict,
) -> InputCollection:
return self.field(name, "STRING", **kwargs)
def float(
self,
name: str,
*,
step: float = 0.001,
min: float = -10000.0,
max: float = 10000.0,
round: bool = False,
**kwargs: dict,
) -> InputCollection:
return self.field(
name,
"FLOAT",
step=step,
min=min,
max=max,
round=round,
**kwargs,
)
def int(
self,
name: str,
*,
min: float = -10000,
max: float = 10000,
**kwargs: dict,
) -> InputCollection:
return self.field(
name,
"INT",
min=min,
max=max,
**kwargs,
)
def bool(
self,
name: str,
default: bool = False,
**kwargs: dict,
) -> InputCollection:
return self.field(name, "BOOLEAN", default=default, **kwargs)
boolean = bool
def seed(
self,
name: str = "seed",
*,
default: int = 0,
min: int = 0,
max: int = 0xFFFFFFFFFFFFFFFF,
tooltip="Seed to use for generated noise",
**kwargs: dict,
) -> InputCollection:
return self.int(
name,
default=default,
min=min,
max=max,
tooltip=tooltip,
**kwargs,
)
def image(self, name: str = "image", **kwargs: dict) -> InputCollection:
return self.field(name, "IMAGE", **kwargs)
def latent(self, name: str = "latent", **kwargs: dict) -> InputCollection:
return self.field(name, "LATENT", **kwargs)
def conditioning(
self,
name: str = "conditioning",
**kwargs: dict,
) -> InputCollection:
return self.field(name, "CONDITIONING", **kwargs)
def model(self, name: str = "model", **kwargs: dict) -> InputCollection:
return self.field(name, "MODEL", **kwargs)
def sigmas(self, name: str = "sigmas", **kwargs: dict) -> InputCollection:
return self.field(name, "SIGMAS", **kwargs)
def sampler(self, name: str = "sampler", **kwargs: dict) -> InputCollection:
return self.field(name, "SAMPLER", **kwargs)
def clip(self, name: str = "clip", **kwargs: dict) -> InputCollection:
return self.field(name, "CLIP", **kwargs)
def vae(self, name: str = "vae", **kwargs: dict) -> InputCollection:
return self.field(name, "VAE", **kwargs)
class InputTypes:
C = TypeVar("C", bound=type)
def __init__(
self,
*,
parent=None,
parent_field: str | None = "INPUT_TYPES",
parent_args=(),
parent_kwargs=None,
required: dict | C | None = None,
optional: dict | C | None = None,
collection_class: C = InputCollection,
):
if parent is not None and parent_field is not None:
parent = getattr(parent, parent_field)
if isinstance(parent, LazyInputTypes):
parent = parent.get_input_types(
*parent_args,
**({} if parent_kwargs is None else parent_kwargs),
)
if isinstance(parent, LazyInputTypes):
raise TypeError("Unexpected multi-level LazyInputTypes parent!")
if required is None:
required = {}
elif isinstance(required, collection_class):
required = required.to_dict()
elif not isinstance(required, dict):
raise TypeError("Bad type for 'required' parameter.")
if optional is None:
optional = {}
elif isinstance(optional, collection_class):
optional = optional.to_dict()
elif not isinstance(optional, dict):
raise TypeError("Bad type for 'optional' parameter.")
if parent is not None:
required = parent.required.to_dict() | required
optional = parent.optional.to_dict() | optional
self.required = collection_class(**required)
self.optional = collection_class(**optional)
def __len__(self) -> int:
return len(self.required) + len(self.optional)
def clone(self) -> InputTypes:
return InputTypes(required=self.required, optional=self.optional)
def to_dict(self) -> dict:
return {
"required": self.required.to_dict(),
"optional": self.optional.to_dict(),
}
def __call__(self) -> dict:
return self.to_dict()
def __getattr__(self, key: str):
if key.startswith("req_"):
meth = getattr(self.required, key[4:])
elif key.startswith("opt_"):
meth = getattr(self.optional, key[4:])
else:
errstr = f"Unknown attribute {key} for InputTypes"
raise AttributeError(errstr)
def wrapper(*args: list, **kwargs: dict):
meth(*args, **kwargs)
return self
return wrapper
class LazyInputTypes:
def __init__(self, builder: Callable, initializers=()):
self._input_types_params = {}
self._input_types = None
self.builder = builder
self.initializers = initializers
def get_input_types(self, *args: list, **kwargs: dict):
if args or kwargs:
args = tuple(args)
cache_key = (args, tuple(kwargs.items()))
cached = self._input_types_params.get(cache_key)
else:
cache_key = None
cached = self._input_types
if cached:
return cached
for fun in self.initializers:
fun()
result = self.builder(*args, **kwargs)
if not cache_key:
self._input_types = result
else:
self._input_types_params[cache_key] = result
return result
def __call__(self, *args: list, **kwargs: dict) -> dict:
return self.get_input_types(*args, **kwargs)()
-288
View File
@@ -1,288 +0,0 @@
from __future__ import annotations
from comfy import samplers
from .. import external, noise
from .base import (
NoiseNoChainInputTypes,
SonarCustomNoiseNodeBase,
SonarInputTypes,
SonarLazyInputTypes,
SonarNormalizeNoiseNodeMixin,
)
NODE_CLASS_MAPPINGS = {}
bleh = None
class SonarBlendFilterNoiseNode(
SonarCustomNoiseNodeBase,
SonarNormalizeNoiseNodeMixin,
):
DESCRIPTION = "Custom noise type that allows blending and filtering the output of another noise generator using ComfyUI-bleh."
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseNoChainInputTypes()
.req_customnoise_sonar_custom_noise()
.req_selectblend(insert_modes=("simple_add",), default="simple_add")
.req_field_ffilter(
() if bleh is None else tuple(bleh.py.latent_utils.FILTER_PRESETS.keys()),
)
.req_string_ffilter_custom(default="")
.req_float_ffilter_scale(default=1.0)
.req_float_ffilter_strength(default=0.0)
.req_int_ffilter_threshold(default=1, min=1, max=32)
.req_field_enhance_mode(
("none",)
if bleh is None
else ("none", *bleh.py.latent_utils.ENHANCE_METHODS),
default="none",
)
.req_float_enhance_strength(default=0.0)
.req_field_affect(("result", "noise", "both"), default="result")
.req_normalizetristate_normalize_result()
.req_normalizetristate_normalize_noise(),
)
@classmethod
def get_item_class(cls):
return noise.BlendFilterNoise
def go(
self,
*,
factor,
sonar_custom_noise,
blend_mode,
ffilter,
ffilter_custom,
ffilter_scale,
ffilter_strength,
ffilter_threshold,
enhance_mode,
enhance_strength,
affect,
normalize_result,
normalize_noise,
):
if bleh is None:
raise RuntimeError("bleh not available")
import ast # noqa: PLC0415
ffilter_custom = ffilter_custom.strip()
normalize_result = (
None if normalize_result == "default" else normalize_result == "forced"
)
normalize_noise = (
None if normalize_noise == "default" else normalize_noise == "forced"
)
if ffilter_custom:
ffilter = ast.literal_eval(f"[{ffilter_custom}]")
elif ffilter == "none":
ffilter = None
else:
ffilter = bleh.py.latent_utils.FILTER_PRESETS[ffilter]
return super().go(
factor,
noise=sonar_custom_noise.clone(),
blend_mode=blend_mode,
ffilter=ffilter,
ffilter_scale=ffilter_scale,
ffilter_strength=ffilter_strength,
ffilter_threshold=ffilter_threshold,
enhance_mode=enhance_mode,
enhance_strength=enhance_strength,
affect=affect,
normalize_noise=self.get_normalize(normalize_noise),
normalize_result=self.get_normalize(normalize_result),
)
class SonarBlehOpsNoiseNode(
SonarCustomNoiseNodeBase,
SonarNormalizeNoiseNodeMixin,
):
DESCRIPTION = (
"Custom noise type that allows manipulating noise with ComfyUI-bleh ops."
)
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseNoChainInputTypes()
.req_customnoise_sonar_custom_noise()
.req_normalizetristate_normalize()
.req_yaml_rules(
tooltip="Enter rules in the bleh block ops format here.",
placeholder="# YAML ops here",
),
)
@classmethod
def get_item_class(cls):
return noise.BlehOpsNoise
def go(
self,
*,
factor,
sonar_custom_noise,
rules,
normalize,
):
if bleh is None:
raise RuntimeError("bleh not available")
return super().go(
factor,
noise=sonar_custom_noise.clone(),
rules=bleh.py.nodes.ops.RuleGroup.from_yaml(rules),
normalize=normalize,
)
restart = None
def KRestartSamplerCustomNoise_INPUT_TYPES_BUILDER():
if restart is not None:
get_normal_schedulers = getattr(
restart.nodes,
"get_supported_normal_schedulers",
restart.nodes.get_supported_restart_schedulers,
)
restart_normal_schedulers = get_normal_schedulers()
restart_schedulers = restart.nodes.get_supported_restart_schedulers()
restart_default_segments = restart.restart_sampling.DEFAULT_SEGMENTS
else:
restart_default_segments = ""
restart_normal_schedulers = restart_schedulers = ()
return (
SonarInputTypes()
.req_model()
.req_field_add_noise(("enable", "disable"), default="enable")
.req_seed_noise_seed()
.req_int_steps(default=20, min=1)
.req_float_cfg(default=8.0, min=0.0)
.req_sampler()
.req_field_scheduler(restart_normal_schedulers)
.req_conditioning_positive()
.req_conditioning_negative()
.req_latent_latent_image()
.req_int_start_at_step(default=0, min=0)
.req_int_end_at_step(default=10000, min=0)
.req_field_return_with_leftover_noise(
("disable", "enable"),
default="disable",
)
.req_string_segments(default=restart_default_segments)
.req_field_restart_scheduler(restart_schedulers)
.req_bool_chunked_mode(default=True)
.opt_customnoise_custom_noise_opt(tooltip="Optional custom noise input.")
)
class KRestartSamplerCustomNoise:
DESCRIPTION = "Restart sampler variant that allows specifying a custom noise type for noise added by restarts."
INPUT_TYPES = SonarLazyInputTypes(KRestartSamplerCustomNoise_INPUT_TYPES_BUILDER)
RETURN_TYPES = ("LATENT", "LATENT")
RETURN_NAMES = ("output", "denoised_output")
FUNCTION = "go"
CATEGORY = "sampling"
@classmethod
def go(
cls,
*,
model,
add_noise,
noise_seed,
steps,
cfg,
sampler,
scheduler,
positive,
negative,
latent_image,
start_at_step,
end_at_step,
return_with_leftover_noise,
segments,
restart_scheduler,
chunked_mode=False,
custom_noise_opt=None,
):
if restart is None:
raise RuntimeError("Restart not available")
return restart.restart_sampling.restart_sampling(
model,
noise_seed,
steps,
cfg,
sampler,
scheduler,
positive,
negative,
latent_image,
segments,
restart_scheduler,
disable_noise=add_noise == "disable",
step_range=(start_at_step, end_at_step),
force_full_denoise=return_with_leftover_noise != "enable",
output_only=False,
chunked_mode=chunked_mode,
custom_noise=custom_noise_opt.make_noise_sampler
if custom_noise_opt
else None,
)
class RestartSamplerCustomNoise:
DESCRIPTION = "Wrapper used to make another sampler Restart compatible. Allows specifying a custom type for noise added by restarts."
RETURN_TYPES = ("SAMPLER",)
FUNCTION = "go"
CATEGORY = "sampling/custom_sampling/samplers"
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_sampler()
.req_bool_chunked_mode(default=True)
.opt_customnoise_custom_noise_opt(tooltip="Optional custom noise input."),
)
@classmethod
def go(cls, sampler, chunked_mode, custom_noise_opt=None):
if restart is None or not hasattr(restart.restart_sampling, "RestartSampler"):
raise RuntimeError("Restart not available")
restart_options = {
"restart_chunked": chunked_mode,
"restart_wrapped_sampler": sampler,
"restart_custom_noise": None
if custom_noise_opt is None
else custom_noise_opt.make_noise_sampler,
}
restart_sampler = samplers.KSAMPLER(
restart.restart_sampling.RestartSampler.sampler_function,
extra_options=sampler.extra_options | restart_options,
inpaint_options=sampler.inpaint_options,
)
return (restart_sampler,)
NODE_CLASS_MAPPINGS |= {
"KRestartSamplerCustomNoise": KRestartSamplerCustomNoise,
"RestartSamplerCustomNoise": RestartSamplerCustomNoise,
"SonarBlendFilterNoise": SonarBlendFilterNoiseNode,
"SonarBlehOpsNoise": SonarBlehOpsNoiseNode,
}
def init_integrations(integrations):
global restart, bleh # noqa: PLW0603
restart = integrations.restart
bleh = integrations.bleh
external.MODULES.register_init_handler(init_integrations)
-550
View File
@@ -1,550 +0,0 @@
from __future__ import annotations
import functools
import math
from typing import TYPE_CHECKING
from .. import utils
from ..external import IntegratedNode
from ..latent_ops import (
SonarLatentOperation,
SonarLatentOperationAdvanced,
SonarLatentOperationNoise,
SonarLatentOperationSetSeed,
)
from .base import SonarInputTypes, SonarLazyInputTypes
from .noise_filters import SonarQuantileFilteredNoiseNode
if TYPE_CHECKING:
import torch
class SonarApplyLatentOperationCFG(metaclass=IntegratedNode):
DESCRIPTION = "Allows applying a LATENT_OPERATION during sampling. ComfyUI has a few that are builtin and this node pack also includes: SonarLatentOperationQuantileFilter."
RETURN_TYPES = ("MODEL",)
CATEGORY = "latent/advanced/operations"
FUNCTION = "go"
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_model()
.req_field_mode(
(
"cond_sub_uncond",
"denoised_sub_uncond",
"uncond_sub_cond",
"denoised",
"cond",
"uncond",
"model_input",
),
default="cond_sub_uncond",
tooltip="cond_sub_uncond is what ComfyUI's latent operations use. The non-sub_uncond modes likely won't work with pred_flip mode enabled. If you have anything but the denoised options selected, this will use pre-CFG, otherwise it will use post-CFG (unless you are using model_input).",
)
.req_bool_pred_flip_mode(
tooltip="Lets you try to apply the latent operation to the noise prediction rather than the image prediction. Doesn't work properly with the non-sub_uncond modes. No real reason it should be better, just something you can try. Note: The noise prediction gets scaled by the sigma first, in case that's useful information.",
)
.req_bool_require_uncond(
tooltip="When enabled, the operation will be skipped if uncond is unavailable. This will also happen if you choose a mode that requires uncond.",
)
.req_float_start_sigma(
default=-1.0,
min=-1.0,
tooltip="First sigma the effect becomes active. You can set a negative value here to use whatever the model's maximum sigma is.",
)
.req_float_end_sigma(
default=0.0,
min=0.0,
tooltip="Last sigma the effect is active.",
)
.req_selectblend_blend_mode(
tooltip="Controls how the output of the latent operation is blended with the original result.",
)
.req_float_blend_strength(
default=0.5,
tooltip="Strength of the blend. For a normal blend mode like LERP, 1.0 means use 100% of the output from the latent operation, 0.0 means use none of it and only the original value. Note: Blending is applied to the final result of the operations unless you enable immediate_blend, in other words operation_2 sees a full unblended result from operation_1.",
)
.req_field_blend_scale_mode(
(
"none",
"reverse_sampling",
"sampling",
"reverse_enabled_range",
"enabled_range",
"sampling_sin",
"enabled_range_sin",
),
default="reverse_sampling",
tooltip="Can be used to scale the blend strength over time. Basically works like blend_strength * scale_factor (see below)\nnone: Just uses the blend_strength you have set.\nreverse_sampling: The opposite of the model sampling percent, so if you're making a new generation, the beginning of sampling will be 1.0 and the end will be 0.0. The recommended option as applying these operations usually works better toward the beginning of sampling.\nsampling: Same as reverse_sampling, except the beginning will be 0.0 and the end will be 1.0.\nreverse_enabled_range: Flipped percentage of the range between start_sigma and end_sigma.\nenabled_range: Percentage of the range between start_sigma and end_sigma.\nsampling_sin: Uses the sampling percentage with the sine function such that blend_strength will hit the peak value in the middle of the range.\nenabled_range_sin: Similar to sampling_sin except it applies to the percentage of the enabled range.",
)
.req_float_blend_scale_offset(
default=0.0,
min=-1.0,
max=1.0,
tooltip="Only applies when blend_scale_mode is not none. Adds the offset to the calculated percentage and then clamps it to be between blend_scale_min and blend_scale_max.",
)
.req_float_blend_scale_min(
default=0.0,
tooltip="Only applies when blend_scale_mode is not none. Minimum value for the blend scale percentage. Many blend modes don't tolerate negative values here.",
)
.req_float_blend_scale_max(
default=1.0,
tooltip="Only applies when blend_scale_mode is not none. Maximum value for the blend scale percentage. Many blend modes don't tolerate values over 1.0 here.",
)
.req_bool_immediate_blend(
tooltip="You can enable this to do blending immediately after each latent operation is called. Mainly affects the case where you have multiple latent operations connected.",
)
.opt_field_operation_1(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
)
.opt_field_operation_2(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
)
.opt_field_operation_3(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
)
.opt_field_operation_4(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
)
.opt_field_operation_5(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
),
)
@staticmethod
def get_blend_scaling(
*,
model_sampling: object,
scale_mode: str,
sigma: float,
sigma_t_max: torch.Tensor,
start_sigma: float,
end_sigma: float,
offset: float,
min_pct: float,
max_pct: float,
) -> float | torch.Tensor:
if scale_mode == "none":
return 1.0
if scale_mode in {"sampling", "sampling_sin", "reverse_sampling"}:
rev_sampling_pct = (
(model_sampling.timestep(sigma_t_max) / 999).clamp(0, 1).detach().item()
)
result = (
1.0 - rev_sampling_pct if scale_mode == "sampling" else rev_sampling_pct
)
elif scale_mode in {
"enabled_range",
"enabled_range_sin",
"reverse_enabled_range",
}:
rev_range_pct = (sigma - end_sigma) / (start_sigma - end_sigma)
result = (
1.0 - rev_range_pct if scale_mode == "enabled_range" else rev_range_pct
)
else:
raise ValueError("Bad blend_scale_mode")
if scale_mode.endswith("_sin"):
result = math.sin(result * math.pi)
return max(min_pct, min(result + offset, max_pct))
@classmethod
def go(
cls,
*,
model,
mode: str,
pred_flip_mode: bool,
require_uncond: bool,
start_sigma: float,
end_sigma: float,
blend_mode: str,
blend_strength: float,
blend_scale_mode: str,
blend_scale_offset: float,
blend_scale_min: float,
blend_scale_max: float,
immediate_blend: bool,
operation_1=None,
operation_2=None,
operation_3=None,
operation_4=None,
operation_5=None,
) -> tuple:
if mode == "model_input":
if require_uncond:
raise ValueError(
"require_uncond does not make sense for the model_input mode.",
)
if pred_flip_mode:
raise ValueError(
"pred_flip does not make sense for the model_input mode.",
)
model = model.clone()
operations = tuple(
SonarLatentOperation(op=o)
for o in (operation_1, operation_2, operation_3, operation_4, operation_5)
if o is not None
)
if not operations:
return (model,)
ms = model.get_model_object("model_sampling")
post_cfg_mode = mode in {"denoised", "denoised_sub_uncond"}
blend_function = utils.BLENDING_MODES[blend_mode]
sigma_max, sigma_min = (
ms.sigma_max.detach().item(),
ms.sigma_min.detach().item(),
)
if start_sigma < 0:
start_sigma = sigma_max
start_sigma = max(sigma_min, min(sigma_max, start_sigma))
end_sigma = max(sigma_min, min(sigma_max, end_sigma))
if end_sigma > start_sigma:
start_sigma, end_sigma = end_sigma, start_sigma
if start_sigma == end_sigma:
blend_scale_mode = "none"
orig_mode = mode
def patch(args: dict) -> torch.Tensor:
nonlocal mode
x = args["input"]
cond_scale = args.get("cond_scale")
sigma_t = args["sigma"]
sigma_t_max = sigma_t.max()
if sigma_t.numel() > 1:
shape_pad = (1,) * (x.ndim - sigma_t.ndim)
sigma_t = sigma_t.reshape(sigma_t.shape[0], *shape_pad)
sigma = sigma_t_max.detach().item()
enabled = end_sigma <= sigma <= start_sigma
conds_out = args.get("conds_out", ())
uncond = (
args.get("uncond_denoised")
if post_cfg_mode
else (conds_out[1] if len(conds_out) > 1 else None)
)
if uncond is None and (
require_uncond
or mode in {"uncond", "uncond_sub_cond", "denoised_sub_uncond"}
):
enabled = False
if not enabled:
if mode == "model_input":
return x
return args["denoised"] if post_cfg_mode else conds_out
cond = conds_out[0] if not post_cfg_mode and len(conds_out) else None
if uncond is None and mode.endswith("_sub_uncond"):
mode = orig_mode.split("_", 1)[0]
else:
mode = orig_mode
if mode == "model_input":
t1 = x
t2 = None
elif mode in {"cond", "cond_sub_uncond"}:
t1 = cond
t2 = uncond if mode == "cond_sub_uncond" else None
elif mode in {"uncond", "uncond_sub_cond"}:
t1 = uncond
t2 = cond if mode == "uncond_sub_cond" else None
else:
t1 = args["denoised"]
t2 = uncond if mode == "denoised_sub_uncond" else None
t1_orig = t1
if pred_flip_mode:
t1 = (x - t1) / sigma_t
if t2 is not None:
t2 = (x - t2) / sigma_t
curr_blend = blend_strength * cls.get_blend_scaling(
scale_mode=blend_scale_mode,
offset=blend_scale_offset,
min_pct=blend_scale_min,
max_pct=blend_scale_max,
model_sampling=args["model"].model_sampling,
start_sigma=start_sigma,
end_sigma=end_sigma,
sigma=max(sigma_min, min(sigma, sigma_max)),
sigma_t_max=sigma_t_max.clamp(sigma_min, sigma_max),
)
result = t1 - t2 if t2 is not None else t1.clone()
for operation in operations:
curr_result = operation(
result,
sigma=sigma,
t2=t2,
cond=cond,
uncond=uncond,
cond_scale=cond_scale,
raw_args=args,
)
result = (
blend_function(result, curr_result, curr_blend)
if immediate_blend
else curr_result
)
if t2 is not None:
result += t2
if pred_flip_mode:
result = x - sigma_t * result
if not immediate_blend:
result = blend_function(t1_orig, result, curr_blend)
if post_cfg_mode or mode == "model_input":
return result
conds_out = conds_out.copy()
conds_out[0 if mode.startswith("cond") else 1] = result
return conds_out
if post_cfg_mode:
model.set_model_sampler_post_cfg_function(patch)
elif mode == "model_input":
def patch_wrapper(apply_model, args: dict) -> torch.Tensor:
timestep = args["timestep"]
patch_args = args | {"sigma": timestep, "model": model.model}
return apply_model(patch(patch_args), timestep, **args["c"])
model.set_model_unet_function_wrapper(patch_wrapper)
else:
model.set_model_sampler_pre_cfg_function(patch)
return (model,)
class SonarLatentOperationQuantileFilter(SonarQuantileFilteredNoiseNode):
DESCRIPTION = "Allows applying a quantile normalization function to the latent during sampling. Can be used with Sonar SonarApplyLatentOperationCFG. The just copies most of the parameters from the other quantile normalization node where it talks to 'noise', this will apply to whatever you're applying the latent operation to (denoised, uncond, etc)."
RETURN_TYPES = ("LATENT_OPERATION",)
CATEGORY = "latent/advanced/operations"
@classmethod
def INPUT_TYPES(cls):
result = super().INPUT_TYPES()
result.pop("optional", None)
reqparams = result["required"]
for k in ("custom_noise", "normalize", "normalize_noise", "factor"):
reqparams.pop(k, None)
return result
@classmethod
def go(
cls,
*,
quantile: float,
dim: str,
flatten: bool,
norm_power: float,
norm_factor: float,
strategy: str,
):
qnorm_filter = functools.partial(
utils.quantile_normalize,
quantile=quantile,
dim=None if dim == "global" else int(dim),
flatten=flatten,
nq_fac=norm_factor,
pow_fac=norm_power,
strategy=strategy,
)
return (SonarLatentOperation(op=lambda latent: qnorm_filter(latent)),) # noqa: PLW0108
class SonarLatentOperationAdvancedNode(metaclass=IntegratedNode):
DESCRIPTION = "Allows scheduling and other advanced features for latent operations. If you attach the optional extra LATENT_OPERATIONS, they will be called in sequence _before_ blending or output scaling."
RETURN_TYPES = ("LATENT_OPERATION",)
CATEGORY = "latent/advanced/operations"
FUNCTION = "go"
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_field_operation(
"LATENT_OPERATION",
tooltip="Latent operation to apply.",
)
.req_float_start_sigma(
default=-1.0,
min=-1.0,
tooltip="First sigma the effect becomes active. You can set a negative value here to use whatever the model's maximum sigma is.",
)
.req_float_end_sigma(
default=0.0,
min=0.0,
tooltip="Last sigma the effect is active.",
)
.req_float_input_multiplier(
default=1.0,
tooltip="Flat multiplier on the input to the latent operation. The multiplied input is *not* used when calculating the difference, it is only passed to the operation.",
)
.req_float_output_multiplier(
default=1.0,
tooltip="Flat multiplier on the output from the latent operation. Occurs before blending or calculating the difference.",
)
.req_float_difference_multiplier(
default=1.0,
tooltip="Flat multiplier on the difference or change from the original that the operation performed. Occurs after output_multiplier and before blending applies.",
)
.req_selectblend_blend_mode(
default="inject",
tooltip="Controls how the change from the operation is combined with the input. The default of inject just adds it scaled by the blend strength. With 1.0 blend strength, this is just using the output from the operation with no change.",
)
.req_float_blend_strength(
default=0.5,
tooltip="Strength of the blend.",
)
.opt_field_operation_alt(
"LATENT_OPERATION",
tooltip="Optional alternative operation that will be used when the primary one isn't enabled. May be useful in a case when you want one operation between sigma 1.0 and 0.5 and then a difference operation for lower sigmas which is kind of annoying to specify manually (you'd need to do something like configure another operation to start at 0.499999 or something).",
)
.opt_field_operation_2(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
)
.opt_field_operation_3(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
)
.opt_field_operation_4(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
)
.opt_field_operation_5(
"LATENT_OPERATION",
tooltip="Optional LATENT_OPERATION. The operations will be applied in sequence.",
),
)
@classmethod
def go(
cls,
*,
operation,
start_sigma: float,
end_sigma: float,
input_multiplier: float,
output_multiplier: float,
difference_multiplier: float,
blend_mode: str,
blend_strength: float,
operation_alt=None,
operation_2=None,
operation_3=None,
operation_4=None,
operation_5=None,
) -> tuple[SonarLatentOperationAdvanced]:
operations = tuple(
o if isinstance(o, SonarLatentOperation) else SonarLatentOperation(op=o)
for o in (operation, operation_2, operation_3, operation_4, operation_5)
if o is not None
)
if operation_alt is not None and not isinstance(
operation_alt,
SonarLatentOperation,
):
operation_alt = SonarLatentOperation(op=operation_alt)
return (
SonarLatentOperationAdvanced(
ops=operations,
op_alt=operation_alt,
start_sigma=start_sigma,
end_sigma=end_sigma,
input_multiplier=input_multiplier,
output_multiplier=output_multiplier,
difference_multiplier=difference_multiplier,
blend_mode=blend_mode,
blend_strength=blend_strength,
),
)
class SonarLatentOperationNoiseNode(metaclass=IntegratedNode):
DESCRIPTION = "Latent operation that allows injecting noise."
RETURN_TYPES = ("LATENT_OPERATION",)
CATEGORY = "latent/advanced/operations"
FUNCTION = "go"
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_customnoise_custom_noise()
.req_bool_scale_to_sigma(tooltip="Scales the noise to the current sigma.")
.req_bool_cpu_noise(
tooltip="Controls whether noise is generated on the CPU or GPU. GPU is usually faster but may change seeds for different models of GPU.",
)
.req_bool_normalize(
default=True,
tooltip="Controls whether the generated noise is normalized.",
)
.req_bool_lazy_noise_sampler(
default=True,
tooltip="When enabled, the latent operation will attempt to cache the noise sampler between calls and only recreate it when necessary. However, there isn't a 100% reliable way for a latent operation to know when sampling starts/ends so if we get it wrong this will lead to non-deterministic generations. I believe the heuristic I'm using to detect this should be reliable but you can disable it if you notice weird results.",
),
)
@classmethod
def go(
cls,
*,
custom_noise,
scale_to_sigma: bool,
cpu_noise: bool,
normalize: bool,
lazy_noise_sampler: bool,
) -> tuple[SonarLatentOperationNoise]:
return (
SonarLatentOperationNoise(
custom_noise=custom_noise,
scale_to_sigma=scale_to_sigma,
cpu_noise=cpu_noise,
normalize=normalize,
lazy_noise_sampler=lazy_noise_sampler,
),
)
class SonarLatentOperationSetSeedNode(metaclass=IntegratedNode):
DESCRIPTION = "Latent operation that allows setting a seed. Can be useful for running latent operations that generate noise outside of a normal sampling context (i.e. operations on the initial latent before sampling)."
RETURN_TYPES = ("LATENT_OPERATION",)
CATEGORY = "latent/advanced/operations"
FUNCTION = "go"
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_field_operation("LATENT_OPERATION")
.req_seed(
tooltip="Seed to set. Note that this is called _every time_ before the operation.",
)
.req_bool_restore_rng_state(
default=False,
tooltip="When enabled, the current RNG state is saved just before calling the operation and restored afterwards. In other words, only the latent operation will see the seed you set. Note: This only handles the PyTorch and Python random module states.",
),
)
@classmethod
def go(
cls,
*,
operation,
seed: int,
restore_rng_state: bool,
) -> tuple[SonarLatentOperationSetSeed]:
return (
SonarLatentOperationSetSeed(
op=operation,
seed=seed,
restore_rng_state=restore_rng_state,
),
)
NODE_CLASS_MAPPINGS = {
"SonarApplyLatentOperationCFG": SonarApplyLatentOperationCFG,
"SonarLatentOperationQuantileFilter": SonarLatentOperationQuantileFilter,
"SonarLatentOperationAdvanced": SonarLatentOperationAdvancedNode,
"SonarLatentOperationNoise": SonarLatentOperationNoiseNode,
"SonarLatentOperationSetSeed": SonarLatentOperationSetSeedNode,
}
-906
View File
@@ -1,906 +0,0 @@
from __future__ import annotations
import functools
import inspect
import math
import random
from typing import Any, Callable
import numpy as np
import torch
import yaml
from comfy import model_management, samplers
from tqdm import tqdm
from .. import noise, utils
from ..external import IntegratedNode
from ..noise import NoiseType
from ..wavelet_cfg import WaveletCFG, WCFGRules
from .base import (
NoiseChainInputTypes,
SonarCustomNoiseNodeBase,
SonarInputTypes,
SonarLazyInputTypes,
SonarNormalizeNoiseNodeMixin,
)
class NoisyLatentLikeNode(metaclass=IntegratedNode):
DESCRIPTION = "Allows generating noise (and optionally adding it) based on a reference latent. Note: For img2img workflows, you will generally want to enable add_to_latent as well as connecting the model and sigmas inputs."
RETURN_TYPES = ("LATENT",)
OUTPUT_TOOLTIPS = ("The noisy latent image.",)
CATEGORY = "latent/noise"
FUNCTION = "go"
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_selectnoise_noise_type(
tooltip="Sets the type of noise to generate. Has no effect when the custom_noise_opt input is connected.",
)
.req_seed()
.req_latent(tooltip="Latent used as a reference for generating noise.")
.req_float_multiplier(
default=1.0,
tooltip="Multiplier for the strength of the generated noise. Performed after mul_by_sigmas_opt.",
)
.req_bool_add_to_latent(
tooltip="Add the generated noise to the reference latent rather than adding it to an empty latent. Generally should be enabled for img2img workflows.",
)
.req_int_repeat_batch(
default=1,
min=1,
tooltip="Repeats the noise generation the specified number of times. For example, if set to two and your reference latent is also batch two you will get a batch of four as output.",
)
.req_bool_cpu_noise(
default=True,
tooltip="Controls whether noise will be generated on GPU or CPU. Only affects noise types that support GPU generation (maybe only Brownian).",
)
.req_bool_normalize(
default=True,
tooltip="Controls whether the generated noise is normalized to 1.0 strength before scaling. Generally should be left enabled.",
)
.opt_customnoise_custom_noise_opt()
.opt_sigmas_mul_by_sigmas_opt(
tooltip="When connected, will scale the generated noise by the first sigma. Must also connect model_opt to enable.",
)
.opt_model_model_opt(
tooltip="Used when mul_by_sigmas_opt is connected, no effect otherwise.",
),
)
@classmethod
def go(
cls,
*,
noise_type: str,
seed: int | None,
latent: dict,
multiplier: float = 1.0,
add_to_latent=False,
repeat_batch=1,
cpu_noise=True,
normalize=True,
custom_noise_opt: object | None = None,
mul_by_sigmas_opt: torch.Tensor | None = None,
model_opt: object | None = None,
):
model, sigmas = model_opt, mul_by_sigmas_opt
if sigmas is not None and len(sigmas) > 0:
if model is None:
raise ValueError(
"NoisyLatentLike requires a model when sigmas are connected!",
)
while hasattr(model, "model"):
model = model.model
latent_scale_factor = model.latent_format.scale_factor
model_sigma_max = float(model.model_sampling.sigma_max)
first_sigma = float(sigmas[0])
max_denoise = (
math.isclose(model_sigma_max, first_sigma, rel_tol=1e-05)
or first_sigma > model_sigma_max
)
multiplier *= (
float(
torch.sqrt(1.0 + sigmas[0] ** 2.0) if max_denoise else sigmas[0],
)
/ latent_scale_factor
)
if sigmas is not None and sigmas.numel() > 1:
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
sigma, sigma_next = sigmas[0], sigmas[1]
else:
sigma_min, sigma_max, sigma, sigma_next = (None,) * 4
latent_samples = latent["samples"]
orig_device = latent_samples.device
want_device = (
torch.device("cpu") if cpu_noise else model_management.get_torch_device()
)
if latent_samples.device != want_device:
latent_samples = latent_samples.detach().clone().to(want_device)
if custom_noise_opt is not None:
ns = custom_noise_opt.make_noise_sampler(
latent_samples,
sigma_min=sigma_min,
sigma_max=sigma_max,
seed=seed,
cpu=cpu_noise,
normalized=normalize,
)
else:
ns = noise.get_noise_sampler(
NoiseType[noise_type.upper()],
latent_samples,
sigma_min,
sigma_max,
seed=seed,
cpu=cpu_noise,
normalized=normalize,
)
randst = torch.random.get_rng_state()
try:
torch.random.manual_seed(seed)
result = torch.cat(
tuple(ns(sigma, sigma_next) for _ in range(repeat_batch)),
dim=0,
)
finally:
torch.random.set_rng_state(randst)
result = utils.scale_noise(result, multiplier, normalized=True)
if add_to_latent:
result += latent_samples.repeat(
*(repeat_batch if i == 0 else 1 for i in range(latent_samples.ndim)),
).to(result)
result = result.to(orig_device)
return ({"samples": result},)
class SonarNoiseImageNode(metaclass=IntegratedNode):
DESCRIPTION = "Allows adding noise to an image or generating images full of noise."
RETURN_TYPES = ("IMAGE",)
CATEGORY = "image"
FUNCTION = "go"
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_selectnoise_noise_type(
tooltip="Sets the type of noise to generate. Has no effect when the custom_noise_opt input is connected.",
)
.req_seed()
.req_image(tooltip="Image noise will be added to.")
.req_float_noise_min(
default=0.0,
tooltip="Generated noise will be normalized to have values between noise_min and noise_max. If you set them both to the same value then this disables normalization.",
)
.req_float_noise_max(
default=1.0,
tooltip="Generated noise will be normalized to have values between noise_min and noise_max. If you set them both to the same value then this disables normalization.",
)
.req_float_noise_multiplier(
default=0.5,
tooltip="Multiplier for the strength of the generated noise. This is performed after noise_min/max scaling.",
)
.req_field_channel_mode(
(
"RGB",
"RGBA",
"R",
"G",
"B",
"A",
"RA",
"GA",
"BA",
"RG",
"RB",
"GB",
"RGA",
"RBA",
"GBA",
),
default="RGB",
tooltip="RGBA will also add noise to the alpha channel as well if it exists. Only used for 3 or 4 channel images, for other numbers of channels (i.e. one channel) then all channels will be targeted.",
)
.req_selectblend(
insert_modes=("simple_add",),
default="simple_add",
tooltip="Controls how the generated noise is combined with the image. simple_add just adds it and blend_strength is ignored in that case.",
)
.req_float_blend_strength(
default=0.5,
tooltip="Multiplier for the strength of the generated noise.",
)
.req_field_overflow_mode(
("clamp", "rescale"),
default="clamp",
tooltip="When set to clamp, values above/below 0, 1 will be set to those values. When set to rescale, the image values will be rescaled such that the minimum value is 0 and the maximum is 1.",
)
.req_bool_greyscale_mode(
tooltip="When set to clamp, values above/below 0, 1 will be set to those values. When set to rescale, the image values will be rescaled such that the minimum value is 0 and the maximum is 1.",
)
.req_bool_pure_noise_mode(
tooltip="When enabled, the original image is only used for its shape and you will be adding noise to an image full of zeros (black), suitable for creating pure noise images.",
)
.req_field_dtype(
("default", "float32", "float64", "float16", "bfloat16"),
default="default",
tooltip="When set to default it will use the same type as the input tensor (probably float32). You can manually set the dtype if you want, though it likely isn't going to matter. Using dtypes with limited range (float16, bfloat16) isn't recommended.",
)
.req_bool_cpu_noise(
default=True,
tooltip="Controls whether noise will be generated on GPU or CPU.",
)
.req_bool_normalize(
default=True,
tooltip="Controls whether the generated noise is normalized to 1.0 strength before scaling. Generally should be left enabled.",
)
.opt_customnoise_custom_noise_opt(
tooltip="Allows connecting a custom noise chain. When connected, noise_type has no effect.",
),
)
@classmethod
def go(
cls,
*,
noise_type: str,
seed: int,
image: torch.Tensor,
noise_multiplier: float,
noise_min: float,
noise_max: float,
channel_mode: str,
blend_mode: str,
blend_strength: float,
overflow_mode: str,
greyscale_mode: bool,
dtype: str,
pure_noise_mode: bool,
cpu_noise: bool,
normalize: bool,
custom_noise_opt: object | None = None,
):
sigma_min, sigma_max, sigma, sigma_next = (None,) * 4
orig_image = image = (
torch.zeros_like(image) if pure_noise_mode else image.detach().clone()
)
if image.ndim == 3:
image = image.unsqueeze(0)
elif image.ndim != 4:
errstr = (
f"Expected image tensor with 3 or 4 dimensions, got {image.ndim}",
)
raise ValueError(errstr)
blend_function = (
utils.BLENDING_MODES[blend_mode]
if blend_mode != "simple_add"
else lambda a, b, _t: a + b
)
if noise_min > noise_max:
noise_min, noise_max = noise_max, noise_min
image = image.movedim(-1, 1)
channels = image.shape[1]
channel_map = {"R": 0, "B": 1, "G": 2, "A": 3}
channel_mode = channel_mode.upper()
if channels == 3 or channels == 4: # noqa: PLR1714
channel_targets = tuple(
channel_map[c]
for c in "RGBA"
if c in channel_mode and channel_map[c] < channels
)
else:
channel_targets = tuple(range(channels))
want_device = (
torch.device("cpu") if cpu_noise else model_management.get_torch_device()
)
image = image.to(
device=want_device,
dtype={
"float32": torch.float32,
"float64": torch.float64,
"bfloat16": torch.bfloat16,
"float16": torch.float16,
}.get(
dtype,
image.dtype,
),
)
pyrandst = random.getstate()
randst = torch.random.get_rng_state()
try:
random.seed(seed)
torch.random.manual_seed(seed)
if custom_noise_opt is not None:
ns = custom_noise_opt.make_noise_sampler(
image,
sigma_min=sigma_min,
sigma_max=sigma_max,
seed=seed,
cpu=cpu_noise,
normalized=normalize,
)
else:
ns = noise.get_noise_sampler(
NoiseType[noise_type.upper()],
image,
sigma_min,
sigma_max,
seed=seed,
cpu=cpu_noise,
normalized=normalize,
)
result = ns(sigma, sigma_next)
finally:
torch.random.set_rng_state(randst)
random.setstate(pyrandst)
del ns
result = utils.scale_noise(result, normalized=True)
if greyscale_mode:
result = result.mean(dim=1, keepdim=True).expand(image.shape).contiguous()
if noise_max != 0 and noise_min != noise_max: # noqa: PLR1714
result = utils.normalize_to_scale(result, noise_min, noise_max)
result *= noise_multiplier
image[:, channel_targets, ...] = blend_function(
image[:, channel_targets, ...],
result[:, channel_targets, ...],
blend_strength,
)
if overflow_mode == "rescale":
image = utils.normalize_to_scale(image, 0.0, 1.0)
else:
image = image.clip_(0, 1)
image = image.movedim(1, -1).to(
device=orig_image.device,
dtype=orig_image.dtype,
)
return (image,)
class CustomNOISE:
def __init__(
self,
custom_noise,
seed,
*,
cpu_noise=True,
normalize=True,
multiplier=1.0,
):
self.custom_noise = custom_noise
self.seed = seed
self.cpu_noise = cpu_noise
self.normalize = normalize
self.multiplier = multiplier
def _sample_noise(self, latent_image, seed):
result = self.custom_noise.make_noise_sampler(
latent_image,
None,
None,
seed=seed,
cpu=self.cpu_noise,
normalized=self.normalize,
)(None, None).to(
device="cpu",
dtype=latent_image.dtype,
)
if result.layout != latent_image.layout:
if latent_image.layout == torch.sparse_coo:
return result.to_sparse()
errstr = f"Cannot handle latent layout {type(latent_image.layout).__name__}"
raise NotImplementedError(errstr)
return result if self.multiplier == 1.0 else result.mul_(self.multiplier)
def generate_noise(self, input_latent):
latent_image = input_latent["samples"]
batch_inds = input_latent.get("batch_index")
torch.manual_seed(self.seed)
random.seed(self.seed)
if self.multiplier == 0.0:
return torch.zeros(
latent_image.shape,
dtype=latent_image.dtype,
layout=latent_image.layout,
device="cpu",
)
if batch_inds is None:
return self._sample_noise(latent_image, self.seed)
unique_inds, inverse_inds = np.unique(batch_inds, return_inverse=True)
result = []
batch_size = latent_image.shape[0]
for idx in range(unique_inds[-1] + 1):
noise = self._sample_noise(
latent_image[idx % batch_size].unsqueeze(0),
self.seed + idx,
)
if idx in unique_inds:
result.append(noise)
return torch.cat(tuple(result[i] for i in inverse_inds), axis=0)
class SonarToComfyNOISENode(metaclass=IntegratedNode):
DESCRIPTION = "Allows converting SONAR_CUSTOM_NOISE to NOISE (used by SamplerCustomAdvanced and possibly other custom samplers). NOTE: Does not work with noise types that depend on sigma (Brownian, ScheduledNoise, etc)."
RETURN_TYPES = ("NOISE",)
CATEGORY = "sampling/custom_sampling/noise"
FUNCTION = "go"
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_customnoise_custom_noise(
tooltip="Custom noise type to convert.",
)
.req_seed(tooltip="Seed to use for generated noise.")
.req_bool_cpu_noise(
default=True,
tooltip="Controls whether noise is generated on CPU or GPU.",
)
.req_bool_normalize(
default=True,
tooltip="Controls whether generated noise is normalized to 1.0 strength.",
)
.req_float_multiplier(
default=1.0,
tooltip="Simple multiplier applied to noise after all other scaling and normalization effects. If set to 0, no noise will be generated (same as disabling noise).",
),
)
@classmethod
def go(cls, *, custom_noise, seed, cpu_noise=True, normalize=True, multiplier=1.0):
return (
CustomNOISE(
custom_noise,
seed,
cpu_noise=cpu_noise,
normalize=normalize,
multiplier=multiplier,
),
)
class SamplerNodeConfigOverride(metaclass=IntegratedNode):
DESCRIPTION = "Allows overriding paramaters for a SAMPLER. Only parameters that particular sampler supports will be applied, so for example setting ETA will have no effect for non-ancestral Euler."
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_sampler()
.req_float_eta(
default=1.0,
tooltip="Basically controls the ancestralness of the sampler. When set to 0, you will get a non-ancestral (or SDE) sampler.",
)
.req_float_s_noise(
default=1.0,
tooltip="Multiplier for noise added during ancestral or SDE sampling.",
)
.req_float_s_churn(
default=0.0,
tooltip="Churn was the predececessor of ETA. Only used by a few types of samplers (notably Euler non-ancestral). Not used by any ancestral or SDE samplers.",
)
.req_float_r(
default=0.5,
tooltip="Used by dpmpp_sde (and perhaps a few other SDE samplers).",
)
.req_field_sde_solver(
("midpoint", "heun"),
tooltip="Solver used by dpmpp_2m_sde.",
)
.req_bool_cpu_noise(
default=True,
tooltip="Controls whether noise is generated on CPU or GPU.",
)
.req_bool_normalize(
default=True,
tooltip="Controls whether generated noise is normalized to 1.0 strength.",
)
.opt_selectnoise_noise_type(
insert_types=("DEFAULT",),
default="DEFAULT",
tooltip="Noise type used during ancestral or SDE sampling. DEFAULT will use the default for the attached sampler. Only used when the custom noise input is not connected.",
)
.opt_customnoise_custom_noise_opt(
tooltip="Optional input for custom noise used during ancestral or SDE sampling. When connected, the built-in noise_type selector is ignored.",
)
.opt_yaml(),
)
RETURN_TYPES = ("SAMPLER",)
CATEGORY = "sampling/custom_sampling/samplers"
FUNCTION = "get_sampler"
def get_sampler(
self,
*,
sampler,
eta,
s_noise,
s_churn,
r,
sde_solver,
cpu_noise=True,
noise_type=None,
custom_noise_opt=None,
normalize=True,
yaml_parameters="",
):
sampler_kwargs = {
"s_noise": s_noise,
"eta": eta,
"s_churn": s_churn,
"r": r,
"solver_type": sde_solver,
}
if yaml_parameters:
extra_params = yaml.safe_load(yaml_parameters)
if extra_params is None:
pass
elif not isinstance(extra_params, dict):
raise ValueError(
"SamplerConfigOverride: yaml_parameters must either be null or an object",
)
else:
sampler_kwargs |= extra_params
sampler_function = functools.update_wrapper(
functools.partial(
self.sampler_function,
override_sampler_cfg={
"sampler": sampler,
"noise_type": NoiseType[noise_type.upper()]
if noise_type not in {None, "DEFAULT"}
else None,
"custom_noise": custom_noise_opt,
"sampler_kwargs": sampler_kwargs,
"cpu_noise": cpu_noise,
"normalize": normalize,
},
),
sampler.sampler_function,
)
return (
samplers.KSAMPLER(
sampler_function,
extra_options=sampler.extra_options.copy(),
inpaint_options=sampler.inpaint_options.copy(),
),
)
@staticmethod
def sampler_function(
model,
x,
sigmas,
*args: list[Any],
override_sampler_cfg: dict[str, Any] | None = None,
noise_sampler: Callable | None = None,
extra_args: dict[str, Any] | None = None,
**kwargs: dict[str, Any],
) -> torch.Tensor:
if not override_sampler_cfg:
raise ValueError("Override sampler config missing!")
if extra_args is None:
extra_args = {}
cfg = override_sampler_cfg
sampler, sampler_kwargs, noise_type, custom_noise, cpu, normalize = (
cfg["sampler"],
cfg["sampler_kwargs"],
cfg.get("noise_type"),
cfg.get("custom_noise"),
cfg.get("cpu_noise", True),
cfg.get("normalize", True),
)
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
sig = inspect.signature(sampler.sampler_function)
params = sig.parameters
if "noise_sampler" in params:
seed = extra_args.get("seed")
if custom_noise is not None:
noise_sampler = custom_noise.make_noise_sampler(
x,
sigma_min,
sigma_max,
seed=seed,
cpu=cpu,
normalized=normalize,
)
elif noise_type is not None:
noise_sampler = noise.get_noise_sampler(
noise_type,
x,
sigma_min,
sigma_max,
seed=seed,
cpu=cpu,
normalized=normalize,
)
kwargs |= {k: v for k, v in sampler_kwargs.items() if k in params}
if "noise_sampler" in params:
kwargs["noise_sampler"] = noise_sampler
return sampler.sampler_function(
model,
x,
sigmas,
*args,
extra_args=extra_args,
**kwargs,
)
class SonarSplitNoiseChainNode(SonarCustomNoiseNodeBase, SonarNormalizeNoiseNodeMixin):
DESCRIPTION = "Custom noise type that allows splitting off a new chain. This can be useful if you want a link in the chain to be a blended type."
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseChainInputTypes()
.req_normalizetristate_normalize(
tooltip="Controls whether the generated noise is normalized to 1.0 strength.",
)
.opt_customnoise_custom_noise(),
)
@classmethod
def get_item_class(cls):
return noise.BlendedNoise
def go(
self,
*,
factor,
rescale,
sonar_custom_noise_opt=None,
normalize,
custom_noise=None,
):
return super().go(
factor,
rescale=rescale,
sonar_custom_noise_opt=sonar_custom_noise_opt,
blend_function=lambda a, _b, _t: a,
normalize=self.get_normalize(normalize),
custom_noise_1=custom_noise,
custom_noise_2=None,
noise_2_percent=0.0,
)
class SonarWaveletCFGNode(metaclass=IntegratedNode):
DESCRIPTION = "Wavelet CFG function that allows you to apply different CFG strength to different frequencies."
CATEGORY = "model_patches"
RETURN_TYPES = ("MODEL",)
FUNCTION = "go"
_yaml_placeholder = """# YAML or JSON here.
# I recommend reading the documentation at https://github.com/blepping/ComfyUI-sonar/docs/waveletcfg.md
# For wavelet information, see: https://pytorch-wavelets.readthedocs.io/en/latest/index.html
# You may override the fields from the node like start_sigma here.
# This section is basically the CFG scale. (All scales sections use the same format.)
difference:
# Scale for the low frequency components.
yl_scale: 5.0
# Scale (or scales) for high frequency components.
# This can be scalar or a list or list of lists.
# List example:
# yh_scales:
# - [1, 2, 3]
# - fill
# - 5
# You can separately apply a scale to items equal to the wavelet level. Levels go from fine to coarse.
# If the item is a list, the three items correspond to horizontal, vertical, diagonal for DWT. (DTCWT has 6.)
# You can have one "fill" item, this will replicate the item before it however many times is necessary to
# match the wavelet level.
yh_scales: 3.0
# You can optionally include a scales_end block with yl_scale/yh_scales.
# to interpolate from the toplevel scales (can also be in a scales_start blockx if you prefer).
# scales_end:
# yl_scale: 1.0
# yh_scales: 1.0
# The following scheduling parameters only apply if scales_end exists.
# One of linear, logarithmic, exponential, half_cosine, sine
# Sine mode will hit the peak scales_after values in the middle of the range.
schedule: linear
# One of: sampling, enabled_sampling, sigmas, enabled_sigmas, step, enabled_steps
schedule_mode: sampling
# When enabled, flips the schedule percentage. This happens before the schedule is applied
# or any offset/multiplier stuff. If you want to flip the final result you can do something like
# schedule_offset_after: -1.0 and schedule_multiplier_after: -1.0
reverse_schedule: false
# Added to the percentage before the schedule function is applied.
schedule_offset: 0.0
# Applied to the percentage before the schedule function (but after the offset).
schedule_multiplier: 1.0
# Added to the percentage after the schedule function is applied.
schedule_offset_after: 0.0
# Applied to the percentage after the schedule function (but after the offset).
schedule_multiplier_after: 1.0
# Min/max for the final calculated percent. Must be between 0 and 1.
schedule_min: 0.0
schedule_max: 1.0
# If you're a crazy person, you can use non-standard blend modes for interpolating
# the scales. Not recommended.
blend_mode: lerp
# Wavelet type
wave: db4
# Wavelet level
level: 5
### Start of advanced options
# Mode used for padding
padding_mode: symmetric
# Mutually exclusive with DTCWT mode.
use_1d_dwt: false
# Enables DTCWT mode.
use_dtcwt: false
# Configuration for DTCWT, only relevant when enabled.
biort: near_sym_a
qshift: qshift_a
# It's also possible to set these wavelet options with an "inv_"
# prefix: mode, biort, qshift, wave, padding_mode
# One of: noise_norm, noise, denoised
# Normal CFG uses denoised mode. noise_norm divides by the current sigma, noise just uses the raw noise prediction.
target_mode: denoised
# Can be used to scale cond before the difference is calculated.
cond:
yl_scale: 1.0
yh_scales: 1.0
# Can be used to scale uncond before the difference is calculated.
uncond:
yl_scale: 1.0
yh_scales: 1.0
# Can be used to scale the final result after blending.
final:
yl_scale: 1.0
yh_scales: 1.0
# Uses float64 for the wavelets/scaling/blending operations.
# It doesn't seem to hurt performance much, but you can disable it if you want.
high_precision_mode: true
# Inject is just addition which is usually what you want. The normal CFG function is:
# uncond + (cond - uncond) * cfg_scale
difference_blend_mode: inject
difference_blend_strength: 1.0
# Per-rule value, can be enabled to spam your console with information when
# rules activate, dump exactly what high/low scales are used, etc.
verbose: false
# You may include a rules block which is a list of these configuration definitions.
# Include start_sigma/end_sigma parameters. The first matching definition will be used.
# rules:
# - start_sigma: -1.0
"""
INPUT_TYPES = SonarLazyInputTypes(
lambda _yaml_placeholder=_yaml_placeholder: SonarInputTypes()
.req_model()
.req_float_start_sigma(
default=-1.0,
min=-1.0,
tooltip="First sigma wavelet CFG will be used.",
)
.req_float_end_sigma(
default=0.0,
min=0.0,
tooltip="Last sigma wavelet CFG will be used.",
)
.req_field_fallback_mode(
("existing", "own"),
default="existing",
tooltip="Existing mode uses whatever CFG function existed set when this model patch was applied. Own mode does the CFG calculation on its own. The scale will be whatever you set in your guider or sampler.",
)
.req_selectblend_blend_mode(
tooltip="Controls how the result from wavelet CFG is blended with normal CFG. The default of LERP with strength 1.0 uses 100% wavelet CFG.",
)
.req_float_blend_strength(
default=1.0,
tooltip="Controls how the result from wavelet CFG is blended with normal CFG. The default of LERP with strength 1.0 uses 100% wavelet CFG.",
)
.req_yaml(default=_yaml_placeholder)
.opt_field_operation_cond(
"LATENT_OPERATION",
tooltip="Optional latent operation that will be applied to cond. Note: Latent operations only apply if a rule matches.",
)
.opt_field_operation_uncond(
"LATENT_OPERATION",
tooltip="Optional latent operation that will be applied to uncond. Note: Latent operations only apply if a rule matches.",
)
.opt_field_operation_fallback_cfg(
"LATENT_OPERATION",
tooltip="Optional latent operation that will be applied to the fallback (non-wavelet) CFG result. Note: Latent operations only apply if a rule matches.",
)
.opt_field_operation_wavelet_cfg(
"LATENT_OPERATION",
tooltip="Optional latent operation that will be applied to wavelet CFG result. Note: Latent operations only apply if a rule matches.",
)
.opt_field_operation_result(
"LATENT_OPERATION",
tooltip="Optional latent operation that will be applied to the final result, after wavelet and normal CFG are potentially blended. Note: Latent operations only apply if a rule matches.",
),
)
@classmethod
def go(
cls,
*,
model: object,
start_sigma: float,
end_sigma: float,
fallback_mode: str,
blend_mode: str,
blend_strength: float,
yaml_parameters: str,
operation_cond: Callable | None = None,
operation_uncond: Callable | None = None,
operation_fallback_cfg: Callable | None = None,
operation_wavelet_cfg: Callable | None = None,
operation_result: Callable | None = None,
_override_rules_dict: dict | None = None,
) -> tuple[object]:
if start_sigma < 0:
start_sigma = math.inf
if _override_rules_dict is not None:
wavelet_params = _override_rules_dict.copy()
else:
wavelet_params = yaml.safe_load(yaml_parameters)
rules = WCFGRules.build(
**(
{
"start_sigma": start_sigma,
"end_sigma": end_sigma,
"fallback_existing": fallback_mode == "existing",
"blend_mode": blend_mode,
"blend_strength": blend_strength,
}
| wavelet_params
),
)
if len(rules) and rules[0].verbose:
tqdm.write(f"\nWCFG: Using rules: {rules}\n")
model = model.clone()
model.set_model_sampler_cfg_function(
WaveletCFG(
existing_cfg=model.model_options.get("sampler_cfg_function"),
rules=rules,
operation_cond=operation_cond,
operation_uncond=operation_uncond,
operation_fallback_cfg=operation_fallback_cfg,
operation_wavelet_cfg=operation_wavelet_cfg,
operation_result=operation_result,
),
)
return (model,)
NODE_CLASS_MAPPINGS = {
"NoisyLatentLike": NoisyLatentLikeNode,
"SamplerConfigOverride": SamplerNodeConfigOverride,
"SONAR_CUSTOM_NOISE to NOISE": SonarToComfyNOISENode,
"SonarNoiseImage": SonarNoiseImageNode,
"SonarSplitNoiseChain": SonarSplitNoiseChainNode,
"SonarWaveletCFG": SonarWaveletCFGNode,
}
-249
View File
@@ -1,249 +0,0 @@
from __future__ import annotations
from comfy import samplers
from ..external import IntegratedNode
from ..noise import NoiseType
from ..sonar import (
GuidanceConfig,
GuidanceType,
HistoryType,
SonarConfig,
SonarDPMPPSDE,
SonarEuler,
SonarEulerAncestral,
)
from .base import SonarInputTypes, SonarLazyInputTypes
class GuidanceConfigNode(metaclass=IntegratedNode):
DESCRIPTION = "Allows specifying extended guidance parameters for Sonar samplers."
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_float_factor(
default=0.01,
min=-2.0,
max=2.0,
tooltip="Controls the strength of the guidance. You'll generally want to use fairly low values here.",
)
.req_field_guidance_type(
tuple(t.name.lower() for t in GuidanceType),
default="linear",
tooltip="Method to use when calculating guidance. When set to linear, will simply LERP the guidance at the specified strength. When set to Euler, will do a Euler step toward the guidance instead.",
)
.req_int_start_step(
default=0,
min=0,
tooltip="First zero-based step the guidance is active.",
)
.req_int_end_step(
default=9999,
min=0,
tooltip="Last zero-based step the guidance is active.",
)
.req_latent(tooltip="Latent to use as a reference for guidance."),
)
RETURN_TYPES = ("SONAR_GUIDANCE_CFG",)
CATEGORY = "sampling/custom_sampling/samplers"
FUNCTION = "make_guidance_cfg"
@classmethod
def make_guidance_cfg(
cls,
guidance_type,
factor,
start_step,
end_step,
latent,
):
return (
GuidanceConfig(
guidance_type=GuidanceType[guidance_type.upper()],
factor=factor,
start_step=start_step,
end_step=end_step,
latent=latent.get("samples"),
),
)
class SamplerNodeSonarBase:
DESCRIPTION = "Sonar - momentum based sampler node."
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes()
.req_float_momentum(
default=0.95,
min=-0.5,
max=2.5,
tooltip="How much of the normal result to keep during sampling. 0.95 means 95% normal, 5% from history. When set to 1.0 effectively disables momentum.",
)
.req_float_momentum_hist(
default=0.75,
min=-1.5,
max=1.5,
tooltip="How much of the existing history to leave at each update. 0.75 means keep 75%, mix in 25% of the new result.",
)
.req_field_momentum_init(
tuple(t.name for t in HistoryType),
default="ZERO",
tooltip="Initial value used for momentum history. ZERO - history starts zeroed out. RAND - History is initialized with a random value. SAMPLE - History is initialized from the latent at the start of sampling.",
)
.req_float_direction(
default=1.0,
min=-30.0,
max=15.0,
tooltip="Multiplier applied to the result of normal sampling.",
)
.req_field_rand_init_noise_type(
tuple(NoiseType.get_names(skip=(NoiseType.BROWNIAN,))),
default="gaussian",
tooltip="Noise type to use when momentum_init is set to RANDOM.",
)
.opt_field_guidance_cfg_opt(
"SONAR_GUIDANCE_CFG",
tooltip="Optional input for extended guidance parameters.",
),
)
RETURN_TYPES = ("SAMPLER",)
CATEGORY = "sampling/custom_sampling/samplers"
class SamplerNodeSonarEuler(SamplerNodeSonarBase):
RETURN_TYPES = ("SAMPLER",)
CATEGORY = "sampling/custom_sampling/samplers"
FUNCTION = "get_sampler"
@classmethod
def get_sampler(
cls,
*,
momentum,
momentum_hist,
momentum_init,
direction,
rand_init_noise_type,
guidance_cfg_opt=None,
):
cfg = SonarConfig(
momentum=momentum,
init=HistoryType[momentum_init.upper()],
momentum_hist=momentum_hist,
direction=direction,
rand_init_noise_type=NoiseType[rand_init_noise_type.upper()],
guidance=guidance_cfg_opt,
)
return (samplers.KSAMPLER(SonarEuler.sampler, {"sonar_config": cfg}),)
class SamplerNodeSonarEulerAncestral(SamplerNodeSonarEuler):
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes(parent=SamplerNodeSonarEuler)
.req_float_s_noise(
default=1.0,
tooltip="Multiplier for noise added during ancestral or SDE sampling.",
)
.req_float_eta(
default=1.0,
tooltip="Basically controls the ancestralness of the sampler. When set to 0, you will get a non-ancestral (or SDE) sampler.",
)
.req_selectnoise_noise_type(
tooltip="Noise type used during ancestral or SDE sampling. Only used when the custom noise input is not connected.",
)
.opt_customnoise_custom_noise_opt(
tooltip="Optional input for custom noise used during ancestral or SDE sampling. When connected, the built-in noise_type selector is ignored.",
),
)
@classmethod
def get_sampler(
cls,
*,
momentum,
momentum_hist,
momentum_init,
direction,
rand_init_noise_type,
noise_type,
eta,
s_noise,
guidance_cfg_opt=None,
custom_noise_opt=None,
):
cfg = SonarConfig(
momentum=momentum,
init=HistoryType[momentum_init.upper()],
momentum_hist=momentum_hist,
direction=direction,
rand_init_noise_type=NoiseType[rand_init_noise_type.upper()],
noise_type=NoiseType[noise_type.upper()],
custom_noise=custom_noise_opt.clone() if custom_noise_opt else None,
guidance=guidance_cfg_opt,
)
return (
samplers.KSAMPLER(
SonarEulerAncestral.sampler,
{
"sonar_config": cfg,
"eta": eta,
"s_noise": s_noise,
},
),
)
class SamplerNodeSonarDPMPPSDE(SamplerNodeSonarEulerAncestral):
INPUT_TYPES = SonarLazyInputTypes(
lambda: SonarInputTypes(
parent=SamplerNodeSonarEulerAncestral,
).req_selectnoise_noise_type(default="brownian"),
)
@classmethod
def get_sampler(
cls,
*,
momentum,
momentum_hist,
momentum_init,
direction,
rand_init_noise_type,
noise_type,
eta,
s_noise,
guidance_cfg_opt=None,
custom_noise_opt=None,
):
cfg = SonarConfig(
momentum=momentum,
init=HistoryType[momentum_init.upper()],
momentum_hist=momentum_hist,
direction=direction,
rand_init_noise_type=NoiseType[rand_init_noise_type.upper()],
noise_type=NoiseType[noise_type.upper()],
custom_noise=custom_noise_opt.clone() if custom_noise_opt else None,
guidance=guidance_cfg_opt,
)
return (
samplers.KSAMPLER(
SonarDPMPPSDE.sampler,
{
"sonar_config": cfg,
"eta": eta,
"s_noise": s_noise,
},
),
)
NODE_CLASS_MAPPINGS = {
"SamplerSonarEuler": SamplerNodeSonarEuler,
"SamplerSonarEulerA": SamplerNodeSonarEulerAncestral,
"SamplerSonarDPMPPSDE": SamplerNodeSonarDPMPPSDE,
"SonarGuidanceConfig": GuidanceConfigNode,
}
File diff suppressed because it is too large Load Diff
-748
View File
@@ -1,748 +0,0 @@
from __future__ import annotations
import torch
from .. import noise, utils
from ..noise_generation import DistroNoiseGenerator, VoronoiNoiseGenerator
from .base import (
NoiseChainInputTypes,
SonarCustomNoiseNodeBase,
SonarLazyInputTypes,
SonarNormalizeNoiseNodeMixin,
)
class SonarAdvancedPyramidNoiseNode(SonarCustomNoiseNodeBase):
DESCRIPTION = (
"Custom noise type that allows specifying parameters for Pyramid variants."
)
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseChainInputTypes()
.req_field_variant(
(
"highres_pyramid",
"pyramid",
"pyramid_old",
),
default="highres_pyramid",
tooltip="Sets the Pyramid noise variant to generate.",
)
.req_int_iterations(
default=-1,
min=-1,
max=8,
tooltip="When set to -1 will use the variant default.",
)
.req_float_discount(
default=0.0,
tooltip="When set to 0 will use the variant default.",
)
.req_selectscalemode_upscale_mode(
insert_modes=("default",),
default="default",
tooltip="Allows setting the scaling mode for Pyramid noise. Leave on default to use the variant default.",
),
)
@classmethod
def get_item_class(cls):
return noise.AdvancedPyramidNoise
def go(
self,
*,
factor,
rescale,
variant,
iterations,
discount,
upscale_mode,
sonar_custom_noise_opt=None,
):
return super().go(
factor,
rescale=rescale,
sonar_custom_noise_opt=sonar_custom_noise_opt,
variant=variant,
iterations=iterations if iterations != -1 else None,
discount=discount if discount != 0 else None,
upscale_mode=upscale_mode if upscale_mode != "default" else None,
)
class SonarAdvanced1fNoiseNode(SonarCustomNoiseNodeBase):
DESCRIPTION = "Custom noise type that allows specifying parameters for 1f (pink, green, etc) variants."
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseChainInputTypes()
.req_float_alpha(
default=0.25,
tooltip="Similar to the advanced power noise node, positive values increase low frequencies (with colorful effects), negative values increase high frequencies.",
)
.req_float_k(
default=1.0,
tooltip="Currently no description of exactly what it does, it's just another knob you can try turning for a different effect.",
)
.req_float_vertical_factor(
default=1.0,
tooltip="Vertical frequency scaling factor.",
)
.req_float_horizontal_factor(
default=1.0,
tooltip="Horizontal frequency scaling factor.",
)
.req_bool_use_sqrt(
default=True,
tooltip="Controls whether to sqrt when dividing the FFT. Negative hfac/wfac won't work when enabled. Turning it off seems to make the parameters have a much stronger effect.",
),
)
@classmethod
def get_item_class(cls):
return noise.Advanced1fNoise
def go(
self,
*,
factor,
rescale,
alpha,
k,
vertical_factor,
horizontal_factor,
use_sqrt,
sonar_custom_noise_opt=None,
):
return super().go(
factor,
rescale=rescale,
sonar_custom_noise_opt=sonar_custom_noise_opt,
alpha=alpha,
k=k,
hfac=vertical_factor,
wfac=horizontal_factor,
use_sqrt=use_sqrt,
)
class SonarAdvancedPowerLawNoiseNode(SonarCustomNoiseNodeBase):
DESCRIPTION = "Custom noise type that allows specifying parameters for power law (grey, violet, etc) variants."
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseChainInputTypes()
.req_float_alpha(
default=0.5,
tooltip="Similar to the advanced power noise node, positive values increase low frequencies (with colorful effects), negative values increase high frequencies.",
)
.req_field_div_max_dims(
(
"none",
"non-batch",
"spatial",
"all",
"batch",
"channel",
"height",
"width",
),
default="non-batch",
tooltip="If non-none, the noise gets divide by the maximum over this dimension.",
)
.req_bool_use_div_max_abs(
default=True,
tooltip="Only has an effect when div_max_dims is not none. Controls whether maximization is done with the absolute values or raw values.",
)
.req_bool_use_sign(
tooltip="When set, only the sign of the initial noise is used, so -0.5, -0.2 all turn into -1, 0.5, 2, etc all turn into 1.",
),
)
@classmethod
def get_item_class(cls):
return noise.AdvancedPowerLawNoise
MAX_DIMS_MAP = { # noqa: RUF012
"none": None,
"non-batch": (-3, -2, -1),
"spatial": (-2, -1),
"all": (),
"batch": 0,
"channel": 1,
"height": 2,
"width": 3,
}
def go(
self,
*,
factor,
rescale,
alpha,
div_max_dims,
use_sign,
use_div_max_abs,
sonar_custom_noise_opt=None,
):
return super().go(
factor,
rescale=rescale,
sonar_custom_noise_opt=sonar_custom_noise_opt,
alpha=alpha,
div_max_dims=self.MAX_DIMS_MAP.get(div_max_dims),
use_sign=use_sign,
use_div_max_abs=use_div_max_abs,
)
class SonarAdvancedCollatzNoiseNode(SonarCustomNoiseNodeBase):
DESCRIPTION = "Custom noise type that allows specifying parameters for Collatz noise. Very experimental, also very slow. It might just about work as initial noise with non-ancestral sampling but if you get weird results I recommend mixing it with other noise types or possibly using ancestral/SDE sampling."
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseChainInputTypes()
.req_bool_adjust_scale(
default=False,
tooltip="When enabled, the output will be normalized to values between -1 and 1 using the last two dimensions (if there are four or more), otherwise dimensions after the first.",
)
.req_string_chain_length(
default="1, 1, 2, 2, 3, 3",
tooltip="Comma-separated list of chain lengths. Cannot be empty. Iterations will cycle through the list and wrap. Controls the length of Collatz chains. Note: Using a high chain length may be very slow, especially if combined with many iterations.",
)
.req_int_chain_offset(
default=5,
min=0,
max=10000,
tooltip="Uses values starting at the specified offset. Note: This entails generating chains of length chain_length + chain_offset, which may be quite slow if you use high values.",
)
.req_int_iterations(
default=10,
min=1,
max=10000,
tooltip="Number of iterations to run. Warning: Collatz noise (my implementation, anyway) is EXTREMELY slow.",
)
.req_bool_iteration_sign_flipping(
default=True,
tooltip="Controls whether we cycle between flipping the sign on the output from each iteration. May average out weirdness... Or make stuff weirder.",
)
.req_float_rmin(
default=-8000.0,
tooltip="Minimum value a chain can start with. Going as low as -9500 should be safe with float32.",
)
.req_float_rmax(
default=8000.0,
tooltip="Maximum value a chain can start with. I don't recommend going over 9500 if you are using the float32 dtype here as that is where the Collatz chain starts to reach values that can't be accurately represented.",
)
.req_string_dims(
default="-1, -1, -2, -2",
tooltip="Comma-separated list of dimensions. Cannot be empty. May be negative to count from the end of the list. Iterations will cycle through the list and wrap.",
)
.req_bool_flatten(
tooltip="Controls whether dimensions past the current one selected from the dims parameter will get flattened.",
)
.req_field_output_mode(
(
"values",
"ratios",
"mults",
"adds",
"seed_x_mults",
"seed_x_adds",
"noise_x_ratios",
"noise_x_mults",
"noise_x_adds",
),
default="values",
)
.req_float_quantile(
default=0.5,
min=0.0,
max=1.0,
tooltip="The initial output of each iteration will be run through quantile normalization. Setting the parameter to 0 or 1 will disable quantile normalization.",
)
.req_field_quantile_strategy(
tuple(utils.quantile_handlers.keys()),
default="clamp",
tooltip="Determines how to treat outliers. zero and reverse_zero modes are only useful if you're going to do something like add the result to some other noise. zero will return zero for anything outside the quantile range, reverse_zero only _keeps_ the outliers and zeros everything else.",
)
.req_field_noise_dtype(
("float32", "float64", "float16", "bfloat16"),
default="float32",
tooltip="Generally should be left at the default. Only float32 and float64 will work if you have quantile normalization enabled.",
)
.req_float_even_multiplier(
default=0.5,
tooltip="Multiplier to use when the previous link in the chain is even. Collatz uses 0.5 (divides by two) here.",
)
.req_float_even_addition(
default=0.0,
tooltip="Value to add when the previous link in the chain is even. Collatz uses 0 here.",
)
.req_float_odd_multiplier(
default=3.0,
tooltip="Multiplier to use when the previous link in the chain is odd. Collatz uses 3 here.",
)
.req_float_odd_addition(
default=1.0,
tooltip="Value to add when the previous link in the chain is odd. Collatz uses 1 here.",
)
.req_bool_integer_math(
default=True,
tooltip="Controls whether the results during chain generation get truncated to an integer value or not. Should be enabled if you actually want to generate accurate Collatz chains.",
)
.req_bool_add_preserves_sign(
default=True,
tooltip="Controls whether additions use the same sign as the item they're being added to.",
)
.req_bool_break_loops(
default=True,
tooltip="Controls whether the chain resets back to the seed value once it reaches 1 or 0. Generally should be left enabled, otherwise the chain will oscillate between only a few values for the rest of the length (at least with the Collatz rules).",
)
.req_field_seed_mode(
("default", "force_odd", "force_even"),
default="default",
tooltip="Default mode just uses whatever the original seed value was. force_odd/force_even will force it to the specified parity by adding one if it doesn't match. Starting from odd seeds might result in longer chains. Enabling the force modes may cause the initial seeds to exceed rmax by one.",
)
.opt_customnoise_seed_custom_noise(
tooltip="Optional custom noise to use for initial values for Collatz chains. May be slow as it will generate noise according to the original input size and then crop it. Does this noise type have enough warnings about it being slow? Yeah. Connecting something here will probably make it even slower!",
)
.opt_customnoise_mix_custom_noise(
tooltip="Optional custom noise to use with the output modes starting with 'noise'.",
),
)
@classmethod
def get_item_class(cls):
return noise.AdvancedCollatzNoise
def go(
self,
*,
factor: float,
rescale: float,
adjust_scale: bool,
iteration_sign_flipping: bool,
chain_length: int,
iterations: int,
rmin: float,
rmax: float,
flatten: bool,
dims: str,
output_mode: str,
noise_dtype: str,
quantile: float,
quantile_strategy: str,
integer_math: bool,
add_preserves_sign: bool,
even_multiplier: float,
even_addition: float,
odd_multiplier: float,
odd_addition: float,
chain_offset: int,
seed_mode: str,
break_loops: bool,
seed_custom_noise: object | None = None,
mix_custom_noise: object | None = None,
sonar_custom_noise_opt=None,
):
if rmin > rmax:
rmin, rmax = rmax, rmin
dims = tuple(int(i) for i in dims.split(","))
return super().go(
factor,
rescale=rescale,
sonar_custom_noise_opt=sonar_custom_noise_opt,
adjust_scale=adjust_scale,
iteration_sign_flipping=iteration_sign_flipping,
chain_length=tuple(int(i) for i in chain_length.split(",")),
iterations=iterations,
rmin=rmin,
rmax=rmax,
flatten=flatten,
dims=dims,
output_mode=output_mode,
quantile=quantile,
quantile_strategy=quantile_strategy,
integer_math=integer_math,
add_preserves_sign=add_preserves_sign,
even_multiplier=even_multiplier,
even_addition=even_addition,
odd_multiplier=odd_multiplier,
odd_addition=odd_addition,
chain_offset=chain_offset,
break_loops=break_loops,
seed_mode=seed_mode,
noise_dtype={
"float32": torch.float32,
"float64": torch.float64,
"float16": torch.float16,
"bfloat16": torch.bfloat16,
}.get(noise_dtype, torch.float32),
seed_custom_noise=seed_custom_noise,
mix_custom_noise=mix_custom_noise,
)
class SonarAdvancedDistroNoiseNode(SonarCustomNoiseNodeBase):
DESCRIPTION = "Custom noise type that allows specifying parameters for Distro variants. See: https://pytorch.org/docs/stable/distributions.html"
@classmethod
def INPUT_TYPES(cls):
distro_params = DistroNoiseGenerator.distro_params()
variants = tuple(sorted(distro_params.keys()))
combined_params = DistroNoiseGenerator.build_params()
result = super().INPUT_TYPES()
result["required"] |= {
"distribution": (
variants,
{
"tooltip": "Sets the distribution used for noise generation. See: https://pytorch.org/docs/stable/distributions.html",
"default": "uniform",
},
),
"quantile_norm": (
"FLOAT",
{
"default": 0.85,
"min": -1.0,
"max": 1.0,
"step": 0.001,
"round": False,
"tooltip": "When enabled, will normalize generated noise to this quantile (i.e. 0.75 means outliers >75% will be clipped). Set to 1.0 or 0.0 to disable quantile normalization. A value like 0.75 or 0.85 should be reasonable, it really depends on the distribution and how many of the values are extreme. (Experimental) You can use a negative quantile to consider the values closest to zero as extreme.",
},
),
"quantile_norm_mode": (
(
"global",
"batch",
"channel",
"batch_row",
"batch_col",
"nonflat_row",
"nonflat_col",
),
{
"default": "batch",
"tooltip": "Controls what dimensions quantile normalization uses. By default, the noise is flattened first. You can try the nonflat versions but they may have a very strong row/column influence. Only applies when quantile_norm is active.",
},
),
"result_index": (
"STRING",
{
"default": "-1",
"tooltip": "When noise generation returns a batch of items, it will select the specified index. Negative indexes count from the end. Values outside the valid range will be automatically adjusted. You may enter a space-separated list of values for the case where there might be multiple added batch dimensions. Excess batch dimensions are removed from the end, indexe from result_index are used in order so you may want to enter the indexes in reverse order.\nExample: If your noise has shape (1, 4, 3, 3) and two 2-sized batch dims are added resulting in (1, 4, 3, 3, 2, 2) and you wanted index 0 from the first additional batch dimension and 1 from the second you would use result_index: 1 0",
},
),
} | {
k: ("STRING" if isinstance(v["default"], str) else v.get("_ty", "FLOAT"), v)
for k, v in combined_params.items()
}
# print("RESULT:", result)
return result
@classmethod
def get_item_class(cls):
return noise.AdvancedDistroNoise
def go(
self,
*,
factor,
rescale,
distribution,
quantile_norm,
quantile_norm_mode,
result_index,
sonar_custom_noise_opt=None,
**kwargs: dict[str],
):
normdim, normflat = {
"global": (None, True),
"batch": (0, True),
"channel": (1, True),
"batch_row": (2, True),
"batch_col": (3, True),
"nonflat_row": (2, False),
"nonflat_col": (3, False),
}.get(quantile_norm_mode, (1, True))
result_index = tuple(int(v) for v in result_index.split(None))
return super().go(
factor,
rescale=rescale,
sonar_custom_noise_opt=sonar_custom_noise_opt,
distro=distribution,
quantile_norm=quantile_norm,
quantile_norm_dim=normdim,
quantile_norm_flatten=normflat,
result_index=result_index,
**kwargs,
)
class SonarWaveletNoiseNode(
SonarCustomNoiseNodeBase,
SonarNormalizeNoiseNodeMixin,
):
DESCRIPTION = "Custom noise type that allows generating wavelet noise. Very simple explanation of how a single octave works:\n1) Generate some noise.\n2) Scale it down 50%.\n3) Scale it back up to the original size.\n4) Subtract the scaled noise from the original noise.\nScaling the noise down and then back up blurs it, so this is essentially sharpening the noise."
INPUT_TYPES = SonarLazyInputTypes(
lambda: NoiseChainInputTypes()
.req_int_octaves(
default=4,
min=-100,
max=100,
tooltip="Number of octaves to generate. You can use a negative number here to run the octaves in reverse order though it may produce weird results/not work very well.",
)
.req_float_octave_height_factor(
default=0.5,
min=0.001,
tooltip="Wavelet noise works by scaling noise by this factor in each octave, then scaling it back up to the original size. After that, the scaled noise is subtracted from the original noise.",
)
.req_float_octave_width_factor(
default=0.5,
min=0.001,
tooltip="Wavelet noise works by scaling noise by this factor in each octave, then scaling it back up to the original size. After that, the scaled noise is subtracted from the original noise.",
)
.req_selectscalemode_octave_scale_mode(
default="adaptive_avg_pool2d",
tooltip="Scaling mode used within each octave to produce the scaled noise. By default this will be scaling down that octave's noise.",
)
.req_selectscalemode_octave_rescale_mode(
default="bilinear",
tooltip="Scaling mode used within each octave to scale the noise back up to that octave's original size.",
)
.req_selectscalemode_post_octave_rescale_mode(
default="bilinear",
tooltip="Scaling mode used to scale the output of an octave back up to the actual latent size.",
)
.req_float_initial_amplitude(
default=1.0,
tooltip="Basically the strength an octave gets added to the total. This will be scaled by persistance after each octave.",
)
.req_float_persistence(
default=0.5,
tooltip="Multiplier applied to amplitude after each octave. 0.5 means the first octave uses initial_amplitude, the second uses half of that and so on.",
)
.req_float_height_factor(
default=2.0,
min=0.001,
tooltip="Scaling factor for height, calculated after each octave. 2.0 means divide by two. Note: It's possible to use values below 1 here but be careful as it's very easy to reach absurd latent sizes with only a few octaves.",
)
.req_float_width_factor(
tooltip="Scaling factor for width, calculated after each octave. 2.0 means divide by two. Note: It's possible to use values below 1 here but be careful as it's very easy to reach absurd latent sizes with only a few octaves.",
default=2.0,
min=0.001,
)
.req_float_update_blend(
tooltip="Controls how original_noise - scaled_noise is blended with original_noise. The default is to use 100% original_noise - scaled_noise.",
default=1.0,
)
.req_selectblend_update_blend_mode(
insert_modes=("simple_add",),
default="lerp",
tooltip="Controls how the enhanced noise from each octave is blended with that octave's raw noise. With normal wavelet noise there's no blending and you use 100% enhanced noise.",
)
.req_bool_normalize_noise(
tooltip="Controls whether the noise source is normalized before wavelet filtering occurs.",
)
.req_normalizetristate_normalize()
.opt_customnoise_custom_noise(
tooltip="Optional: Custom noise input. If unconnected will default to Gaussian noise. Note: When connected, the noise for all octaves will be generated at the maximum scale and then cropped which may be slow.",
),
)
@classmethod
def get_item_class(cls):
return noise.AdvancedWaveletNoise
def go(
self,
*,
factor,
rescale,
normalize,
octaves: int,
octave_height_factor: float,
octave_width_factor: float,
octave_scale_mode: str,
octave_rescale_mode: str,
post_octave_rescale_mode: str,
initial_amplitude: float,
persistence: float,
height_factor: float,
width_factor: float,
update_blend: float,
update_blend_mode: str,
normalize_noise: bool,
custom_noise=None,
sonar_custom_noise_opt=None,
):
if persistence == 0 or initial_amplitude == 0 or octaves == 0:
raise ValueError(
"Persistence, initial amplitude and octaves must be non-zero",
)
return super().go(
factor,
rescale=rescale,
sonar_custom_noise_opt=sonar_custom_noise_opt,
octaves=octaves,
octave_height_factor=octave_height_factor,
octave_width_factor=octave_width_factor,
octave_scale_mode=octave_scale_mode,
octave_rescale_mode=octave_rescale_mode,
post_octave_rescale_mode=post_octave_rescale_mode,
initial_amplitude=initial_amplitude,
persistence=persistence,
height_factor=height_factor,
width_factor=width_factor,
update_blend=update_blend,
update_blend_function=utils.BLENDING_MODES[update_blend_mode],
normalize=self.get_normalize(normalize),
normalize_noise=normalize_noise,
custom_noise=custom_noise,
)
class SonarAdvancedVoronoiNoiseNode(SonarCustomNoiseNodeBase):
DESCRIPTION = "Voronoi noise is a very weird noise type. The default settings are just borderline usable with SDXL at a 20% ratio with normal Gaussian noise. I recommend reading the section on this noise type in the project documentation (under advanced noise types) as there are too many features to describe in the node itself."
INPUT_TYPES = SonarLazyInputTypes(
lambda _pretty_distance_modes=", ".join( # noqa: B008
sorted(VoronoiNoiseGenerator.voronoi_distance_modes), # noqa: B008
),
_pretty_result_modes=", ".join( # noqa: B008
sorted(VoronoiNoiseGenerator.voronoi_result_modes), # noqa: B008
): NoiseChainInputTypes()
.req_string_n_points(
default="256",
tooltip="Controls the number of features points in the generated noise. Higher generally results in more detail/better results but is slower. May be a comma separated list for each octave (only applicable when octave mode is set to new_features). 2 is the minimum value.",
)
.req_string_distance_mode(
default="euclidean",
placeholder=f"One of: {_pretty_distance_modes}",
tooltip="Distance modes. You can specify a comma-separated list of items which will be used for each octave.\n"
"You can specify an average of multiple distance modes by separating the names with +.\n"
"Some modes can take arguments. Example syntax: modename:argname=value:argname=value\n"
"All modes support scaling their output with dscale (which defaults to 1).\n"
f"Possible distance modes: {_pretty_distance_modes}",
)
.req_float_z_initial(
default=0.0,
tooltip="Initial value for z (depth).",
)
.req_float_z_increment(
default=1.0,
tooltip="Amount z (depth) is incremented when applicable.",
)
.req_float_z_max(
default=9999.0,
tooltip="Maximum difference from the intial value. At that point, z_max_mode will apply. When set to 0, z_increment has no effect and you will get different noise each time you call the noise sampler.",
)
.req_field_z_max_mode(
(
"reset",
"wrap",
"bounce",
),
default="reset",
tooltip="Controls what happens when the z_max limit is hit (see tooltip for z_max). Reset will reset the feature points and z to the initial values. Wrap will reset z to the initial value. Bounce will flip the sign on the increment and do an increment.",
)
.req_string_result_mode(
default="diff2",
placeholder=f"One of: {_pretty_result_modes}",
tooltip="Result modes. You can specify a comma-separated list of items which will be used for each octave.\n"
"You can specify an average of multiple result modes by separating the names with +.\n"
"Some modes can take arguments. Example syntax: modename:argname=value:argname=value\n"
"All modes support scaling their output with rscale (which defaults to 1).\n"
f"Possible result modes: {_pretty_result_modes}",
)
.req_field_octave_mode(
(
"same_features",
"new_features",
"same_invert_odd",
"same_invert_even",
"same_roll_chan_up",
"same_roll_chan_down",
"same_roll_dir_up",
"same_roll_dir_down",
),
default="new_features",
tooltip="Only relevant when generating multiple octaves. Controls whether octaves share a set of feature points or if they are different for each octave (note that this is slower). Modes starting with 'same' will use the same feature points per octave but may transform them.",
)
.req_int_octaves(
default=3,
min=1,
tooltip="Number of octaves of noise to generate.",
)
.req_float_gain(default=0.75)
.req_float_lacunarity(default=2.0)
.req_float_initial_amplitude(default=1.0)
.req_float_initial_scale(default=1.0)
.req_normalizetristate_normalize()
.opt_customnoise(
"custom_noise",
tooltip="Optional input if you want to use some other noise type for the initial feature points. Won't work well with noise types that care about the content of the latent (I think only spectral modulation) or manage their own seed (I believe this only applies to Brownian or if you're using the custom noise parameters node to override seeds/fork the RNG).",
),
)
@classmethod
def get_item_class(cls):
return noise.AdvancedVoronoiNoise
def go(
self,
*,
factor: float,
rescale: float,
n_points: str,
distance_mode: str,
z_initial: float,
z_increment: float,
z_max: float,
z_max_mode: str,
result_mode: str,
octave_mode: str,
octaves: int,
gain: float,
lacunarity: float,
initial_amplitude: float,
initial_scale: float,
normalize: str,
custom_noise=None,
sonar_custom_noise_opt=None,
):
n_points = tuple(int(v) for v in n_points.split(","))
distance_mode = tuple(v.strip() for v in distance_mode.split(","))
result_mode = tuple(v.strip() for v in result_mode.split(","))
return super().go(
factor,
rescale=rescale,
sonar_custom_noise_opt=sonar_custom_noise_opt,
n_points=n_points,
distance_mode=distance_mode,
z_initial=z_initial,
z_increment=z_increment,
z_max=z_max,
z_max_mode=z_max_mode,
result_mode=result_mode,
octave_mode=octave_mode,
octaves=octaves,
gain=gain,
lacunarity=lacunarity,
initial_amplitude=initial_amplitude,
initial_scale=initial_scale,
custom_noise=custom_noise,
normalize=normalize,
)
NODE_CLASS_MAPPINGS = {
"SonarAdvancedPyramidNoise": SonarAdvancedPyramidNoiseNode,
"SonarAdvanced1fNoise": SonarAdvanced1fNoiseNode,
"SonarAdvancedPowerLawNoise": SonarAdvancedPowerLawNoiseNode,
"SonarAdvancedCollatzNoise": SonarAdvancedCollatzNoiseNode,
"SonarAdvancedDistroNoise": SonarAdvancedDistroNoiseNode,
"SonarAdvancedVoronoiNoise": SonarAdvancedVoronoiNoiseNode,
"SonarWaveletNoise": SonarWaveletNoiseNode,
}
+202 -1109
View File
File diff suppressed because it is too large Load Diff
+186 -1470
View File
File diff suppressed because it is too large Load Diff
+186 -133
View File
@@ -16,16 +16,16 @@ from comfy.k_diffusion.sampling import BrownianTreeNoiseSampler
from PIL import Image from PIL import Image
from torch import Tensor from torch import Tensor
from ..noise import CustomNoiseItemBase from .nodes import (
from ..utils import scale_noise
from .base import (
NOISE_INPUT_TYPES_HINT, NOISE_INPUT_TYPES_HINT,
WILDCARD_NOISE, WILDCARD_NOISE,
NoiseChainInputTypes,
SonarCustomNoiseNodeBase, SonarCustomNoiseNodeBase,
SonarInputTypes,
SonarNormalizeNoiseNodeMixin, SonarNormalizeNoiseNodeMixin,
) )
from .noise import CustomNoiseItemBase
from .utils import scale_noise
# ruff: noqa: ANN003, FBT001, FBT002
PREVIEW_FORMAT = comfy.latent_formats.SD15() PREVIEW_FORMAT = comfy.latent_formats.SD15()
@@ -295,14 +295,7 @@ class PowerFilter:
class PowerNoiseItem(CustomNoiseItemBase): class PowerNoiseItem(CustomNoiseItemBase):
def __init__( def __init__(self, factor, *, channel_correlation, power_filter=None, **kwargs):
self,
factor,
*,
channel_correlation,
power_filter=None,
**kwargs: dict,
):
if isinstance(channel_correlation, str): if isinstance(channel_correlation, str):
channel_correlation = torch.tensor( channel_correlation = torch.tensor(
tuple( tuple(
@@ -372,7 +365,6 @@ class PowerNoiseItem(CustomNoiseItemBase):
x: Tensor, x: Tensor,
sigma_min: float | None, sigma_min: float | None,
sigma_max: float | None, sigma_max: float | None,
*,
seed: int | None, seed: int | None,
cpu: bool = True, cpu: bool = True,
normalized=True, normalized=True,
@@ -469,15 +461,7 @@ def rfft2_to_fft2(x):
class PowerFilterNoiseItem(PowerNoiseItem): class PowerFilterNoiseItem(PowerNoiseItem):
def __init__( def __init__(self, factor, *, noise, normalize_noise, normalize_result, **kwargs):
self,
factor,
*,
noise,
normalize_noise,
normalize_result,
**kwargs: dict,
):
super().__init__( super().__init__(
factor, factor,
noise=noise.clone(), noise=noise.clone(),
@@ -496,7 +480,6 @@ class PowerFilterNoiseItem(PowerNoiseItem):
x: Tensor, x: Tensor,
sigma_min: float | None, sigma_min: float | None,
sigma_max: float | None, sigma_max: float | None,
*,
seed: int | None, seed: int | None,
cpu: bool = True, cpu: bool = True,
normalized=True, normalized=True,
@@ -557,69 +540,122 @@ class PowerFilterNoiseItem(PowerNoiseItem):
class SonarPowerNoiseNode(SonarCustomNoiseNodeBase): class SonarPowerNoiseNode(SonarCustomNoiseNodeBase):
DESCRIPTION = "Custom noise type that applies a filter to generated noise." DESCRIPTION = "Custom noise type that applies a filter to generated noise."
INPUT_TYPES = ( @classmethod
NoiseChainInputTypes() def INPUT_TYPES(cls, *args: list, **kwargs: dict):
.req_bool_time_brownian( result = super().INPUT_TYPES(*args, **kwargs)
tooltip="Controls whether brownian noise is used when mix isn't 1.0.", result["required"] |= {
) "time_brownian": (
.req_float_alpha( "BOOLEAN",
default=0.0, {
min=-5.0, "default": False,
max=5.0, "tooltip": "Controls whether brownian noise is used when mix isn't 1.0.",
tooltip="Values above 0 will amplify low frequencies, negative values will amplify high frequencies.", },
) ),
.req_float_max_freq( "alpha": (
default=0.7071, "FLOAT",
min=0.0, {
max=0.7071, "default": 0.0,
tooltip="Maximum frequency to pass through the filter.", "min": -5.0,
) "max": 5.0,
.req_float_min_freq( "step": 0.001,
default=0.0, "round": False,
min=0.0, "tooltip": "Values above 0 will amplify low frequencies, negative values will amplify high frequencies.",
max=0.7071, },
tooltip="Minimum frequency to pass through the filter.", ),
) "max_freq": (
.req_float_stretch( "FLOAT",
default=1.0, {
min=0.01, "default": 0.7071,
max=100.0, "min": 0.0,
tooltip="Stretches the filter's shape by the specified factor.", "max": 0.7071,
) "step": 0.001,
.req_float_rotate( "round": False,
default=0.0, "tooltip": "Maximum frequency to pass through the filter.",
min=-90.0, },
max=90.0, ),
step=5.0, "min_freq": (
tooltip="Rotates the filter.", "FLOAT",
) {
.req_float_pnorm( "default": 0.0,
default=2.0, "min": 0.0,
min=0.125, "max": 0.7071,
max=100.0, "step": 0.001,
step=0.1, "round": False,
tooltip="Factor used for cushioning the band-pass region.", "tooltip": "Minimum frequency to pass through the filter.",
) },
.req_floatpct_mix( ),
default=1.0, "stretch": (
tooltip="Controls the ratio of filtered noise. For example, 0.75 means 75% noise with the filter effects applied, 25% raw noise.", "FLOAT",
) {
.req_float_common_mode( "default": 1.0,
default=0.0, "min": 0.01,
min=-100.0, "max": 100,
max=100.0, "step": 0.1,
tooltip="Attempts to desaturate the latent by injecting the average across channels (controlled by channel_correction). Applied after mix.", "round": False,
) "tooltip": "Stretches the filter's shape by the specified factor.",
.req_string_channel_correlation( },
default="1, 1, 1, 1, 1, 1", ),
tooltip="Comma-separated list of channel correlation strengths.", "rotate": (
) "FLOAT",
.req_field_preview( {
("none", "no_mix", "mix"), "default": 0,
default="none", "min": -90,
tooltip="When enabled, displays a preview of the filter shape and a sample of noise. Mix - previews noise after mix is applied. no_mix - only previews the filtered noise.", "max": 90,
) "step": 5,
) "round": False,
"tooltip": "Rotates the filter.",
},
),
"pnorm": (
"FLOAT",
{
"default": 2,
"min": 0.125,
"max": 100,
"step": 0.1,
"round": False,
"tooltip": "Factor used for cushioning the band-pass region.",
},
),
"mix": (
"FLOAT",
{
"default": 1.0,
"min": 0.0,
"max": 1.0,
"step": 0.001,
"round": False,
"tooltip": "Controls the ratio of filtered noise. For example, 0.75 means 75% noise with the filter effects applied, 25% raw noise.",
},
),
"common_mode": (
"FLOAT",
{
"default": 0.0,
"min": -100.0,
"max": 100.0,
"step": 0.001,
"round": False,
"tooltip": "Attempts to desaturate thelatent by injecting the average across channels (controlled by channel_correction). Applied after mix.",
},
),
"channel_correlation": (
"STRING",
{
"default": "1, 1, 1, 1, 1, 1",
"multiline": False,
"dynamicPrompts": False,
"tooltip": "Comma-separated list of channel correlation strengths.",
},
),
"preview": (
("none", "no_mix", "mix"),
{
"tooltip": "When enabled, displays a preview of the filter shape and a sample of noise. Mix - previews noise after mix is applied. no_mix - only previews the filtered noise.",
},
),
}
return result
@classmethod @classmethod
def get_item_class(cls): def get_item_class(cls):
@@ -628,7 +664,7 @@ class SonarPowerNoiseNode(SonarCustomNoiseNodeBase):
def go( def go(
self, self,
preview="none", preview="none",
**kwargs: dict, **kwargs,
): ):
result = super().go(**kwargs) result = super().go(**kwargs)
if preview == "none": if preview == "none":
@@ -644,7 +680,7 @@ class SonarPowerFilterNoiseNode(SonarPowerNoiseNode, SonarNormalizeNoiseNodeMixi
@classmethod @classmethod
def INPUT_TYPES(cls): def INPUT_TYPES(cls):
result = super().INPUT_TYPES() result = super().INPUT_TYPES(include_rescale=False, include_chain=False)
for k in ( for k in (
"min_freq", "min_freq",
"max_freq", "max_freq",
@@ -825,42 +861,67 @@ class SonarPreviewFilterNode:
FUNCTION = "go" FUNCTION = "go"
OUTPUT_NODE = True OUTPUT_NODE = True
INPUT_TYPES = ( @classmethod
SonarInputTypes() def INPUT_TYPES(cls):
.req_field_sonar_power_filter( return {
"SONAR_POWER_FILTER", "required": {
tooltip="Power Filter to preview.", "sonar_power_filter": (
) "SONAR_POWER_FILTER",
.req_float_filter_gain( {
default=1 / 3, "tooltip": "Power Filter to preview.",
min=0.0, },
tooltip="Gain factor applied to the filter part of the preview.", ),
) "filter_gain": (
.req_float_kernel_gain( "FLOAT",
default=1 / 3, {
min=0.0, "default": 1 / 3,
tooltip="Gain factor applied to the kernel part of the preview.", "min": 0.0,
) "max": 1000000.0,
.req_floatpct_norm_factor( "step": 0.1,
default=1.0, "round": False,
tooltip="Normalization factor applied to the filter before previewing. 1.0 means 100% normalized.", "tooltip": "Gain factor applied to the filter part of the preview.",
) },
.req_field_preview_size( ),
( "kernel_gain": (
"128x128", "FLOAT",
"256x256", {
"384x256", "default": 1 / 3,
"256x384", "min": 0.0,
"768x512", "max": 1000000.0,
"512x768", "step": 0.1,
"768x768", "round": False,
"128x127", "tooltip": "Gain factor applied to the kernel part of the preview.",
"127x128", },
), ),
default="128x128", "norm_factor": (
tooltip="Controls the size of the generated preview. Note: Sizes are in latent pixels. For most models, one latent pixel equals eight pixels", "FLOAT",
) {
) "default": 1.0,
"min": 0.0,
"max": 1.0,
"step": 0.1,
"round": False,
"tooltip": "Normalization factor applied to the filter before previewing. 1.0 means 100% normalized.",
},
),
"preview_size": (
(
"128x128",
"256x256",
"384x256",
"256x384",
"768x512",
"512x768",
"768x768",
"128x127",
"127x128",
),
{
"tooltip": "Controls the size of the generated preview. Note: Sizes are in latent pixels. For most models, one latent pixel equals eight pixels",
},
),
},
}
@classmethod @classmethod
def go( def go(
@@ -883,11 +944,3 @@ class SonarPreviewFilterNode:
), ),
(filt,), (filt,),
) )
NODE_CLASS_MAPPINGS = {
"SonarPowerNoise": SonarPowerNoiseNode,
"SonarPowerFilterNoise": SonarPowerFilterNoiseNode,
"SonarPowerFilter": SonarPowerFilterNode,
"SonarPreviewFilter": SonarPreviewFilterNode,
}
+12 -21
View File
@@ -368,46 +368,34 @@ class SonarGuidanceMixin:
) )
raise ValueError("Sonar: Guidance: Unknown guidance type") raise ValueError("Sonar: Guidance: Unknown guidance type")
@classmethod @staticmethod
def guidance_shift(cls, t: Tensor, ref_latent: Tensor, *, dim=None):
if dim is None:
dim = tuple(range(-(t.ndim - 1), 0))
avg_t = t.mean(dim=dim, keepdim=True)
std_t = t.std(dim=dim, keepdim=True)
return (ref_latent * std_t).add_(avg_t)
@classmethod
def guidance_euler( def guidance_euler(
cls,
sigma: Tensor, sigma: Tensor,
sigma_next: Tensor, sigma_next: Tensor,
x: Tensor, x: Tensor,
denoised: Tensor, denoised: Tensor,
ref_latent: Tensor, ref_latent: Tensor,
factor: float = 0.2, factor: float = 0.2,
*,
do_shift: bool = True,
) -> Tensor: ) -> Tensor:
if torch.equal(sigma, sigma_next): avg_t = denoised.mean(dim=(-3, -2, -1), keepdim=True)
return cls.guidance_linear(x, ref_latent, factor=factor, do_shift=do_shift) std_t = denoised.std(dim=(-3, -2, -1), keepdim=True)
ref_img_shift = ( ref_img_shift = ref_latent * std_t + avg_t
cls.guidance_shift(denoised, ref_latent) if do_shift else ref_latent
)
d = to_d(x, sigma, ref_img_shift) d = to_d(x, sigma, ref_img_shift)
dt = (sigma_next - sigma) * factor dt = (sigma_next - sigma) * factor
return (d * dt).add_(x) return (d * dt).add_(x)
@classmethod @staticmethod
def guidance_linear( def guidance_linear(
cls,
x: Tensor, x: Tensor,
ref_latent: Tensor, ref_latent: Tensor,
factor: float = 0.2, factor: float = 0.2,
*, *,
blend=torch.lerp, blend=torch.lerp,
do_shift: bool = True,
) -> Tensor: ) -> Tensor:
ref_img_shift = cls.guidance_shift(x, ref_latent) if do_shift else ref_latent avg_t = x.mean(dim=(-3, -2, -1), keepdim=True)
std_t = x.std(dim=(-3, -2, -1), keepdim=True)
ref_img_shift = (ref_latent * std_t).add_(avg_t)
return blend(x, ref_img_shift, factor) return blend(x, ref_img_shift, factor)
@@ -480,6 +468,7 @@ class SonarEuler(SonarSampler):
) )
@classmethod @classmethod
@torch.no_grad()
def sampler( def sampler(
cls, cls,
model, model,
@@ -573,6 +562,7 @@ class SonarEulerAncestral(SonarSampler):
) )
@classmethod @classmethod
@torch.no_grad()
def sampler( def sampler(
cls, cls,
model, model,
@@ -770,6 +760,7 @@ class SonarDPMPPSDE(SonarSampler):
) )
@classmethod @classmethod
@torch.no_grad()
def sampler( def sampler(
cls, cls,
model, model,
+39 -634
View File
@@ -1,24 +1,14 @@
from __future__ import annotations from __future__ import annotations
import math import math
import random
from functools import partial
from typing import TYPE_CHECKING, Callable
import torch import torch
from comfy.model_management import device_supports_non_blocking, get_torch_device from comfy.model_management import device_supports_non_blocking
from comfy.utils import common_upscale from comfy.utils import common_upscale
from .external import MODULES as EXT from .external import MODULES as EXT
if TYPE_CHECKING: BLENDING_MODES = {"lerp": torch.lerp}
from collections.abc import Sequence
BLENDING_MODES = {
"lerp": torch.lerp,
"inject": lambda a, b, t: (b * t).add_(a),
"subtract_b": lambda a, b, t: a - b * t,
}
UPSCALE_METHODS = ( UPSCALE_METHODS = (
"bilinear", "bilinear",
"nearest-exact", "nearest-exact",
@@ -26,35 +16,9 @@ UPSCALE_METHODS = (
"area", "area",
"bicubic", "bicubic",
"bislerp", "bislerp",
"adaptive_avg_pool2d",
) )
def blend_scalar(
a: float,
b: float,
t: float,
*,
blend_function: Callable | None = None,
clamp_function: Callable | None = None,
) -> float:
if blend_function is None:
return maybe_apply(
a * (1.0 - t) + b * t,
clamp_function is not None,
clamp_function,
)
return maybe_apply(
blend_function(
*(torch.tensor((v,), device="cpu", dtype=torch.float64) for v in (a, b, t)),
)
.cpu()
.item(),
clamp_function is not None,
clamp_function,
)
def scale_samples( def scale_samples(
samples: torch.Tensor, samples: torch.Tensor,
width: int, width: int,
@@ -62,8 +26,6 @@ def scale_samples(
*, *,
mode: str = "bicubic", mode: str = "bicubic",
) -> torch.Tensor: ) -> torch.Tensor:
if mode == "adaptive_avg_pool2d":
return torch.nn.functional.adaptive_avg_pool2d(samples, (height, width))
return common_upscale(samples, width, height, mode, None) return common_upscale(samples, width, height, mode, None)
@@ -121,393 +83,59 @@ def tensor_to(
return tensor.to(dest, non_blocking=non_blocking) return tensor.to(dest, non_blocking=non_blocking)
def _quantile_norm_scaledown(
noise: torch.Tensor,
nq: torch.Tensor,
*,
dim,
**_kwargs: dict,
) -> torch.Tensor:
noiseabs = noise.abs()
mv = noiseabs.max(dim=dim, keepdim=True).values.clamp(min=1e-06)
return (
noise
if mv.sum().item() == 0
else torch.where(noiseabs > nq, noise * (nq / mv), noise)
)
def _quantile_norm_wave(
noise: torch.Tensor,
nq: torch.Tensor,
*,
preserve_sign: bool = False,
wave_function=torch.sin,
pi_factor: float = 0.5,
wrong_mode: bool = False,
**_kwargs: dict,
) -> torch.Tensor:
if wrong_mode:
multiplier = 1.0 / ((math.pi * pi_factor) / nq)
else:
multiplier = 1.0 / (nq / (math.pi * pi_factor))
pos_mask = noise >= 0
neg_mask = ~pos_mask
result = torch.zeros_like(noise)
result[pos_mask] = wave_function(noise.mul(multiplier))[pos_mask]
result[neg_mask] = wave_function(noise.mul(multiplier))[neg_mask]
result *= nq
return result.copysign(noise) if preserve_sign else result
def _quantile_norm_mode(
noise: torch.Tensor,
nq: torch.Tensor,
*,
dim: int | None,
decimals=1,
**_kwargs: dict,
) -> torch.Tensor:
return torch.where(
noise.abs() > nq,
noise.round(decimals=decimals).mode(dim=dim, keepdim=True).values,
noise,
)
def _quantile_norm_replace(
noise: torch.Tensor,
nq: torch.Tensor,
*,
keep_sign: bool = False,
avoid_sign: bool = False,
count: int = 1,
count_flipping: bool = False,
**_kwargs: dict,
) -> torch.Tensor:
mask = noise.abs() <= nq
candidates = noise[mask].flatten()
n_candidates = candidates.numel()
idxs = torch.arange(noise.numel()) % n_candidates
cresult = candidates[idxs]
if count < 2:
candidates = cresult
else:
multiplier = 1.0 / count
cresult = cresult * multiplier # noqa: PLR6104
for i in range(1, count):
cresult += (
candidates[
torch.roll(
idxs,
i if not count_flipping or (i % 2) == 0 else -i,
dims=(-1,),
)
]
* multiplier
)
candidates = cresult.reshape(noise.shape)
if keep_sign or avoid_sign:
candidates = candidates.copysign_(noise.neg() if avoid_sign else noise)
return torch.where(mask, noise, candidates)
quantile_handlers = {
"clamp": lambda noise, nq, **_kwargs: noise.clamp(-nq, nq),
"scale_down": _quantile_norm_scaledown,
"tanh": lambda noise, nq, **_kwargs: noise.tanh().mul_(nq.abs()),
"tanh_outliers": lambda noise, nq, **_kwargs: torch.where(
noise.abs() > nq,
noise.tanh().mul_(nq.abs()),
noise,
),
"sigmoid_keepsign": lambda noise, nq, **_kwargs: noise.sigmoid()
.mul_(nq.abs())
.copysign(noise),
"sigmoid": lambda noise, nq, **_kwargs: noise.sigmoid()
.mul_(nq.abs() * 2)
.sub_(nq.abs()),
"sigmoid_outliers": lambda noise, nq, **_kwargs: torch.where(
noise.abs() > nq,
noise.sigmoid().mul_(nq.abs()).copysign(noise),
noise,
),
"sin": partial(_quantile_norm_wave, wave_function=torch.sin),
"sin_wholepi": partial(
_quantile_norm_wave,
wave_function=torch.sin,
pi_factor=1.0,
),
"sin_keepsign": partial(
_quantile_norm_wave,
wave_function=torch.sin,
preserve_sign=True,
),
"sin_wrong": partial(_quantile_norm_wave, wave_function=torch.sin, wrong_mode=True),
"sin_wrong_wholepi": partial(
_quantile_norm_wave,
wave_function=torch.sin,
pi_factor=1.0,
wrong_mode=True,
),
"sin_wrong_keepsign": partial(
_quantile_norm_wave,
wave_function=torch.sin,
preserve_sign=True,
wrong_mode=True,
),
"cos": partial(_quantile_norm_wave, wave_function=torch.cos),
"cos_wholepi": partial(
_quantile_norm_wave,
wave_function=torch.cos,
pi_factor=1.0,
),
"cos_keepsign": partial(
_quantile_norm_wave,
wave_function=torch.cos,
preserve_sign=True,
),
"cos_wrong": partial(_quantile_norm_wave, wave_function=torch.cos, wrong_mode=True),
"cos_wrong_wholepi": partial(
_quantile_norm_wave,
wave_function=torch.cos,
pi_factor=1.0,
wrong_mode=True,
),
"cos_wrong_keepsign": partial(
_quantile_norm_wave,
wave_function=torch.cos,
preserve_sign=True,
wrong_mode=True,
),
"atan": lambda noise, nq, **_kwargs: noise.atan().mul_(nq.abs() / (math.pi / 2)),
"tenth": lambda noise, nq, **_kwargs: torch.where(
noise.abs() > nq,
noise * 0.1,
noise,
),
"half": lambda noise, nq, **_kwargs: torch.where(
noise.abs() > nq,
noise * 0.5,
noise,
),
"zero": lambda noise, nq, **_kwargs: torch.where(noise.abs() > nq, 0, noise),
"reverse_zero": lambda noise, nq, **_kwargs: torch.where(
noise.abs() >= nq,
noise,
0,
),
"mean": lambda noise, nq, *, dim, **_kwargs: torch.where(
noise.abs() > nq,
noise.mean(dim=dim, keepdim=True),
noise,
),
"median": lambda noise, nq, *, dim, **_kwargs: torch.where(
noise.abs() > nq,
noise.median(dim=dim, keepdim=True).values,
noise,
),
"mode_1dec": partial(_quantile_norm_mode, decimals=1),
"mode_2dec": partial(_quantile_norm_mode, decimals=2),
"replace": _quantile_norm_replace,
"replace_keepsign": partial(_quantile_norm_replace, keep_sign=True),
"replace_avoidsign": partial(_quantile_norm_replace, avoid_sign=True),
"replace_2pt": partial(_quantile_norm_replace, count=2),
"replace_3pt": partial(_quantile_norm_replace, count=3),
"replace_2pt_flip": partial(_quantile_norm_replace, count=2, count_flipping=True),
"replace_3pt_flip": partial(_quantile_norm_replace, count=3, count_flipping=True),
"replace_2pt_keepsign": partial(
_quantile_norm_replace,
count=2,
keep_sign=True,
),
"replace_3pt_keepsign": partial(
_quantile_norm_replace,
count=3,
keep_sign=True,
),
"replace_2pt_flip_keepsign": partial(
_quantile_norm_replace,
count=2,
count_flipping=True,
keep_sign=True,
),
"replace_3pt_flip_keepsign": partial(
_quantile_norm_replace,
count=3,
count_flipping=True,
keep_sign=True,
),
"replace_2pt_avoidsign": partial(
_quantile_norm_replace,
count=2,
avoid_sign=True,
),
"replace_3pt_avoidsign": partial(
_quantile_norm_replace,
count=3,
avoid_sign=True,
),
"replace_2pt_flip_avoidsign": partial(
_quantile_norm_replace,
count=2,
count_flipping=True,
avoid_sign=True,
),
"replace_3pt_flip_avoidsign": partial(
_quantile_norm_replace,
count=3,
count_flipping=True,
avoid_sign=True,
),
}
# Initial version based on Studentt distribution normalizatino from https://github.com/Clybius/ComfyUI-Extra-Samplers/
def quantile_normalize( def quantile_normalize(
noise: torch.Tensor, noise: torch.Tensor,
*, *,
quantile: float | tuple | list = 0.75, quantile: float = 0.75,
dim: int | None = 1, dim: int | None = 1,
flatten: bool = True, flatten: bool = True,
nq_fac: float = 1.0, nq_fac: float = 1.0,
pow_fac: float = 0.5, pow_fac: float = 0.5,
strategy: str = "clamp",
strategy_handler=None,
eps=1e-08,
) -> torch.Tensor: ) -> torch.Tensor:
if noise.numel() == 0: if quantile is None or quantile <= 0 or quantile >= 1:
return noise return noise
if isinstance(quantile, (tuple, list)):
for q in quantile:
noise = quantile_normalize(
noise=noise,
quantile=q,
dim=dim,
flatten=flatten,
nq_fac=nq_fac,
pow_fac=pow_fac,
strategy=strategy,
strategy_handler=strategy_handler,
)
return noise
if quantile is None or quantile >= 1 or quantile <= -1:
return noise
centered = quantile < 0
absquantile = abs(quantile)
orig_shape = noise.shape orig_shape = noise.shape
if noise.ndim > 1 and flatten: if isinstance(quantile, (tuple, list)):
flatnoise = noise.flatten(start_dim=dim) quantile = torch.tensor(
else:
flatten = False
flatnoise = noise
handler = (
quantile_handlers.get(strategy)
if strategy_handler is None
else strategy_handler
)
if handler is None:
raise ValueError("Unknown strategy")
if not centered:
nq = torch.quantile(
flatnoise.abs(),
quantile, quantile,
dim=-1 if flatten else dim, device=noise.device,
keepdim=True, dtype=noise.dtype,
)
nq = nq.mul_(nq_fac).add_(eps)
# print(f"\nNQ: {nq}")
noise = handler(
flatnoise,
nq,
orig_noise=noise,
dim=dim,
flatten=flatten,
) )
qdim = dim
if noise.ndim > 1 and flatten:
if qdim is not None and qdim >= noise.ndim:
qdim = 1 if noise.ndim > 2 else None
if qdim is None:
flatdim = 0
elif qdim in {0, 1}:
flatdim = qdim + 1
elif qdim in {2, 3}:
noise = noise.movedim(qdim, 1)
tempshape = noise.shape
flatdim = 2
else:
raise ValueError(
"Cannot handling quantile normalization flattening dims > 3",
)
else: else:
absnoise = flatnoise.abs() flatdim = None
maxabs = absnoise.amax(dim=-1 if flatten else dim, keepdim=True) nq = torch.quantile(
proxy = flatnoise.sign().mul_(maxabs - absnoise) (noise if flatdim is None else noise.flatten(start_dim=flatdim)).abs(),
nq_proxy = torch.quantile( quantile,
proxy.abs(), dim=-1,
absquantile,
dim=-1 if flatten else dim,
keepdim=True,
)
nq_proxy = nq_proxy.mul_(nq_fac).add_(eps)
# print(f"\nNQ proxy: {nq_proxy}")
out_proxy = handler(
proxy,
nq_proxy,
orig_noise=noise,
dim=dim,
flatten=flatten,
)
noise = out_proxy.sign().mul_(maxabs - out_proxy.abs())
if pow_fac not in {0.0, 1.0}:
noise = noise.abs().pow_(pow_fac).copysign(noise)
return noise if noise.shape == orig_shape else noise.reshape(orig_shape)
def normalize_to_scale(
latent: torch.Tensor,
target_min: float,
target_max: float,
*,
dim=(-3, -2, -1),
eps: float = 1e-07,
) -> torch.Tensor:
min_val, max_val = (
latent.amin(dim=dim, keepdim=True),
latent.amax(dim=dim, keepdim=True),
) )
normalized = latent - min_val nq_shape = tuple(nq.shape) + (1,) * (noise.ndim - nq.ndim)
normalized /= (max_val - min_val).add_(eps) nq = nq.mul_(nq_fac).reshape(*nq_shape)
return ( noise = noise.clamp(-nq, nq)
normalized.mul_(target_max - target_min) noise = torch.copysign(
.add_(target_min) torch.pow(torch.abs(noise), pow_fac),
.clamp_(target_min, target_max) noise,
) )
if flatdim is not None and qdim in {2, 3}:
return (
def normalize_to_scale_adv( noise.reshape(tempshape).movedim(1, qdim).reshape(orig_shape).contiguous()
t: torch.Tensor,
*,
min_pos: float,
max_pos: float,
min_neg: float,
max_neg: float,
dim=(-3, -2, -1),
) -> torch.Tensor:
skip_pos = max_pos <= 0 or min_pos >= max_pos
skip_neg = min_neg >= 0 or min_neg >= max_neg
neg_idxs, pos_idxs = t < 0.0, t > 0.0
result = torch.zeros_like(t)
if skip_neg:
result[neg_idxs] = t[neg_idxs]
elif torch.any(neg_idxs):
neg_values = t[neg_idxs]
if max_neg >= 0:
max_neg = neg_values.max().detach().cpu().item()
result[neg_idxs] = normalize_to_scale(
neg_values,
target_min=min_neg,
target_max=max_neg,
dim=dim,
) )
if skip_pos: return noise
result[pos_idxs] = t[pos_idxs]
elif torch.any(pos_idxs):
pos_values = t[pos_idxs]
if min_pos < 0:
min_pos = pos_values.min().detach().cpu().item()
result[pos_idxs] = normalize_to_scale(
pos_values,
target_min=min_pos,
target_max=max_pos,
dim=dim,
)
return result
def adjust_slice(s: slice, size: int, offset: int) -> slice: def adjust_slice(s: slice, size: int, offset: int) -> slice:
@@ -566,226 +194,3 @@ def crop_samples(
wslice = adjust_slice(wslice, tw, offset_width) wslice = adjust_slice(wslice, tw, offset_width)
hslice = adjust_slice(hslice, th, offset_height) hslice = adjust_slice(hslice, th, offset_height)
return tensor[..., hslice, wslice] return tensor[..., hslice, wslice]
def fallback(val, default=None):
return val if val is not None else default
# Pattern break algorithm adapted from https://github.com/Extraltodeus/noise_latent_perlinpinpin
def pattern_break(
noise: torch.Tensor,
*,
percentage: float = 0.5,
detail_level=0.0,
restore_scale=True,
blend_function=torch.lerp,
):
orig_dtype = noise.dtype
if restore_scale:
orig_min, orig_max = noise.min().item(), noise.max().item()
noise_normed = normalize_to_scale(noise.to(dtype=torch.float32), -1.0, 1.0, dim=())
result = torch.remainder(torch.abs(noise_normed) * 1000000, 11) / 11
result = (
((1 + detail_level / 10) * torch.erfinv(2 * result - 1) * (2**0.5))
.mul_(0.2)
.clamp_(-1, 1)
)
if restore_scale:
result = normalize_to_scale(result, orig_min, orig_max, dim=())
return blend_function(noise, result, percentage).to(dtype=orig_dtype)
def elementwise_shuffle_by_dim(
t: torch.Tensor,
*,
dim: int = -1,
prob: float = 1.0,
no_identity: bool = False,
generator=None,
) -> torch.Tensor:
orig_shape = t.shape
device = t.device
num_positions = math.prod(orig_shape[:dim] + orig_shape[dim + 1 :])
num_elements = orig_shape[dim]
tensor_2d = t.permute(
*tuple(d for d in range(t.dim()) if d != dim),
dim,
).reshape(-1, num_elements)
rand_perms = (
torch.arange(num_elements, device=device).expand(num_positions, -1).clone()
)
if prob < 1.0:
mask = torch.rand(num_positions, device=device, generator=generator) < prob
else:
mask = torch.ones(num_positions, device=device, dtype=torch.bool)
if no_identity:
offsets = torch.randint(
1,
num_elements,
(num_positions,),
device=device,
generator=generator,
)
rand_perms[mask] = (
torch.arange(num_elements, device=device) + offsets[mask][:, None]
) % num_elements
else:
rand_perms[mask] = torch.rand(
num_positions,
num_elements,
device=device,
generator=generator,
)[mask].argsort(dim=1)
shuffled_2d = torch.gather(tensor_2d, 1, rand_perms)
shuffled = shuffled_2d.reshape(
*orig_shape[:dim],
*orig_shape[dim + 1 :],
orig_shape[dim],
)
return shuffled.permute(
*tuple(d for d in range(t.dim() - 1) if d < dim),
t.dim() - 1,
*tuple(d for d in range(t.dim() - 1) if d >= dim),
).contiguous()
def trunc_decimals(x: torch.Tensor, decimals: int = 3) -> torch.Tensor:
x_i = x.trunc()
x_f = x - x_i
scale = 10.0**decimals
return x_i.add_(x_f.mul_(scale).trunc_().mul_(1.0 / scale))
def maybe_apply(val, cond, fun):
return fun(val) if cond else val
def maybe_apply_kwargs(d: dict | None, cond, fun, *, default=None):
return default if d is None or not cond else fun(**d)
def tensor_item(val: torch.Tensor | float, *, collapse_function=torch.max) -> float:
if isinstance(val, torch.Tensor):
return float(collapse_function(val).detach().cpu().item())
return float(val)
# Does not handle out of order or duplicated sigmas.
def step_from_sigmas(
sigma: float | torch.Tensor,
sigmas: torch.Tensor,
*,
decimals: int | None = 4,
output_decimals: int = 2,
) -> float | None:
sigma = tensor_item(sigma)
sigmas = sigmas.detach().cpu()
if sigmas.ndim == 2:
sigmas = sigmas.max(dim=0).values
elif sigmas.ndim != 1:
errstr = f"Unexpected number of dimensions in sigmas, should be 1 or 2 but got shape {sigmas.shape}"
raise ValueError(errstr)
sigmas = sigmas[:-1]
if not len(sigmas) or torch.any(sigmas <= 0):
return None
if decimals is not None:
sigmas = sigmas.round(decimals=decimals)
sigma = round(sigma, decimals)
sigma_min, sigma_max = sigmas.aminmax()
if not sigma_min <= sigma <= sigma_max:
return None
max_idx = len(sigmas) - 1
idx = int(tensor_item((sigmas - sigma).abs().argmin()))
idx_sigma = tensor_item(sigmas[idx])
if decimals is not None:
idx_sigma = round(idx_sigma, decimals)
if sigma == idx_sigma:
return float(idx)
# Between sigmas, but guaranteed to be in range here.
idx_low, idx_high = (idx, idx - 1) if sigma > idx_sigma else (idx + 1, idx)
if idx_low < 0 or idx_high < 0 or idx_low > max_idx or idx_high > max_idx:
return None
sigma_low, sigma_high = tensor_item(sigmas[idx_low]), tensor_item(sigmas[idx_high])
step_diff = sigma_high - sigma_low
if step_diff == 0:
return float(idx)
pct = 1.0 - ((sigma - sigma_low) / step_diff)
return round(idx_high + pct, output_decimals)
def clamp_float(val: float, minval=0.0, maxval=1.0) -> float:
return max(minval, min(val, maxval))
def filter_dict(d: dict, keep: set | Sequence, *, recursive: bool = False) -> dict:
return {
k: v if not (recursive and isinstance(v, dict)) else filter_dict(v, keep)
for k, v in d.items()
if k in keep
}
class RNGStates:
DEFAULT_GPU_TYPE = get_torch_device().type
def __init__(
self,
device_types: set | str | Sequence | None = None,
*,
add_defaults: bool = True,
):
if device_types is None:
device_types = set()
elif isinstance(device_types, str):
device_types = {device_types}
elif not isinstance(device_types, set):
device_types = set(device_types)
if add_defaults:
device_types = device_types | {"python", "cpu", self.DEFAULT_GPU_TYPE} # noqa: PLR6104
self.rng_states = self.get_states(device_types)
def update(self):
self.rng_states = self.get_states(set(self.rng_states))
@staticmethod
def get_states(device_types: set) -> dict:
return {
k: torch.get_rng_state()
if k == "cpu"
else (
random.getstate()
if k == "python"
else getattr(torch, k).get_rng_state()
)
for k in device_types
if k in {"python", "cpu"} or hasattr(torch, k)
}
def set_states(self, *, update: bool = True, override_states: dict | None = None):
states = self.rng_states if override_states is None else override_states
new_states = {}
for k, v in states.items():
if isinstance(v, torch.Tensor):
v = v.clone() # noqa: PLW2901
if k == "cpu":
new_states[k] = v
torch.set_rng_state(v)
continue
if k == "python":
new_states[k] = v
random.setstate(v)
continue
tm = getattr(torch, k, None)
if tm is not None:
new_states[k] = v
tm.set_rng_state(v)
if update:
self.rng_states = new_states
-842
View File
@@ -1,842 +0,0 @@
from __future__ import annotations
import math
from enum import Enum, auto
from typing import TYPE_CHECKING, Callable, NamedTuple
import torch
from tqdm import tqdm
from . import utils
from .wavelet_functions import (
Wavelet,
expand_yh_scales,
wavelet_blend,
wavelet_scaling,
)
if TYPE_CHECKING:
from collections.abc import Sequence
def pretty_non_default(obj: NamedTuple, *, defaults: object | None = None) -> str:
result = ", ".join(
f"{fn}={fv.pretty_non_default()}"
if hasattr(fv, "pretty_non_default")
else f"{fn}={fv!r}"
for fn, fv in ((_fn, getattr(obj, _fn)) for _fn in obj._fields)
if defaults is None or fv != getattr(defaults, fn)
)
return f"{obj.__class__.__name__}({result})"
class WCFGSchedule(Enum):
LINEAR = auto()
LOGARITHMIC = auto()
LOG = LOGARITHMIC
EXPONENTIAL = auto()
EXP = EXPONENTIAL
HALF_COSINE = auto()
SINE = auto()
SIN = SINE
def interp(self, val: float) -> float:
val = utils.clamp_float(val)
if self == WCFGSchedule.LINEAR:
return val
if self == WCFGSchedule.LOGARITHMIC:
result = 0.0 if val == 0 else math.log(val) + 1.0
elif self == WCFGSchedule.EXPONENTIAL:
result = math.exp(val) - 1.0
elif self == WCFGSchedule.HALF_COSINE:
result = 1.0 - ((1.0 + math.cos(val * math.pi)) / 2)
elif self == WCFGSchedule.SINE:
result = math.sin(val * math.pi)
else:
raise ValueError("Bad interpolation schedule!?")
return utils.clamp_float(result)
class WCFGSchedMode(Enum):
SAMPLING = auto()
ENABLED_SAMPLING = auto()
SIGMAS = auto()
ENABLED_SIGMAS = auto()
STEP = auto()
ENABLED_STEPS = auto()
# Aliases
MODEL_SAMPLING = SAMPLING
ENABLED_MODEL_SAMPLING = ENABLED_SAMPLING
SIGMA_RANGE = SIGMAS
ENABLED_SIGMA_RANGE = ENABLED_SIGMAS
class WCFGTarget(Enum):
DENOISED = auto()
NOISE = auto()
NOISE_NORM = auto()
class WCFGPercentages(NamedTuple):
sigma: float
sigma_min: float
sigma_max: float
sigma_first: float | None
sigma_last: float | None
steps: int | None
step: float | None
step_first: int | None
step_last: int | None
pct_sampling: float
pct_enabled_sampling: float
pct_sigmas: float | None
pct_enabled_sigmas: float | None
pct_steps: float | None
pct_enabled_steps: float | None
def invert(self) -> WCFGPercentages:
return self._replace(
pct_sampling=1.0 - self.pct_sampling,
pct_enabled_sampling=1.0 - self.pct_enabled_sampling,
pct_sigmas=None if self.pct_sigmas is None else 1.0 - self.pct_sigmas,
pct_enabled_sigmas=None
if self.pct_enabled_sigmas is None
else 1.0 - self.pct_enabled_sigmas,
pct_steps=None if self.pct_steps is None else 1.0 - self.pct_steps,
pct_enabled_steps=None
if self.pct_enabled_steps is None
else 1.0 - self.pct_enabled_steps,
)
def pct_from_schedmode(self, mode: WCFGSchedMode) -> float | None:
if mode == WCFGSchedMode.MODEL_SAMPLING:
return self.pct_sampling
if mode == WCFGSchedMode.SIGMA_RANGE:
return self.pct_sigmas
if mode == WCFGSchedMode.ENABLED_MODEL_SAMPLING:
return self.pct_enabled_sampling
if mode == WCFGSchedMode.ENABLED_SIGMA_RANGE:
return self.pct_enabled_sigmas
if mode == WCFGSchedMode.STEP:
if self.pct_steps is None:
raise RuntimeError("Step percentage not available")
return self.pct_steps
raise ValueError("Unknown mode")
@classmethod
def build(
cls,
*,
ms: object,
start_sigma: float,
end_sigma: float,
sigma: float,
sigmas: torch.Tensor | None,
**_kwargs: dict,
) -> WCFGPercentages:
if start_sigma < end_sigma:
raise ValueError("start/end sigmas out of order")
sigma_max = ms.sigma_max.detach().item()
sigma_min = ms.sigma_min.detach().item()
start_sigma = min(sigma_max, start_sigma)
end_sigma = min(max(sigma_min, end_sigma), sigma_max)
sigma = min(max(sigma, sigma_min), sigma_max)
rstart = torch.tensor(start_sigma)
rend = torch.tensor(end_sigma)
pct_start = 1.0 - (ms.timestep(rstart) / 999).clamp(0, 1).detach().item()
pct_end = 1.0 - (ms.timestep(rend) / 999).clamp(0, 1).detach().item()
pct_curr = (
1.0 - (ms.timestep(torch.tensor(sigma)) / 999).clamp(0, 1).detach().item()
)
pct_range_curr = (pct_curr - pct_start) / (pct_end - pct_start)
if sigmas is not None:
if sigmas.ndim == 2:
sigmas = sigmas.max(dim=0).values
elif sigmas.ndim != 1:
raise ValueError("Unexpected number of dimensions for sample_sigmas")
sigmas = sigmas.detach().cpu()
sigma_first = sigmas[0].item()
sigma_last = sigmas[-2].item()
if sigma_first <= sigma_last:
raise ValueError(
"Cannot handle non-descending sigmas (possibly Restart or unsampling)",
)
pct_sigmas = (sigma_first - sigma) / (sigma_first - sigma_last)
start_sigma = min(start_sigma, sigma_first)
end_sigma = max(end_sigma, sigma_last)
sigma = min(max(sigma, sigma_last), sigma_first)
if start_sigma == end_sigma:
pct_enabled_sigmas = 1.0
else:
pct_enabled_sigmas = (start_sigma - sigma) / (start_sigma - end_sigma)
steps = len(sigmas) - 1
if steps > 1:
step = utils.step_from_sigmas(sigma, sigmas)
pct_steps = step / (steps - 1) if step is not None else None
enabled_steps = torch.arange(len(sigmas), dtype=torch.int32)[
(sigmas <= start_sigma) & (sigmas >= end_sigma)
]
if len(enabled_steps) > 1:
step_first = enabled_steps[0].item()
step_last = enabled_steps[-1].item()
pct_enabled_steps = (step - step_first) / (step_last - step_first)
else:
step = 0.0
pct_steps = 1.0
step_first = step_last = None
pct_enabled_steps = None
else:
pct_enabled_sigmas = pct_sigmas = None
step = steps = None
pct_enabled_steps = pct_steps = None
sigma_first = sigma_last = None
return WCFGPercentages(
pct_sampling=pct_curr,
pct_enabled_sampling=pct_range_curr,
pct_sigmas=pct_sigmas,
pct_enabled_sigmas=pct_enabled_sigmas,
pct_steps=pct_steps,
pct_enabled_steps=pct_enabled_steps,
sigma=sigma,
sigma_first=sigma_first,
sigma_last=sigma_last,
sigma_min=sigma_min,
sigma_max=sigma_max,
steps=steps,
step=step,
step_first=step_first,
step_last=step_last,
)
class WCFGScales(NamedTuple):
yl_scale: float = 1.0
yh_scales: float | Sequence = 1.0
def get_scales(
self,
*_args: list,
verbose: bool = False,
**_kwargs: dict,
) -> WCFGScales:
if verbose:
tqdm.write(f"WCFG: {self.pretty_scales()}")
return self
def apply_scales(
self,
yl: torch.Tensor,
yh: Sequence,
) -> tuple[torch.Tensor, Sequence]:
return wavelet_scaling(yl, yh, yl_scale=self.yl_scale, yh_scales=self.yh_scales)
def get_and_apply_scales(
self,
pcts: WCFGPercentages,
yl: torch.Tensor,
yh: Sequence,
*,
verbose: bool = False,
) -> tuple[torch.Tensor, Sequence]:
return self.get_scales(pcts, yh, verbose=verbose).apply_scales(yl, yh)
def pretty_yh_scales(self, *, target=None) -> str:
if target is None:
target = self.yh_scales
if isinstance(target, float):
return f"{target:.4f}"
result = ", ".join(
self.pretty_yh_scales(target=val)
if isinstance(val, (list, tuple))
else (val if isinstance(val, str) else f"{val:.4f}")
for val in target
)
return f"({result})"
def pretty_scales(self):
return f"low={self.yl_scale:.4f}, high={self.pretty_yh_scales()}"
class WCFGScheduledScale(NamedTuple):
schedule: WCFGSchedule = WCFGSchedule.LINEAR
schedule_mode: WCFGSchedMode = WCFGSchedMode.ENABLED_MODEL_SAMPLING
schedule_offset: float = 0.0
schedule_offset_after: float = 0.0
schedule_multiplier: float = 1.0
schedule_multiplier_after: float = 1.0
reverse_schedule: bool = False
reverse_schedule_after: bool = False
schedule_min: float = 0.0
schedule_max: float = 1.0
@classmethod
def build(cls, **kwargs: dict) -> WCFGScheduledScale:
schedule = kwargs.pop("schedule", DEFAULT_SCHEDULEDSCALE.schedule)
if isinstance(schedule, str):
schedule = getattr(WCFGSchedule, schedule.upper())
schedule_mode = kwargs.pop(
"schedule_mode",
DEFAULT_SCHEDULEDSCALE.schedule_mode,
)
if isinstance(schedule_mode, str):
schedule_mode = getattr(WCFGSchedMode, schedule_mode.upper())
return WCFGScheduledScale(
schedule=schedule,
schedule_mode=schedule_mode,
**utils.filter_dict(kwargs, cls._fields),
)
def get_b_scale(self, pcts: WCFGPercentages) -> float:
if self.reverse_schedule:
pcts = pcts.invert()
pct = pcts.pct_from_schedmode(self.schedule_mode)
if pct is None:
raise RuntimeError("Couldn't get percentage")
pct = utils.clamp_float(
(
self.schedule.interp(
utils.clamp_float(
(pct + self.schedule_offset) * self.schedule_multiplier,
),
)
+ self.schedule_offset_after
)
* self.schedule_multiplier_after,
minval=utils.clamp_float(self.schedule_min),
maxval=utils.clamp_float(self.schedule_max),
)
if self.reverse_schedule_after:
pct = utils.clamp_float(1.0 - pct)
return pct
def pretty_non_default(self) -> str:
return pretty_non_default(self, defaults=DEFAULT_SCHEDULEDSCALE)
DEFAULT_SCHEDULEDSCALE = WCFGScheduledScale()
class WCFGScalesRange(NamedTuple):
scales_start: WCFGScales = WCFGScales()
scales_end: WCFGScales | None = None
scheduler: WCFGScheduledScale | None = None
blend_mode: str = "lerp"
@classmethod
def build(cls, **kwargs: dict) -> WCFGScales | WCFGScalesRange:
scales_start = kwargs.pop("scales_start", None)
if scales_start is None:
scales_start = {
"yl_scale": kwargs.pop("yl_scale", 1.0),
"yh_scales": kwargs.pop("yh_scales", 1.0),
}
scales_end = utils.filter_dict(kwargs.pop("scales_end", {}), WCFGScales._fields)
if not scales_end or scales_end == scales_start:
return WCFGScales(
yl_scale=scales_start.get("yl_scale", 1.0),
yh_scales=scales_start.get("yh_scales", 1.0),
)
blend_mode = kwargs.pop("blend_mode", "lerp")
return WCFGScalesRange(
scales_start=WCFGScales(**scales_start),
scales_end=WCFGScales(**scales_end),
scheduler=utils.maybe_apply_kwargs(
kwargs,
bool(scales_end),
WCFGScheduledScale.build,
),
blend_mode=blend_mode,
)
def get_scales(
self,
pcts: WCFGPercentages,
yh: Sequence,
*,
verbose: bool = False,
) -> WCFGScales:
if self.scales_end is None or self.scheduler is None:
return self.scales_start.get_scales()
pct = self.scheduler.get_b_scale(pcts)
if verbose:
tqdm.write(f"WCFG: pct={pct:.4f}, percentages: {pcts}")
start, end = self.scales_start, self.scales_end
simple_blend = self.blend_mode == "lerp"
if pct <= 0 and simple_blend:
simple_result = start
elif pct >= 1 and simple_blend:
simple_result = end
else:
simple_result = None
if simple_result is not None:
if verbose:
tqdm.write(
f"WCFG: {simple_result.pretty_scales()}",
)
return simple_result
start_yh_scales = expand_yh_scales(yh, yh_scales=start.yh_scales)
end_yh_scales = expand_yh_scales(yh, yh_scales=end.yh_scales)
blend_function = (
None if self.blend_mode == "lerp" else utils.BLENDING_MODES[self.blend_mode]
)
yl_scale = utils.blend_scalar(
start.yl_scale,
end.yl_scale,
pct,
blend_function=blend_function,
)
yh_scales = tuple(
tuple(
utils.blend_scalar(os, oe, pct, blend_function=blend_function)
for os, oe in zip(bs, be)
)
for bs, be in zip(start_yh_scales, end_yh_scales)
)
result = WCFGScales(yl_scale=yl_scale, yh_scales=yh_scales)
if verbose:
tqdm.write(
f"WCFG: {result.pretty_scales()}",
)
return result
def apply_scales(
self,
yl: torch.Tensor,
yh: Sequence,
) -> tuple[torch.Tensor, Sequence]:
return self.scales_start.apply_scales(yl, yh)
def get_and_apply_scales(
self,
pcts: WCFGPercentages,
yl: torch.Tensor,
yh: Sequence,
*,
verbose: bool = False,
) -> tuple[torch.Tensor, Sequence]:
return self.get_scales(pcts, yh, verbose=verbose).apply_scales(yl, yh)
def pretty_non_default(self) -> str:
return pretty_non_default(self, defaults=DEFAULT_SCALESRANGE)
DEFAULT_SCALESRANGE = WCFGScalesRange()
class WCFGScheduledFloat(NamedTuple):
value_start: float
value_end: float | None = None
scheduler: WCFGScheduledScale | None = None
@classmethod
def build(
cls,
val: float | dict,
*,
default_start: float | None = None,
default_end: float | None = None,
**_kwargs: dict,
) -> WCFGScheduledFloat:
if isinstance(val, float):
return WCFGScheduledFloat(value_start=val)
if not isinstance(val, dict):
raise TypeError("Bad type for scheduled float value")
val = val.copy()
value_start = val.pop("value_start", default_start)
value_end = val.pop("value_end", default_end)
if not isinstance(value_start, (float, int)):
raise TypeError("Bad type for scheduled float start_value")
if value_end is None:
return WCFGScheduledFloat(value_start=val)
if not isinstance(value_end, (float, int)):
raise TypeError("Bad type for scheduled float end_value")
return WCFGScheduledFloat(
value_start=float(value_start),
value_end=float(value_end),
scheduler=WCFGScheduledScale.build(**val),
)
def get_value(self, pcts: WCFGPercentages) -> float:
if self.value_end is None or self.scheduler is None:
return self.value_start
pct = self.scheduler.get_b_scale(pcts)
return (1.0 - pct) * self.value_start + pct * self.value_end
class WCFGWaveletSettings(NamedTuple):
wave: str = "db4"
level: int = 5
padding_mode: str = "symmetric"
use_1d_dwt: bool = False
use_dtcwt: bool = False
biort: str = "near_sym_a"
qshift: str = "qshift_a"
inv_wave: str | None = None
inv_padding_mode: str | None = None
inv_biort: str | None = None
inv_qshift: str | None = None
@classmethod
def build(cls, **kwargs: dict) -> WCFGWaveletSettings:
return WCFGWaveletSettings(**utils.filter_dict(kwargs, cls._fields))
def make_wavelet(self, **kwargs: dict) -> Wavelet:
return Wavelet(
wave=self.wave,
level=self.level,
mode=self.padding_mode,
use_1d_dwt=self.use_1d_dwt,
use_dtcwt=self.use_dtcwt,
biort=self.biort,
qshift=self.qshift,
inv_wave=self.inv_wave,
inv_mode=self.inv_padding_mode,
inv_biort=self.inv_biort,
inv_qshift=self.inv_qshift,
**kwargs,
)
def pretty_non_default(self) -> str:
return pretty_non_default(self, defaults=DEFAULT_WAVELETSETTINGS)
DEFAULT_WAVELETSETTINGS = WCFGWaveletSettings()
class WCFGRule(NamedTuple):
start_sigma: float = math.inf
end_sigma: float = 0.0
verbose: bool = False
blend_mode: str = "lerp"
blend_strength: WCFGScheduledFloat = WCFGScheduledFloat(1.0)
fallback_existing: bool = True
target_mode: WCFGTarget = WCFGTarget.DENOISED
diff: WCFGScalesRange | WCFGScales | None = None
cond: WCFGScalesRange | WCFGScales | None = None
uncond: WCFGScalesRange | WCFGScales | None = None
final: WCFGScalesRange | WCFGScales | None = None
wavelet: WCFGWaveletSettings = DEFAULT_WAVELETSETTINGS
high_precision_mode: bool = True
difference_blend_mode: str = "inject"
difference_blend_strength: WCFGScheduledFloat = WCFGScheduledFloat(1.0)
@classmethod
def build(cls, **kwargs: dict) -> WCFGRule:
target_mode = kwargs.pop("target_mode", DEFAULT_RULE.target_mode)
if isinstance(target_mode, str):
target_mode = getattr(WCFGTarget, target_mode.upper())
difference = kwargs.pop("diff", None)
if difference is None:
difference = kwargs.pop("difference", None)
if difference is not None:
difference = WCFGScalesRange.build(**difference)
cond = kwargs.pop("cond", None)
if cond is not None:
cond = WCFGScalesRange.build(**cond)
uncond = kwargs.pop("uncond", None)
if uncond is not None:
uncond = WCFGScalesRange.build(**uncond)
final = kwargs.pop("final", None)
if final is not None:
final = WCFGScalesRange.build(**final)
blend_strength = kwargs.pop("blend_strength", 1.0)
if not isinstance(blend_strength, (float, int, dict)):
raise TypeError("Bad type for blend_strength, must be float or dict")
difference_blend_strength = kwargs.pop("difference_blend_strength", 1.0)
if not isinstance(difference_blend_strength, (float, int, dict)):
raise TypeError(
"Bad type for difference_blend_strength, must be float or dict",
)
return WCFGRule(
target_mode=target_mode,
diff=difference,
cond=cond,
uncond=uncond,
final=final,
blend_strength=WCFGScheduledFloat(blend_strength),
difference_blend_strength=WCFGScheduledFloat(difference_blend_strength),
wavelet=WCFGWaveletSettings.build(**kwargs),
**utils.filter_dict(kwargs, cls._fields),
)
def make_wavelet(self, **kwargs: dict) -> Wavelet:
return self.wavelet.make_wavelet(**kwargs)
def get_and_apply_scales(
self,
name: str,
pcts: WCFGPercentages,
yl: torch.Tensor,
yh: Sequence,
*,
verbose: bool = False,
) -> tuple[torch.Tensor, Sequence]:
scales = getattr(self, name).get_scales(pcts, yh)
if verbose and (scales.yl_scale != 1.0 or scales.yh_scales != 1.0):
tqdm.write(
f"WCFG: scales({name:>6}): {scales.pretty_scales()}",
)
return scales.apply_scales(yl, yh)
def pretty_non_default(self) -> str:
return pretty_non_default(self, defaults=DEFAULT_RULE)
DEFAULT_RULE = WCFGRule()
class WCFGRules(NamedTuple):
rules: Sequence = ()
def __len__(self) -> int:
return len(self.rules)
def __getitem__(self, idx: int) -> WCFGRule:
return self.rules[idx]
def __bool__(self) -> bool:
return bool(self.rules)
def get_rule(self, sigma: float) -> WCFGRule | None:
for rule in self.rules:
if (
rule.end_sigma
<= sigma
<= (math.inf if rule.start_sigma < 0 else rule.start_sigma)
):
return rule
return None
@classmethod
def build(cls, **params: dict) -> WCFGRules:
params = params.copy()
rules = params.pop("rules", ())
rule_1 = WCFGRule.build(**params)
other_rules = (WCFGRule.build(**rparams) for rparams in rules)
return WCFGRules(rules=(rule_1, *other_rules))
class WCFGContext(NamedTuple):
cond: torch.Tensor
uncond: torch.Tensor
x: torch.Tensor
sigma: torch.Tensor
wavelet: Wavelet
dtype: torch.dtype
op_kwargs: dict
class WaveletCFG:
def __init__(
self,
*,
existing_cfg: Callable | None,
rules: WCFGRules,
operation_cond: Callable | None = None,
operation_uncond: Callable | None = None,
operation_fallback_cfg: Callable | None = None,
operation_wavelet_cfg: Callable | None = None,
operation_result: Callable | None = None,
):
self.wavelet_cache = {}
self.rules = rules
self.fallback_cfg_function = (
existing_cfg
if existing_cfg is not None and (not rules or rules[0].fallback_existing)
else self.basic_cfg_function
)
self.operation_cond = operation_cond
self.operation_uncond = operation_uncond
self.operation_fallback_cfg = operation_fallback_cfg
self.operation_wavelet_cfg = operation_wavelet_cfg
self.operation_result = operation_result
@staticmethod
def basic_cfg_function(args: dict) -> torch.Tensor:
x, scale = args["input"], args["cond_scale"]
uncond, cond = args["uncond_denoised"], args["cond_denoised"]
return x - (cond - uncond).mul_(scale).add_(uncond)
@staticmethod
def maybe_op(
t: torch.Tensor,
mop: Callable | None,
**kwargs: dict,
) -> torch.Tensor:
return (
t
if mop is None
else mop(
latent=t,
**(kwargs if getattr(mop, "EXTENDED_LATENT_OPERATION", None) else {}),
)
)
def get_context(self, *, rule: WCFGRule, args: dict) -> WCFGContext:
sigma_orig = sigma = args["sigma"]
rule_id = id(rule)
x = args["input"]
if x.ndim == 3 and not rule.wavelet.use_1d_dwt:
raise RuntimeError("Enable use_1d_dwt mode for 3D latents.")
if x.ndim < 3:
raise RuntimeError(
"Wavelet CFG can't handle latents with 2 or less dimensions.",
)
if sigma.ndim != x.ndim:
sigma = sigma.reshape(x.shape[0], *((1,) * (x.ndim - sigma.ndim)))
if rule.target_mode in {WCFGTarget.NOISE, WCFGTarget.NOISE_NORM}:
cond, uncond = args["cond"], args["uncond"]
if rule.target_mode == WCFGTarget.NOISE_NORM:
cond = cond / sigma # noqa: PLR6104
uncond = uncond / sigma # noqa: PLR6104
elif rule.target_mode == WCFGTarget.DENOISED:
cond, uncond = args["cond_denoised"], args["uncond_denoised"]
else:
raise ValueError("Bad target mode")
op_kwargs = {
"sigma": sigma_orig,
"cond": cond,
"uncond": uncond,
"cond_scale": args["cond_scale"],
"raw_args": args,
}
cond = self.maybe_op(cond, self.operation_cond, **op_kwargs)
uncond = self.maybe_op(uncond, self.operation_uncond, **op_kwargs)
eff_dtype = torch.float64 if rule.high_precision_mode else x.dtype
wavelet = self.wavelet_cache.get(rule_id)
if wavelet is None:
wavelet = rule.make_wavelet()
self.wavelet_cache[rule_id] = wavelet
wavelet = wavelet.to(device=x.device, dtype=eff_dtype)
if rule.wavelet.use_1d_dwt:
cond = cond.flatten(start_dim=2)
uncond = uncond.flatten(start_dim=2)
elif x.ndim > 4:
cond = cond.flatten(start_dim=1, end_dim=cond.ndim - 3)
uncond = uncond.flatten(start_dim=1, end_dim=uncond.ndim - 3)
return WCFGContext(
cond=cond,
uncond=uncond,
x=x,
sigma=sigma,
wavelet=wavelet,
dtype=eff_dtype,
op_kwargs=op_kwargs,
)
def process_output(
self,
*,
result: torch.Tensor,
rule: WCFGRule,
ctx: WCFGContext,
) -> torch.Tensor:
x_shape = ctx.x.shape
if rule.wavelet.use_1d_dwt:
result = result[..., : ctx.cond.shape[2]].reshape(x_shape)
elif ctx.x.ndim > 4:
result = result[..., : x_shape[-2], : x_shape[-1]].reshape(x_shape)
else:
result = result[tuple(slice(None, sz) for sz in x_shape)]
if rule.target_mode == WCFGTarget.DENOISED:
result = ctx.x - result
elif rule.target_mode == WCFGTarget.NOISE_NORM:
result *= ctx.sigma
return self.maybe_op(result, self.operation_wavelet_cfg, **ctx.op_kwargs)
@classmethod
def wavelet_cfg(
cls,
*,
rule: WCFGRule,
ctx: WCFGContext,
pcts: WCFGPercentages,
) -> torch.Tensor:
verbose = rule.verbose
diff_blend_function = utils.BLENDING_MODES[rule.difference_blend_mode]
condw = ctx.wavelet.forward(ctx.cond.to(dtype=ctx.dtype))
uncondw = ctx.wavelet.forward(ctx.uncond.to(ctx.dtype))
if rule.cond is not None:
condw = rule.get_and_apply_scales("cond", pcts, *condw, verbose=verbose)
if rule.uncond is not None:
uncondw = rule.get_and_apply_scales(
"uncond",
pcts,
*uncondw,
verbose=verbose,
)
diffw = wavelet_blend(
condw,
uncondw,
yl_factor=1.0,
blend_function=lambda a, b, _t: a - b,
)
if rule.diff is not None:
diffw = rule.get_and_apply_scales("diff", pcts, *diffw, verbose=verbose)
resultw = wavelet_blend(
uncondw,
diffw,
yl_factor=rule.difference_blend_strength.get_value(pcts),
blend_function=diff_blend_function,
)
if rule.final is not None:
resultw = rule.get_and_apply_scales(
"final",
pcts,
*resultw,
verbose=verbose,
)
return ctx.wavelet.inverse(*resultw).to(dtype=ctx.x.dtype)
def __call__(self, args: dict) -> torch.Tensor:
sigma = args["sigma"]
sigma_f = sigma.max().item()
rule = self.rules.get_rule(sigma_f)
if rule is None:
return self.fallback_cfg_function(args)
if rule.verbose:
tqdm.write(
f"\nWCFG: Rule matched, sigma={sigma_f:.4f}, rule={rule.pretty_non_default()}",
)
blend_function = utils.BLENDING_MODES[rule.blend_mode]
model = args["model"]
pcts = WCFGPercentages.build(
ms=model.model_sampling,
start_sigma=rule.start_sigma,
end_sigma=rule.end_sigma,
sigma=sigma_f,
sigmas=args.get("model_options", {})
.get("transformer_options", {})
.get("sample_sigmas"),
)
wcfg_blend = rule.blend_strength.get_value(pcts)
if rule.blend_mode == "lerp" and wcfg_blend == 0:
return self.maybe_op(
self.fallback_cfg_function(args),
self.operation_fallback_cfg,
sigma=sigma,
cond=args["cond_denoised"],
uncond=args["uncond_denoised"],
raw_args=args,
)
ctx = self.get_context(rule=rule, args=args)
result = self.wavelet_cfg(rule=rule, ctx=ctx, pcts=pcts)
if rule.blend_mode != "lerp" or wcfg_blend != 1.0:
normal_result = self.maybe_op(
self.fallback_cfg_function(args),
self.operation_fallback_cfg,
**ctx.op_kwargs,
)
if rule.target_mode == WCFGTarget.DENOISED:
normal_result = ctx.x - normal_result
elif rule.target_mode == WCFGTarget.NOISE_NORM:
normal_result /= ctx.sigma
result = blend_function(normal_result, result, wcfg_blend)
result = self.process_output(result=result, ctx=ctx, rule=rule)
return self.maybe_op(
result,
self.operation_result,
**ctx.op_kwargs,
).contiguous()
-238
View File
@@ -1,238 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Callable
import torch
from .utils import fallback
if TYPE_CHECKING:
from collections.abc import Sequence
try:
import pytorch_wavelets as ptwav
import pywt
HAVE_WAVELETS = True
except ImportError:
ptwav = None
pywt = None
HAVE_WAVELETS = False
class Wavelet:
DEFAULT_MODE = "symmetric"
DEFAULT_LEVEL = 3
DEFAULT_WAVE = "db4"
DEFAULT_USE_1D_DWT = False
DEFAULT_USE_DTCWT = False
DEFAULT_QSHIFT = "qshift_a"
DEFAULT_BIORT = "near_sym_a"
def __init__(
self,
*,
wave: str = DEFAULT_WAVE,
level: int = DEFAULT_LEVEL,
mode: str = DEFAULT_MODE,
use_1d_dwt: bool = DEFAULT_USE_1D_DWT,
use_dtcwt: bool = DEFAULT_USE_DTCWT,
biort: str = DEFAULT_BIORT,
qshift: str = DEFAULT_QSHIFT,
inv_wave: str | None = None,
inv_mode: str | None = None,
inv_biort: str | None = None,
inv_qshift=None,
device: str | torch.device | None = None,
):
if not HAVE_WAVELETS:
raise RuntimeError(
"Wavelet noise requires the pytorch_wavelets package to be installed in your Python environment",
)
inv_wave = fallback(inv_wave, wave)
inv_mode = fallback(inv_mode, mode)
inv_biort = fallback(inv_biort, biort)
inv_qshift = fallback(inv_qshift, qshift)
if use_dtcwt:
fwdfun, invfun = ptwav.DTCWTForward, ptwav.DTCWTInverse
elif use_1d_dwt:
fwdfun, invfun = ptwav.DWT1DForward, ptwav.DWT1DInverse
else:
fwdfun, invfun = ptwav.DWTForward, ptwav.DWTInverse
if use_dtcwt:
self._wavelet_forward = fwdfun(
J=level,
mode=mode,
biort=biort,
qshift=qshift,
)
self._wavelet_inverse = invfun(
mode=inv_mode,
biort=inv_biort,
qshift=inv_qshift,
)
else:
self._wavelet_forward = fwdfun(J=level, wave=wave, mode=mode)
self._wavelet_inverse = invfun(wave=inv_wave, mode=inv_mode)
if device is not None:
self._wavelet_forward = self._wavelet_forward.to(device=device)
self._wavelet_inverse = self._wavelet_inverse.to(device=device)
def forward(
self,
t: torch.Tensor,
*,
forward_function: Callable | None = None,
) -> tuple[torch.Tensor, tuple]:
return fallback(forward_function, self._wavelet_forward)(t)
def inverse(
self,
yl: torch.Tensor,
yh: tuple,
*,
inverse_function: Callable | None = None,
two_step_inverse: bool = False,
) -> torch.Tensor:
inverse_function = fallback(inverse_function, self._wavelet_inverse)
if not two_step_inverse:
return inverse_function((yl, yh))
result = inverse_function((torch.zeros_like(yl), yh))
result += inverse_function((
yl,
tuple(torch.zeros_like(yh_band) for yh_band in yh),
))
return result
def to(self, *args: list, copy: bool = False, **kwargs: dict) -> Wavelet:
o = Wavelet.__new__(Wavelet) if copy else self
o._wavelet_forward = self._wavelet_forward.to(*args, **kwargs) # noqa: SLF001
o._wavelet_inverse = self._wavelet_inverse.to(*args, **kwargs) # noqa: SLF001
return o
@staticmethod
def wavelist() -> tuple:
return tuple(pywt.wavelist()) if HAVE_WAVELETS else ()
@staticmethod
def biortlist() -> tuple:
return (
("near_sym_a", "near_sym_b", "antonini", "legall") if HAVE_WAVELETS else ()
)
@staticmethod
def qshiftlist() -> tuple:
return (
("qshift_a", "qshift_b", "qshift_c", "qshift_d", "qshift_06")
if HAVE_WAVELETS
else ()
)
@staticmethod
def modelist() -> tuple:
return (
(
"symmetric",
"zero",
"reflect",
"replicate",
"periodization",
"periodic",
"constant",
)
if HAVE_WAVELETS
else ()
)
def expand_yh_scales(
yh: Sequence,
*,
yh_scales: float | Sequence = 1.0,
) -> float | tuple:
yhlen = len(yh)
yh_shape = yh[0].shape
# Doesn't make sense to target orientations for 1D DWD (3D here).
olen = yh_shape[2] if len(yh_shape) > 3 else 1
# print(f"\nSIZES: yhlen={yhlen}, olen={olen}, yh_shape={yh[0].shape}")
if isinstance(yh_scales, (float, int)):
return ((float(yh_scales),) * olen,) * yhlen
otemplate = (1.0,) * olen
yh_scales = tuple(
(float(band),) * olen
if isinstance(band, (float, int))
else (
(
*(float(i) for i in band[:olen]),
*otemplate[: olen - len(band[:olen])],
)
if isinstance(band, (tuple, list))
else band
)
for band in yh_scales
)
if "fill" in yh_scales:
fillidx = yh_scales.index("fill")
if "fill" in yh_scales[fillidx + 1 :]:
raise ValueError("Only one fill allowed.")
if fillidx == 0 or len(yh_scales) < 2:
raise ValueError(
"Invalid fill value, cannot be in the first position or the only item.",
)
yhslen = len(yh_scales)
if yhslen - 1 < yhlen:
# Need to pad.
fill = (yh_scales[fillidx - 1],) * (yhlen - (len(yh_scales) - 1))
yh_scales = (*yh_scales[:fillidx], *fill, *yh_scales[fillidx + 1 :])
else:
# Just remove the "fill".
yh_scales = (*yh_scales[:fillidx], *yh_scales[fillidx + 1 :])
return yh_scales[:yhlen]
def wavelet_scaling(
yl: torch.Tensor,
yh: Sequence,
yl_scale: float | torch.Tensor,
yh_scales: float | Sequence | None,
*,
in_place: bool = False,
) -> tuple:
if not in_place:
yl = yl.clone()
yh = tuple(yhband.clone() for yhband in yh)
if yl_scale != 1.0:
yl *= yl_scale
yh_scales = expand_yh_scales(
yh,
yh_scales=yh_scales if yh_scales is not None else 1.0,
)
for hscale, ht in zip(yh_scales, yh):
if isinstance(hscale, (int, float)):
ht *= hscale # noqa: PLW2901
continue
for lidx in range(min(ht.shape[2], len(hscale))):
ht[:, :, lidx] *= hscale[lidx]
return (yl, yh)
def wavelet_blend(
a: tuple,
b: tuple,
*,
yl_factor: torch.Tensor | float,
blend_function: Callable,
yh_factor: torch.Tensor | float | None = None,
yh_blend_function: Callable | None = None,
) -> tuple:
if not isinstance(yl_factor, torch.Tensor):
yl_factor = a[0].new_full((1,), yl_factor)
if yh_factor is None:
yh_factor = yl_factor
elif not isinstance(yh_factor, torch.Tensor):
yh_factor = a[0].new_full((1,), yh_factor)
yh_blend_function = fallback(yh_blend_function, blend_function)
return (
blend_function(a[0], b[0], yl_factor),
tuple(yh_blend_function(ta, tb, yh_factor) for ta, tb in zip(a[1], b[1])),
)
-2
View File
@@ -29,12 +29,10 @@ ignore = [
"FBT002", "FBT002",
"PLR0912", "PLR0912",
"PLR0913", "PLR0913",
"PLR0914",
"PLR0915", "PLR0915",
"PLR0917", "PLR0917",
"PLR2004", "PLR2004",
"T201", "T201",
"TID252",
"TRY003", "TRY003",
"N802", "N802",
"N999", "N999",