Compare commits
57
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1ece658da | ||
|
|
d3b485342d | ||
|
|
38fe739a7e | ||
|
|
6005b4208a | ||
|
|
6fc85f55f9 | ||
|
|
f514274656 | ||
|
|
7ee12dae75 | ||
|
|
e791ba54ef | ||
|
|
6a2e98b172 | ||
|
|
e4cdcefdb7 | ||
|
|
7e82f9e075 | ||
|
|
b1512efd98 | ||
|
|
163aa069b7 | ||
|
|
ad621254fa | ||
|
|
7742ded9bf | ||
|
|
dac98129ca | ||
|
|
044490f2e5 | ||
|
|
5ecfcb01d3 | ||
|
|
d6e6f11319 | ||
|
|
067048906b | ||
|
|
716b0d749a | ||
|
|
03fe373c10 | ||
|
|
2e4bf47017 | ||
|
|
77747875b0 | ||
|
|
cb773cd851 | ||
|
|
67a479a65d | ||
|
|
2528e6ae79 | ||
|
|
4ed521fdcc | ||
|
|
0cc120c0ab | ||
|
|
d65c096438 | ||
|
|
cc30fde46c | ||
|
|
1618093e22 | ||
|
|
d5031a8ea7 | ||
|
|
ec0ad9faf3 | ||
|
|
76091dc006 | ||
|
|
a734aeb5a2 | ||
|
|
e58189e5f0 | ||
|
|
f1a8decc55 | ||
|
|
74421f7fbc | ||
|
|
bc1e4b0874 | ||
|
|
3e73d2e352 | ||
|
|
0aa45f98ff | ||
|
|
aac7a05bb2 | ||
|
|
ac1951101f | ||
|
|
fdbbd970e7 | ||
|
|
9db4fbe514 | ||
|
|
2d8125e011 | ||
|
|
076d80918a | ||
|
|
bf43d36bac | ||
|
|
fd5d0ef6a1 | ||
|
|
0595a6d304 | ||
|
|
305720c66e | ||
|
|
f0e52ec054 | ||
|
|
442bde294a | ||
|
|
764f04a6a7 | ||
|
|
2481e7263b | ||
|
|
470b38231f |
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 blepping
|
||||
Copyright (c) 2024 blepping <https://github.com/blepping>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,93 +1,920 @@
|
||||
# Overly Complicated Sampling
|
||||
Wildly unsound and experimental sampling for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
|
||||
|
||||
## Description
|
||||
Experimental and mathematically unsound (but fun!) sampling for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
|
||||
|
||||
Very unstable, experimental and mathematically unsound sampling for ComfyUI.
|
||||
**Status**: In flux, may be useful but likely to change/break workflows frequently. Mainly for advanced users.
|
||||
|
||||
Current status: In flux, not suitable for general use.
|
||||
Feel free create a question in Discussions for usage help: [OCS Q&A Discussion](https://github.com/blepping/comfyui_overly_complicated_sampling/discussions/categories/q-a)
|
||||
|
||||
_Note for Flux users_: Set `cfg1_uncond_optimization: true` in the `model` block for the main `OCS Sampler` as Flux does not use CFG. CFG++ and alt CFG++ features do not work with Flux.
|
||||
|
||||
## Features
|
||||
|
||||
* Many different samplers.
|
||||
* Allows scheduling samplers (i.e. run `euler` for steps 1-4, then switch to `dpmpp_sde`).
|
||||
* CFG++ support (for some samplers).
|
||||
* Native support for Restart sigmas. (Restarts do not currently work with RF models like Flux.)
|
||||
* Supports custom noise types.
|
||||
* Immiscible noise for sampling and Restart. See https://arxiv.org/abs/2406.12303 (note that it was designed for training not inference).
|
||||
* Allows splitting/combining steps in various ways for (potentially) more accurate sampling.
|
||||
* Supports Diffrax, torchdiffeq, torchode and torchsde solver backends. (SDE mode not recommended currently.)
|
||||
* Many tuneable parameters to play with.
|
||||
* Supports ancestral sampling (in a janky way) for rectified flow models like Flux, works for most basic samplers: does not work for SDE samplers currently.
|
||||
* Built in safe expression language that allows filtering and manipulating nearly all parameters during sampling.
|
||||
|
||||
## Credits
|
||||
|
||||
I can move code around but sampling math and creating samplers generally beyond my ability. I didn't write any of the original samplers:
|
||||
|
||||
* Euler, Heun++2, DPMPP SDE, DPMPP 2S, gradient estimation, RES multistep, DPM++ 2m, 2m SDE and 3m SDE samplers based on ComfyUI's implementation.
|
||||
* Reversible Heun, Reversible Heun 1s, RES, Trapezoidal, Bogacki, Reversible Bogacki, RK4, RKF45, dynamic RK(4), SENS and Euler Dancing samplers based on implementation from [https://github.com/Clybius/ComfyUI-Extra-Samplers](https://github.com/Clybius/ComfyUI-Extra-Samplers).
|
||||
* TTM JVP sampler based on implementation written by Katherine Crowson (but yoinked from the Extra-Samplers repo mentioned above).
|
||||
* Distance sampler based on implementation from https://github.com/Extraltodeus/DistanceSampler
|
||||
* IPNDM, IPNDM_V and DEIS adapted from https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py (I used the Comfy version as a reference).
|
||||
* PingPong sampler idea from https://github.com/ace-step/ACE-Step/ (implementation also referenced from that source).
|
||||
* Normal substep merge strategy based on implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
* Immiscible noise processing based on implementation from https://github.com/kohya-ss/sd-scripts/pull/1395 and https://github.com/yhli123/Immiscible-Diffusion - idea for sampling with it and implementation help from https://github.com/Clybius
|
||||
* Precedence climbing (Pratt) expression parser based on implementation from https://github.com/andychu/pratt-parsing-demo
|
||||
|
||||
Please notify me if I somehow missed appropriately crediting any code used here, any such ommissions are unintentional.
|
||||
|
||||
This repo wouldn't be possible without building on the work of others. Thanks!
|
||||
|
||||
## Usage
|
||||
|
||||
First, a note on the basic structure:
|
||||
|
||||

|
||||
|
||||
The sampler node connects to a group node. You can chain group nodes, however only one can match per step. Checking for a match starts at the group furthest from the sampler node. So if you have `Group1 -> Group2 -> Group3 -> Sampler`, the groups will be tried starting from `Group1`. Currently matching groups is only time based.
|
||||
|
||||
You will then connect a substeps node to the group. These can also be chained and like groups, execution starts with the node furthest from the group. I.E.: `Substeps1 -> Substeps2 -> Substeps3 -> Group` will start with `Substeps1`.
|
||||
|
||||
Most of these nodes have a text parameter input (YAML format - JSON is also valid YAML so you can use that instead if you prefer) and a parameter input. The parameter input can be used to specify stuff like custom noise types.
|
||||
|
||||
You may use filters and expressions in the text parameter input. See:
|
||||
|
||||
* [Filters](docs/filter.md)
|
||||
* [Expressions](docs/expression.md)
|
||||
|
||||
## Integration
|
||||
|
||||
* [ComfyUI-bleh](https://github.com/blepping/ComfyUI-bleh) - allows access to many more blend and scaling modes as well as some extra features.
|
||||
* [ComfyUI-sonar](https://github.com/blepping/ComfyUI-sonar) - allows access to many more noise types as well as the Power Filter feature.
|
||||
* [ComfyUi_NNLatentUpscale](https://github.com/Ttl/ComfyUi_NNLatentUpscale) - allows access to the `t_scale_nnlatentupscale` function in expressions.
|
||||
|
||||
If you're going to use OCS, I strongly recommend also installing `ComfyUI-bleh` and `ComfyUI-sonar` as they increase the functionality a lot.
|
||||
|
||||
*Note*: You will basically always have to tweak settings like `s_noise` to get a good result. If the generation looks smooth/undetailed increase `s_noise` somewhere. If it looks crunchy, super high contrast, etc then try reducing noise.
|
||||
|
||||
## Nodes
|
||||
|
||||
### ComposableSampler
|
||||
### `OCS Sampler`
|
||||
|
||||
**Possible Parameters**
|
||||
The main sampler node, with an output suitable for connecting to a `SamplerCustom`. This node has builtin support for Restart sampling, if you are
|
||||
using Restart don't use the `RestartSampler` node.
|
||||
|
||||
* `avgmerge_stretch`(`0.4`): Used for `average` and `sample` merge types. See below.
|
||||
* `model_call_cache`(unset): Caches the result of model calls. For example, Bogacki is 3 model calls per step. The first one usually depends on the merge strategy: `average` for example shares the first model evaluation between substeps, but subsequent model calls (i.e. Bogacki 2nd and 3rd model evaluations) still occur. When the model call cache is active, it's possible to cache those evalutions and avoid a model call for the remaining substeps. If you set `model_call_cache` to `1` then the result of that second call will be cached and if you're running two Bogacki substeps then the second one will use the cached version. Massively accelerates inference (especially when using the `average` merge strategy) but is likely very unsound and inaccurate. Does not apply to the sampler call for the `sample` merge strategy.
|
||||
* `model_call_cache_threshold`(`1`): Disables caching model call results with a call index below the threshold value (starting at 0). For example, if set to `2` and using a sampler like Bogacki that calls the model two extra times, the first will never be cached. The default value of `1` disabling caching for the first model call per substep. I generally would not recommend setting it to `0`, especially with `average` or `sample` merge strategies.
|
||||
* `model_call_cache_max_use`(`1000000`): The number of times cache items can be re-used. The default is effectively no limit. Where would this be useful? Let's say you're using the `average` merge strategy and a multi step sampler that calls the model at least one more time with 50 substeps. If you set the value to `25`, the model cache result will be updated around substep 25 which _may_ produce better results than reusing the result 50 times.
|
||||
You can connect a chain of `OCS Group` nodes to it and it will choose one per step (based on conditions like time).
|
||||
|
||||
#### Input Parameters
|
||||
|
||||
* `restart_custom_noise`: Value type: `SONAR_CUSTOM_NOISE`. Allows specifying a custom noise type when used with Restart sampling.
|
||||
|
||||
#### Text Parameters
|
||||
|
||||
Shown in YAML with default values.
|
||||
|
||||
<details>
|
||||
<summary>★★ Expand ★★</summary>
|
||||
|
||||
```yaml
|
||||
# Noise scale. May not do anything currently.
|
||||
s_noise: 1.0
|
||||
|
||||
# ETA (basically ancestralness). May not do anything currently.
|
||||
eta: 1.0
|
||||
|
||||
# Reversible ETA (used for reversible samplers). May not do anything currently.
|
||||
reta: 1.0
|
||||
|
||||
# Parameters related to restart sampling.
|
||||
restart:
|
||||
# When enabled, out of order sigmas will be detected as restart.
|
||||
# You can disable this if you want to use OCS for something like unsampling.
|
||||
enabled: true
|
||||
# Scales the noise added by restart sampling.
|
||||
s_noise: 1.0
|
||||
# Immiscible block same as described below.
|
||||
immiscible:
|
||||
size: 0
|
||||
|
||||
|
||||
# The noise block allows defining global noise sampling parameters.
|
||||
noise:
|
||||
# You can disable this to allow GPU noise generation.
|
||||
cpu_noise: true
|
||||
|
||||
# ComfyUI has a bug where if you disable add_noise in the sampler, no seed gets set. If you
|
||||
# are manually noising a sample and have add_noise turned off then you should enable this if
|
||||
# you want reproducible generations.
|
||||
set_seed: true
|
||||
|
||||
# Only has an effect when set_seed is enabled. Will advance the RNG this many times to
|
||||
# avoid the common mistake of using the same noise for sampling as the initial noise.
|
||||
seed_offset: 1
|
||||
|
||||
# Global scale scale for generated noise
|
||||
scale: 1.0
|
||||
|
||||
# Whether the generated noise should be normalized before use. Generally a good idea to leave enabled.
|
||||
normalize_noise: true
|
||||
|
||||
# Dimensions to normalize over (when normalization is enabled). Negative values mean starting
|
||||
# from the end (i.e. -1 means the last dimension, -2 means the penultimate dimension).
|
||||
# Latents generally have these dimensions: batch, channels, height, width
|
||||
# The default of [-3, -2, -1] normalizes noise over the batch. You can try something like
|
||||
# [-2, -1] to normalize over the batch and channels. See: https://pytorch.org/docs/stable/generated/torch.std.html
|
||||
normalize_dims: [-3, -2, -1]
|
||||
|
||||
# When caching, the batch size for chunks of noise to generate in advance. Generating a batch of noise
|
||||
# can be more efficient than generating on demand when using a high number of substeps (>10) per step.
|
||||
batch_size: 1
|
||||
|
||||
# Whether to cache noise.
|
||||
caching: true
|
||||
|
||||
# Interval (in full steps) to reset the cache. Brownian noise takes time into account so
|
||||
# if using Brownian with caching enabled you will generally want to reset each step.
|
||||
cache_reset_interval: 9999
|
||||
|
||||
# Immiscible noise processing, see: https://arxiv.org/abs/2406.12303
|
||||
immiscible:
|
||||
# Batch size, 0 disables.
|
||||
size: 0
|
||||
|
||||
# Reference mode, values can be one of:
|
||||
# x: Uses the current latent as a reference.
|
||||
# noise: Uses the current noise as a reference (x - denoised)
|
||||
# denoised: Uses the model image prediction as a reference (factors in positive and negative prompts).
|
||||
# uncond: The model unconditional prediction (negative prompt)
|
||||
# cond: The model conditional prediction (positive prompt)
|
||||
# Advanced feature: Additionally you may enter a string of operations in the format:
|
||||
# "x - denoised * 2 + cond" (just an example, not a recommended setting)
|
||||
# Possible operations: + - / * min max add sub div mul
|
||||
# Note: Each value and operation must be space delimited (i.e. "x-1" will not work).
|
||||
# Also normal operator precedence does not apply here.
|
||||
ref: default
|
||||
|
||||
# Batching mode, one of:
|
||||
# batch: Matches vs batches. Immiscible mode is disabled if size < 2
|
||||
# channel: Splits the batch into a list of channels and matches against those.
|
||||
# row: Splits the batch into a list of rows and matches against those.
|
||||
# column: Splits the batch into a list of columns and matches against those.
|
||||
# Note: Requires reshaping both the noise and x, may be slow and consume
|
||||
# a lot of VRAM.
|
||||
batching: channel
|
||||
|
||||
# Scale for reference latent. Can be negative.
|
||||
scale_ref: 1.0
|
||||
|
||||
# Allows normalizing the reference. If this is a list, you can specify the dimensions to
|
||||
# normalize. See normalize_dims above and https://pytorch.org/docs/stable/generated/torch.std.html
|
||||
normalize_ref: false
|
||||
|
||||
# The proportion of immiscible-ized noise.
|
||||
# You get (immiscible_noise * strength) + ((1.0 - strength) * normal_noise) - LERP.
|
||||
strength: 1.0
|
||||
|
||||
# See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html#scipy.optimize.linear_sum_assignment
|
||||
maximize: false
|
||||
|
||||
# Can be set to enable immiscible v2 mode. 0.0 is disabled, 0.1 is a reasonable value.
|
||||
distance_scale: 0.0
|
||||
|
||||
# If null will use the same value as distance_scale.
|
||||
distance_scale_ref: null
|
||||
|
||||
filter: null
|
||||
|
||||
|
||||
model:
|
||||
# When enabled, skips generating uncond when you have CFG set to 1. Disabled by
|
||||
# default as stuff like CFG++ won't work without uncond. Useful to enable for
|
||||
# models like Flux that don't actually use CFG.
|
||||
cfg1_uncond_optimization: false
|
||||
|
||||
filter:
|
||||
# Input to the model
|
||||
input: null
|
||||
# Result after CFG calculation
|
||||
denoised: null
|
||||
# Result after CFG calculation for JVP
|
||||
jdenoised: null
|
||||
# Cond - positive prompt
|
||||
cond: null
|
||||
# Uncond - negative prompt
|
||||
uncond: null
|
||||
```
|
||||
|
||||
</details><br/>
|
||||
|
||||
Any parameters you don't specify will use the defaults. For example if your text parameter block is:
|
||||
|
||||
```yaml
|
||||
noise:
|
||||
cpu_noise: false
|
||||
```
|
||||
|
||||
Then the rest of the parameters will use the defaults shown above.
|
||||
|
||||
***
|
||||
|
||||
### `OCS Group`
|
||||
|
||||
Defines a group of substeps.
|
||||
|
||||
Since it's kind of confusing even for me, a little more explanation: The model call cache caches results for model call indexes between `model_call_cache_threshold` and `model_call_cache - 1`. If you set `model_call_cache_threshold` to `0` and `model_call_cache` to `1` then only the first model call will be cached. If you set `model_call_cache_threshold` to `1` and `model_call_cache` to `2` then call 0 will not be cached, call 1 will be cached, call 2 will be cached, call 3 will not be cached, and so on.
|
||||
|
||||
#### Merging
|
||||
|
||||
When running multiple substeps per step, the results will combined based on the merge strategy. Possible strategies (in order of least weird to most weird):
|
||||
|
||||
* `simple`: Doesn't merge anything: only runs a single substep per step.
|
||||
* `divide`: Creates a linear schedule between the current sigma and the next and runs the substeps in sequence. The model is called at least once per substep.
|
||||
* `normal`: The model is called at least once per substep (and possibly additional times for higher order samplers). The result of each substep is noised and the next substep uses that result. Then all the results are averaged.
|
||||
* `average`: The model is called once at the beginning of the step and substeps share that result (but it may be called additional times for higher order samplers). This means substeps for samplers like reversible Euler, Heun 1s, DPM++ 2m SDE are essentially free. May be theoretically very unsound and inaccurate, requires manual tweaking of settings like `s_noise`. Supports the parameter `avgmerge_stretch`(`0.4`) which basically rolls back the current sigma and adds some noise (otherwise running a substep is deterministic and there would be no point to running a sampler like Euler more than once).
|
||||
* `sample`: Like `average` (and uses `avgmerge_stretch`) but instead of simply using the average, it does a sampler step toward that instead. You can plug in any substep sampler to the `merge_sampler_opt` input (if unconnected and the merge method is `sample` then Euler will be used). *Note*: Substeps in the attached sampler will be ignored.
|
||||
* `sample_uncached`: Similar to `sample`, however it calls the model per substep instead of caching the result and sharing it. Aside from sampling toward the result, it works more like the `normal` merge strategy. Theoretically it should be better because it's taking less shortcuts but results seem worse.
|
||||
* `supreme_avg`: The model is called at least once per step (and possibly additional times for higher order samplers). Each substep shares the first model call result. The results are averaged together. *Note*: Since the first model call is shared and the initial input is the same for each substep, there is no point in running multiple identical substeps. Also note: This merge strategy doesn't work well with non-ancestral samplers (i.e. dpmpp_2m or any sampler with `eta: 0`).
|
||||
* `overshoot`: The model is called at least once per step. It will sample steps equal to the number of substeps, starting from the current step. Then it will restart back to the expected step.
|
||||
* `lookahead`: Similar to `overshoot`, it samples ahead based on the number of substeps. The last model prediction is used to do a Euler step to the expected step. *Note:* Very experimental, likely to change in the future.
|
||||
* `pingpong`: Works similar to `overshoot` and `lookahead` methods except it does a pingpong sampler style step to the expected sigma.
|
||||
* `dynamic`: Allows specifying the group parameters as an expression to be evaluated. See below.
|
||||
|
||||
When using `average` and `sample` merge strategies and with model call caching enabled you can get away with setting substeps super high. Running something like 100 substeps is actually quite practical and seems to work well.
|
||||
|
||||
### ComposableStepSampler
|
||||
|
||||
This node has a text input for YAML (or JSON) advanced parameters.
|
||||
|
||||
For example, you could enter something like this in the field:
|
||||
**Dynamic Groups**: When `merge_method` is set to `dynamic` you must specify a `dynamic` block in the text parameters. The dynamic block may be either a string with the expression or a list of objects with an (optional) `when` key and a (required) `expression` key. The expression should return a dictionary of parameters you can set in the node (including both keys/values from the text parameters and widgets in the node). The first matching item will be used. Example:
|
||||
|
||||
```yaml
|
||||
reta: 1.1
|
||||
leap: 3
|
||||
dyn_deta_mode: "deta"
|
||||
# Use the simple merge method when step < 3, otherwise use overshoot
|
||||
dynamic:
|
||||
- when: step < 3
|
||||
expression: dict(merge_method :> 'simple)
|
||||
- expression: dict(merge_method :> 'overshoot)
|
||||
|
||||
# You could also write it like this:
|
||||
dynamic: |
|
||||
dict(merge_method :> (step < 3 ? 'simple : 'overshoot)
|
||||
```
|
||||
|
||||
**Possible Parameters**
|
||||
#### Node Parameters
|
||||
|
||||
#### General
|
||||
* `merge_method`: One of the merge methods described above in the Merging section.
|
||||
* `time_mode`(`step`): One of `step`, `step_pct`, `sigma`. Time matching mode. Matching based on steps generally will be simplest. Matches are inclusive and steps start at 0 (so step 0 is the first step). `step_pct` is the percentage of total steps (1.0=100%, 0.5=50%, etc).
|
||||
* `time_start`(`0`): Match start time.
|
||||
* `time_end`(`999`): Match end time.
|
||||
|
||||
* `eta`(`1.0`): Will override `eta` in the node if set.
|
||||
* `dyn_eta_start`(`unset`) and `dyn_eta_end`(`unset`): No effect unless both values are set. Will interpolate between start and end based on the percentage of sampling. *Note*: This is a factor applied to ETA, not a flat value.
|
||||
* `s_noise`(`1.0`): Will override `s_noise` in the node if set.
|
||||
* `solver_type`(`midpoint`): Applies to DPM++ 2m SDE. May be one of `midpoint` or `heun` (`midpoint` is generally recommended).
|
||||
Example:
|
||||
|
||||
#### Reversible
|
||||

|
||||
|
||||
* `reta`(`1.0`): Reverse ETA.
|
||||
* `dyn_reta_start`(`unset`) and `dyn_reta_end`(`unset`): No effect unless both values are set. Will interpolate between start and end based on the percentage of sampling. *Note*: This is a factor applied to RETA, not a flat value.
|
||||
The left side group matches steps 0, 1, 2. The right side group matches all steps. This setup will use whatever substeps are connected to the first group for the first three steps and the second group will handle the rest.
|
||||
|
||||
#### Dancing
|
||||
|
||||
* `leap`(`2`): Distance to try to leap forward. If you set `leap` to `1` you just get plain old Euler ancestral.
|
||||
* `deta`(`1.0`): ETA used for dance steps.
|
||||
* `dyn_deta_start`(`unset`) and `dyn_deta_end`(`unset`): No effect unless both values are set. Will interpolate between start and end based on the percentage of sampling. *Note*: This is a factor applied to DETA, not a flat value.
|
||||
* `dyn_deta_mode`(`lerp`): May be one of:
|
||||
* `deta`: Scales `deta` based on the value from `dyn_deta_start/end`.
|
||||
* `lerp`: Does the dance step according to `deta` and then LERPs the non-dance sample result with the dance sample result based on the scale calculated from `dyn_deta_start/end` (which is `1.0` if they are unset). For example, if the dance scale is `0.5` you will get 50% normal sampling, 50% dancing sampling.
|
||||
* `lerp_alt`: Similar to `lerp` except it LERPs with the leap result instead of a normal Euler ancestral result.
|
||||
#### Input Parameters
|
||||
|
||||
#### RES
|
||||
<!--
|
||||
* `merge_sampler`: Value type: `OCS_SUBSTEPS`. Only used when `merge_method` is `sample` or `sample_uncached`. Allows defining the sampler used for merging substeps.
|
||||
-->
|
||||
|
||||
* `res_simple_phi`(`false`): Uses a faster but possibly less accurate method for calculating phi. What does phi do? I haven't the foggiest!
|
||||
* `res_c2`(`0.5`): Solver partial step size, the default of `0.5` appears to use the midpoint. Setting it to a lower value might possibly be more accurate but slower?
|
||||
* `restart_custom_noise`: Currently only used by the `overshoot` merge method.
|
||||
* `custom_noise`: Currently used by the `lookahead` merge method.
|
||||
|
||||
#### TTM JVP
|
||||
#### Text Parameters
|
||||
|
||||
`alterate_phi_2_calc`(`true`): Supposedly works better than disabled when ETA isn't 0. I didn't notice a difference.
|
||||
Shown in YAML with default values.
|
||||
|
||||
**Note**: TTM is a weird sampler. If you're using model caching you must make sure the entries TTM uses are populated first (by having before any other samplers that call the model multiple times). It may also not work with some other model patches and upscale methods.
|
||||
<details>
|
||||
<summary>★★ Expand ★★</summary>
|
||||
|
||||
## Credits
|
||||
```yaml
|
||||
# Noise scale. May not do anything currently.
|
||||
s_noise: 1.0
|
||||
|
||||
I can move code around but sampling math and creating samplers is far beyond my ability. I didn't write any of the original samplers:
|
||||
# ETA (basically ancestralness). May not do anything currently.
|
||||
eta: 1.0
|
||||
|
||||
* Euler, DPMPP SDE, DPMPP 2S, DPM++ 2m, 2m SDE and 3m SDE samplers based on ComfyUI's implementation.
|
||||
* Reversible Heun, Reversible Heun 1s, RES, Trapezoidal, Bogacki, Reversible Bogacki, RK4 and Euler Dancing samplers based on implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
* TTM JVP sampler based on implementation written by Katherine Crowson (but yoinked from the Extra-Samplers repo mentioned above).
|
||||
* Normal substep merge strategy based on implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
# Reversible ETA (used for reversible samplers). May not do anything currently.
|
||||
reta: 1.0
|
||||
|
||||
Thanks!
|
||||
# Sets the type of preview used for sampling in this group. One of:
|
||||
# denoised: The default, shows the model prediction (takes positive and negative prompt into account).
|
||||
# cond: Shows the model cond prediction (basically the positive prompt).
|
||||
# uncond: Shows the model uncond prediction (basically the negative prompt).
|
||||
# raw: Shows the raw noisy latent input.
|
||||
# noisy: 10% of the noise + denoised.
|
||||
# diff: Multiplies the difference between cond and uncond.
|
||||
preview_mode: denoised
|
||||
|
||||
# Expression.
|
||||
when: null
|
||||
|
||||
# Interpolate the schedule by the specified factor. Only used by the overshoot merge method.
|
||||
#: Example if factor 2 and steps [0,1,2] you'd get [0, 0.5, 1.0, 1.5, 2]
|
||||
overshoot_expand_steps: 1
|
||||
|
||||
# Only used by the overshoot merge method currently.
|
||||
restart:
|
||||
# Scales the noise added by restart sampling.
|
||||
s_noise: 1.0
|
||||
# Immiscible block same as described above.
|
||||
immiscible:
|
||||
size: 0
|
||||
|
||||
# Only used by the lookahead merge method currently.
|
||||
lookahead:
|
||||
# Works like normal samplers, essentially. Disabled by default.
|
||||
eta: 0.0
|
||||
|
||||
# Scales the noise added by lookahead sampling.
|
||||
s_noise: 1.0
|
||||
|
||||
# Controls how much noise to remove in the prediction phase. Higher values will remove more noise.
|
||||
dt_factor: 1.0
|
||||
|
||||
# Immiscible block same as described above.
|
||||
immiscible:
|
||||
size: 0
|
||||
|
||||
# Only used by the pingpong merge method.
|
||||
pingpong:
|
||||
# Scales the noise added by lookahead sampling.
|
||||
s_noise: 1.0
|
||||
|
||||
pre_filter: null
|
||||
|
||||
post_filter: null
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
***
|
||||
|
||||
### `OCS Substeps`
|
||||
|
||||
#### Step Methods (Samplers)
|
||||
|
||||
In alphabetical order.
|
||||
|
||||
* `adapter`: Wraps a normal ComfyUI `SAMPLER`. Attach a `SAMPLER` parameter to the node. Note: Samplers that do unusual stuff like try to manipulate the model won't work. ComfyUI's built-in CFG++ samplers in particular do not work here.
|
||||
* `blep_bas`: Batch Augmented Sampler. My own dumb experiment that expands the batch and averages the result. May be very slow/require a lot of VRAM. See parameters: `bas`
|
||||
* `blep_euler_cycle`: See parameters: `cycle_pct`.
|
||||
* `blep_weoon`: Wavelet-based second order sampler. Another dumb experiment. See parameters: `weoon`
|
||||
* `bogacki`: Bogacki-Shampine sampler. Also has a reversible variant.
|
||||
* `clybius_euler_dancing`: Pretty broken currently, will probably require increased `s_noise` values. See parameters: `deta`, `leap`, `deta_mode`.
|
||||
* `clybius_sens`: Reversible dpmpp_3m_sde variant. Supports a separate set of reversible parameters in `tsde_reversible`.
|
||||
* `deis`: See parameters: `history_limit`. Does not work well with ETA, I don't recommending leaving ETA at the default 1.
|
||||
* `dpm2`: Set `eta: 0` for non-ancestral variant.
|
||||
* `dpmpp_2m_sde`: Also supports reversible parameters. See parameters: `history_limit`.
|
||||
* `dpmpp_2m`: `eta` and `s_noise` parameters are ignored. See parameters: `history_limit`.
|
||||
* `dpmpp_2s`
|
||||
* `dpmpp_3m_sde`: See parameters: `history_limit`.
|
||||
* `dpmpp_sde`
|
||||
* `dynamic`: Advanced step method that allows using an expression to determine the sampler parameters at each substep. See below for a more detailed explanation.
|
||||
* `euler`: If samplers came in vanilla.
|
||||
* `extraltodeus_distance`: Adaptive-ish/configurable step variant of Heun. Referenced from [https://github.com/Extraltodeus/DistanceSampler](https://github.com/Extraltodeus/DistanceSampler). See parameters: `distance`.
|
||||
* `gradient_estimation`
|
||||
* `heun_1s`: Alternate Heun one step implementation. Supports reversible parameters.
|
||||
* `heun`: Alternate Heun implementation. Supports reversible parameters. See parameters: `history_limit`.
|
||||
* `heunpp`: See parameters: `max_order`.
|
||||
* `ipndm_v`: See parameters: `history_limit`.
|
||||
* `ipndm`: See parameters: `history_limit`.
|
||||
* `pingpong`
|
||||
* `res`: Refined Exponential Solver. I believe this is a variant of Heun. Generally works very well.
|
||||
* `res_multistep`
|
||||
* `reversible_bogacki`: Reversible variant of Bockacki-Shampine.
|
||||
* `reversible_heun_1s`: Reversible variant of Heun 1 step. See parameters: `history_limit`.
|
||||
* `reversible_heun`: Reversible variant of Heun.
|
||||
* `rk_dynamic`: Variant of RK4 that lets you set `max_order` (you can also set it to `0` to choose an order dynamically, doesn't seem to work so well though).
|
||||
* `rk4`: Runge-Kutta 4th order sampler.
|
||||
* `rkf45`: 5 model call flavor of RK.
|
||||
* `solver_diffrax`: Uses the [Diffrax](https://github.com/patrick-kidger/diffrax) solver backend. See `de_*` parameters below.
|
||||
* `solver_torchdiffeq`: Uses the [torchdiffeq](https://github.com/rtqichen/torchdiffeq) backend. See `de_*` parameters below.
|
||||
* `solver_torchode`: Uses the [torchode]((https://github.com/martenlienen/torchode)) backend. See `de_*` parameters below.
|
||||
* `solver_torchsde`: Uses the [torchsde](https://github.com/google-research/torchsde) backend. See `de_*` parameters below.
|
||||
* `trapezoidal_cycle`: See parameters: `cycle_pct`.
|
||||
* `trapezoidal`:
|
||||
* `ttm_jvp`: TTM is a weird sampler. If you're using model caching you must make sure the entries TTM uses are populated first (by having it run before any other samplers that call the model multiple times). It may also not work with some other model patches and upscale methods. See parameters: `alternate_phi_2_calc`
|
||||
|
||||
**Sampler Feature Support**
|
||||
|
||||
|Name|Cost|History|Order|Reversible|CFG++|
|
||||
|-|-|-|-|-|-|
|
||||
|`adapter`|?|?|?|?|?|
|
||||
|`blep_bas`|variable|||||
|
||||
|`blep_euler_cycle`|1||||X|
|
||||
|`blep_trapezoidal_cycle`|2|||||
|
||||
|`blep_weoon`|2|||||
|
||||
|`bogacki`|2|||||
|
||||
|`clybius_euler_dancing`|1|||||
|
||||
|`clybius_sens`|1|1||||
|
||||
|`deis`|1|1-3 (1)||||
|
||||
|`dpmpp_2m_sde`|1|1||||
|
||||
|`dpmpp_2m`|1|1||||
|
||||
|`dpmpp_2s`|2|||||
|
||||
|`dpmpp_3m_sde`|1|1-2 (2)||||
|
||||
|`dpmpp_sde`|2|||||
|
||||
|`dynamic`|?|?|?|?|?|
|
||||
|`euler`|1||||X|
|
||||
|`extraltodeus_distance`|variable|||||
|
||||
|`gradient_estimation`|1|1||||
|
||||
|`heun_1s`|1|1||X||
|
||||
|`heun`|2|||X||
|
||||
|`heunpp`|1-3||X|||
|
||||
|`ipndm_v`|1|1-3 (1)||||
|
||||
|`ipndm`|1|1-3 (1)||||
|
||||
|`pingpong`|1|||||
|
||||
|`res`|2|||||
|
||||
|`res_multistep`|1|1||||
|
||||
|`reversible_bogacki`|2|||X||
|
||||
|`reversible_heun_1s`|1|1||X||
|
||||
|`reversible_heun`|2|||X||
|
||||
|`rk4`|1-4|||||
|
||||
|`rk4`|4|||||
|
||||
|`rkf45`|5|||||
|
||||
|`solver_diffrax`|variable|||||
|
||||
|`solver_torchdiffeq`|variable|||||
|
||||
|`solver_torchode`|variable|||||
|
||||
|`solver_torchsde`|variable|||||
|
||||
|`trapezoidal`|2|||||
|
||||
|`ttm_jvp`|2|||||
|
||||
|
||||
|
||||
`deis`, `ipndm*` and `gradient_estimation` do not seem to work well with ancestralness, I recommend `eta: 0.25` or disable it completely.
|
||||
|
||||
**Solver Backend Samplers**:
|
||||
|
||||
You will need to have the relevant Python package installed in your venv to use these. TDE cannot handle batches and
|
||||
each batch item will be evaluated separately. Using `tode` may be faster for batch sizes over 1.
|
||||
|
||||
`ode_solver` types for TDE: adaptive: `dopri8`, `dopri5`, `bosh3`, `fehlberg2`, `adaptive_heun`, fixed step: `euler`, `midpoint`, `rk4`, `explicit_adams`, `implicit_adams`
|
||||
|
||||
`ode_solver` types for TODE: adaptive only: `dopri5`, `tsit5`, `heun`. I haven't much luck with anything other than `dopri5`.
|
||||
|
||||
Note that adaptive solvers may be _very_ slow. Think along the lines of 20-100 model calls per substep (or in other words, the equivalent for running that many `euler` steps). Tolerances only apply to adaptive solvers.
|
||||
|
||||
**Cycle Samplers** (`euler_cycle`, `trapezoidal_cycle`)
|
||||
|
||||
Basically a different approach to ancestral sampling. First a crash course on how sampling works:
|
||||
|
||||
Each step has an expected noise level, with the first step generally being pure noise and the end of the last step aiming to end with no noise remaining. Let's say the image on the current step is called `x`, calling the model with `x` gives us a prediction of what the image looks like with all noise removed (`denoised`), however the model is not capable of just removing all the noise in a single step: its prediction will be imprecise. `x - denoised` leaves us with just the noise (we subtract the prediction which theoretically has no noise from the noisy sample). This is a very simplified, but the idea is basically to add the noise back into `denoised`, but scaled so that it matches the amount of noise expected on the _next_ step. `denoised + noise * expected_noise_at_next_step`.
|
||||
|
||||
When doing ancestral sampling, we actually _overshoot_ expected noise for the next step and add less than that amount back to `denoised`. Then we generate some of our own noise and add it, scaled so that the result matches `expected_noise_at_next_step`. `eta` controls how the scale of the overshoot.
|
||||
|
||||
The difference with cycle is that instead of adding `noise * expected_noise_at_next_step`, we instead first add `noise * (expected_noise_at_next_step * (1.0 - cycle_pct))` and then we generate noise and scale it to `cycle_pct` and add it too. Just for example, suppose `cycle_pct` is `0.2`: we'll add 80% of the expected noise at the next step (`1.0 - 0.2 == 0.8`) and then generate the remaining 20% and add it in to meet the expected amount. I don't recommend setting `cycle_pct` to values over `0.5`, especially if using "weird" noise types.
|
||||
|
||||
**Dynamic Step Method**: When `step_method` is set to `dynamic` you must specify a `dynamic` block in the text parameters. The dynamic block may be either a string with the expression or a list of objects with an (optional) `when` key and a (required) `expression` key. The first matching item will be used. The expression should return a dictionary of parameters you can set in the node (including both keys/values from the text parameters and widgets in the node). Example:
|
||||
|
||||
```yaml
|
||||
# Use the rk4 merge method when step < 3, otherwise use euler
|
||||
dynamic:
|
||||
- when: step < 3
|
||||
expression: dict(step_method :> 'rk4)
|
||||
- expression: dict(step_method :> 'euler)
|
||||
|
||||
# You could also write it like this:
|
||||
dynamic: |
|
||||
dict(step_method :> (step < 3 ? 'rk4 : 'euler)
|
||||
```
|
||||
|
||||
*Note*: You can set all sampler parameters except `substeps` this way. Sampling will use the `substeps` value from the `OCS Substeps` node.
|
||||
|
||||
|
||||
#### Node Parameters
|
||||
|
||||
* `substeps`(`1`): Number of substeps. Generally involves a model call per substep, so for example setting this to 4 would approximately quadruple sampling time.
|
||||
* `step_method`(`euler`): Method used for sampling the substeps. May include a parenthesized number (i.e. `rk4 (3)`) which denotes the number of _extra_ model calls required per sample. At least one is always required. So `euler` requires 1 in total, `rk4` requires 4 in total. RK4 is about 4 times slower than `euler`.
|
||||
|
||||
#### Input Parameters
|
||||
|
||||
* `custom_noise`: Value type: `SONAR_CUSTOM_NOISE`. Allows specifying a custom noise type for samplers that generate noise (most of them).
|
||||
|
||||
#### Text Parameters
|
||||
|
||||
Shown in YAML with default values.
|
||||
|
||||
<details>
|
||||
<summary>★★ Expand ★★</summary>
|
||||
|
||||
```yaml
|
||||
# Scale for added noise.
|
||||
s_noise: 1.0
|
||||
|
||||
# ETA (basically ancestralness).
|
||||
eta: 1.0
|
||||
|
||||
# If the ETA calculation fails, it will retry with eta - eta_retry_increment until it either
|
||||
# succeeds or eta becomes <= 0 (in which case ancestralness just gets disabled).
|
||||
# In other words, you can set ETA as high as you want, set eta_retry_increment to something like 0.1 and
|
||||
# it will just do whatever it takes to find an ETA that works.
|
||||
eta_retry_increment: 0
|
||||
|
||||
# No effect unless both start and end are set. Will scale the eta value based on the
|
||||
# percentage of sampling. In other words, eta*dyn_eta_start at the beginning,
|
||||
# eta*dyn_eta_end at the end.
|
||||
dyn_eta_start: null
|
||||
dyn_eta_end: null
|
||||
|
||||
# alt CFG++ scale (see https://cfgpp-diffusion.github.io/)
|
||||
# Based on the initial incorrect ComfyUI implementation, but it seems to
|
||||
# produce decent results sometimes.
|
||||
# Can also be set to a negative value (I don't recommend going lower than -0.5).
|
||||
alt_cfgpp_scale: 0
|
||||
|
||||
# CFG++ (see https://cfgpp-diffusion.github.io/)
|
||||
cfgpp: false
|
||||
|
||||
### Reversible Settings ###
|
||||
|
||||
reversible:
|
||||
# 0-indexed step where reversible sampling will start.
|
||||
start_step: 0
|
||||
# 0-indexed last step where reversible sampling will be used.
|
||||
end_step: 9999
|
||||
# Scale of the reversible correction. Can also be set to a negative value.
|
||||
scale: 1.0
|
||||
# Reversible ETA.
|
||||
eta: 1.0
|
||||
|
||||
# No effect unless both start and end are set. Will scale the eta value based on the
|
||||
# percentage of sampling. In other words, reta*dyn_reta_start at the beginning,
|
||||
# reta*dyn_reta_end at the end.
|
||||
dyn_eta_start: null
|
||||
dyn_eta_end: null
|
||||
|
||||
eta_retry_increment: 0.0
|
||||
# Might not do anything currently.
|
||||
use_cfgpp: false
|
||||
|
||||
pre_filter: null
|
||||
|
||||
post_filter: null
|
||||
|
||||
### ODE Sampler Settings ###
|
||||
|
||||
# Solver type.
|
||||
de_solver: dopri5 # Example - varies based on solver sampler.
|
||||
# Relative tolerance (log 10)
|
||||
de_rtol: -1.5
|
||||
# Absolute tolerance (log 10)
|
||||
de_atol: -3.5
|
||||
# Max model calls allowed to compute the solution. If the limit is exceeded, it is an error.
|
||||
de_max_nfe: 1000
|
||||
# Min sigma to sample to. If the current step start <= min sigma, then the sampler will run
|
||||
# a Euler step. If the current step end <= min sigma then the slover will sample to the min
|
||||
# sigma and then to a Euler step from min sigma for the rest.
|
||||
de_min_sigma: 0.0292
|
||||
# Hack that seems to help results by stretching the down sigma a bit. Set to 0 to disable.
|
||||
de_fixup_hack: 0.025
|
||||
|
||||
# Used to split the step into sections. Useful for fixed step methods.
|
||||
# Applies to: solver_torchode, solver_diffrax
|
||||
de_split: 1
|
||||
|
||||
# Initial step size (as a percentage).
|
||||
# Applies to: solver_torchode, solver_diffrax
|
||||
de_initial_step: 0.25
|
||||
|
||||
# Coefficients for the step size PID controller.
|
||||
# See https://en.wikipedia.org/wiki/Proportional%E2%80%93integral%E2%80%93derivative_controller
|
||||
# These values seem okay with dopri5.
|
||||
# Applies to: solver_tode, solver_diffrax
|
||||
de_ctl_pcoeff: 0.3
|
||||
de_ctl_icoeff: 0.9
|
||||
de_ctl_dcoeff: 0.2
|
||||
|
||||
# Controls whether to compile the solver. May or may not work,
|
||||
# also may or may not be a speed increase as the compiled solver is
|
||||
# not cached between substeps.
|
||||
# Applies to: solver_torchode
|
||||
tode_compile: false
|
||||
|
||||
### torchsde solver specific parameters.
|
||||
tsde_noise_type: "scalar"
|
||||
tsde_sde_type: "stratonovich"
|
||||
tsde_levy_area_approx: "none"
|
||||
tsde_noise_channels: 1
|
||||
tsde_g_multiplier: 0.05
|
||||
tsde_g_reverse_time: true
|
||||
tsde_g_derp_mode: false
|
||||
tsde_batch_channels: true
|
||||
|
||||
### diffrax solver specific parameters.
|
||||
|
||||
# Turns on adaptive stepping. When enabled, de_split is not used.
|
||||
# When disabled, it may be desirable to set de_split.
|
||||
diffrax_adaptive: false
|
||||
# Hack to make some solver methods work. May not be safe.
|
||||
diffrax_fake_pure_callback: true
|
||||
# Some diffrax methods don't allow adaptive stepping, enabling this
|
||||
# makes them usable although it's less efficient (3x cost, 2x accuracy).
|
||||
diffrax_half_solver: false
|
||||
diffrax_batch_channels: false
|
||||
# Some solvers require specific types of Levy area approximation.
|
||||
# See: https://docs.kidger.site/diffrax/api/brownian/#levy-areas
|
||||
diffrax_levy_area_approx: "brownian_increment"
|
||||
# Some solvers may require manually specifying the error order.
|
||||
diffrax_error_order: null
|
||||
# Enables SDE mode (and SDE-specific solvers). May not be worth using.
|
||||
diffrax_sde_mode: false
|
||||
# Noise multiplier when SDE mode is enabled.
|
||||
diffrax_g_multiplier: 0.0
|
||||
# Only applies when time scaling is enabled. Reverses time.
|
||||
diffrax_g_reverse_time: false
|
||||
# Scales the g multiplier based on the current time.
|
||||
diffrax_g_time_scaling: false
|
||||
# Experimental option to flip the sign on the g multiplier when time >= half the step.
|
||||
# i.e. if you'd get 1,2,3,4 as g values for the step, with this it would be 1,2,-3,-4.
|
||||
diffrax_g_split_time_mode: false
|
||||
|
||||
# blep_bas sampler-specific parameters
|
||||
bas:
|
||||
# Batch expansion factor. Whatever your original batch size was will be multiplied
|
||||
# by this. If it's 0 then you just get normal Euler.
|
||||
batch_multiplier: 2
|
||||
# First 0-indexed step when BAS sampling will apply.
|
||||
start_step: 0
|
||||
# Last 0-index step when BAS sampling will apply.
|
||||
end_step: 3
|
||||
|
||||
s_noise: 1.0
|
||||
eta: 0.0
|
||||
eta_retry_increment: 0.0
|
||||
|
||||
# List of weights for the denoised batches, with 0 being the original denoised.
|
||||
# If the list is smaller than the batch size, the list will be padded with the
|
||||
# last item.
|
||||
# If set to null it will be calculated automatically.
|
||||
# Example: [0.5, 1.0]
|
||||
# Will use weight 0.5 for the original denoised and 1.0 for any other items.
|
||||
denoised_factors: null
|
||||
|
||||
# If set to something other than 0 the supplied denoised_factors will be rebalanced
|
||||
# to add up to this number.
|
||||
denoised_factors_scale: 1.0
|
||||
|
||||
# Global multiplier on denoised for BAS steps.
|
||||
denoised_multiplier: 1.0
|
||||
|
||||
# One of: restart, restart_noneta, simple
|
||||
renoise_mode: restart
|
||||
|
||||
# Multiplier on the start sigma for BAS steps.
|
||||
# Note that taking the multipliers into account sigma_next must be less than sigma.
|
||||
fromstep_factor: 1.0
|
||||
|
||||
# Multiplier on the end sigma for BAS steps.
|
||||
tostep_factor: 1.0
|
||||
|
||||
# Source for the downstep. Can be one of dt, sigma or sigma_next.
|
||||
# dt means you get bsigma + (sigma_next - bsigma) * tostep_factor
|
||||
# where bsigma = sigma * fromstep_factor
|
||||
tostep_source: dt
|
||||
|
||||
# blep_weoon sampler-specific options.
|
||||
# Parameters with "inv" in the name apply to the inverse wavelet operation.
|
||||
# When set to null, they will use the normal setting.
|
||||
weoon:
|
||||
start_step: 0
|
||||
end_step: 9999
|
||||
eta: 0.0
|
||||
eta_retry_increment: 0.0
|
||||
s_noise: 1.0
|
||||
# One of dwt, dwt1d, dtcwt
|
||||
wavelet_mode: dwt
|
||||
# Padding scheme used for wavelets
|
||||
padding: periodization
|
||||
# Padding scheme used for the inverse wavelet operation
|
||||
inv_padding: null
|
||||
# Wavelet type. Does not apply if wavelet_mode is dtcwt.
|
||||
wave: db4
|
||||
# Wavelet type used for the inverse wavelet operation. Does not apply if wavelet_mode is dtcwt.
|
||||
inv_wave: null
|
||||
# dtcwt qshift parameter. Only applies if the wavelet mode is dtcwt.
|
||||
dtcwt_qshift: qshift_a
|
||||
# dtcwt biort parameter. Only applies if the wavelet mode is dtcwt.
|
||||
dtcwt_biort: near_sym_a
|
||||
# dtcwt qshift parameter used for the inverse wavelet operation. Only applies if the wavelet mode is dtcwt.
|
||||
dtcwt_inv_qshift: null
|
||||
# dtcwt biort parameter used for the inverse wavelet operation. Only applies if the wavelet mode is dtcwt.
|
||||
dtcwt_inv_biort: null
|
||||
# Can be used to stretch the step down. I.E. 1.0 would be sigma -> sigma_next
|
||||
# while 2.0 would be twice the distance between sigma and sigma_next.
|
||||
downstep_scale: 1.0
|
||||
# Blend scale for the downstep denoised lowpass wavelets
|
||||
yl_strength: 1.0
|
||||
# Blend scale for the downstep denoised highpass wavelets
|
||||
yh_strength: 0.5
|
||||
# Mode used for blending wavelets.
|
||||
wavelet_blend_mode: lerp
|
||||
# Blend mode for wavelet highpass, uses wavelet_blend_mode if null.
|
||||
wavelet_blend_mode_yh: null
|
||||
# Extra multipliers that can be applied to the low/highpass wavelets for the normal
|
||||
# denoised or downstep denoised.
|
||||
denoised_yl_multiplier: 1.0
|
||||
denoised_yh_multiplier: 1.0
|
||||
denoised_down_yl_multiplier: 1.0
|
||||
denoised_down_yh_multiplier: 1.0
|
||||
# Only applies when wavelet_mode is dwt1d. Can be:
|
||||
# 2: Flatten starting at spatial dimensions
|
||||
# 1: Flatten starting at channels dimension
|
||||
# 0: Smash everything together!
|
||||
flatten_start_dim: 2
|
||||
|
||||
### Other Sampler Specific Parameters ###
|
||||
|
||||
# Used for some samplers that use history from previous steps.
|
||||
# List of samplers and default value below:
|
||||
# dpmpp_2m: 1
|
||||
# dpmpp_2m_sde: 1
|
||||
# dpmpp_3m_sde: 2
|
||||
# reversible_heun_1s: 1
|
||||
# ipndm: 1 (max 3)
|
||||
# ipndm_v: 1 (max 3)
|
||||
# deis: 1 (max 3)
|
||||
# clybius_sens: 2
|
||||
history_limit: 999 # Varies based on sampler.
|
||||
|
||||
# Used for some samplers with variable order. List of samplers and default value below:
|
||||
# heunpp2: 3
|
||||
# rk_dynamic: 4 - Can also be set to 0 to try to dynamically adjust the order based on calculated
|
||||
# error from the last step (but that may not work well).
|
||||
max_order: 999 # Varies based on sampler.
|
||||
|
||||
# Used for dpmpp_2m. One of midpoint, heun
|
||||
solver_type: "midpoint"
|
||||
|
||||
# Coefficients mode for DEIS. One of tab or rhoab.
|
||||
deis_mode: "tab"
|
||||
|
||||
# Used for samplers with cycle in the name. Controls how much noise is cycled per step.
|
||||
cycle_pct: 0.25
|
||||
|
||||
# Used for ttm_jvp. Supposed works better when ETA > 0
|
||||
alternate_phi_2_calc: true
|
||||
|
||||
# Parameters for dancing samplers:
|
||||
# Number of steps to leap ahead.
|
||||
leap: 2
|
||||
# ETA for dance steps
|
||||
deta: 1.0
|
||||
# dyn_deta works the same as dyn_eta/reta. See above.
|
||||
dyn_deta_start: null
|
||||
dyn_deta_end: null
|
||||
# One of lerp, lerp_alt, deta
|
||||
dyn_deta_mode: "lerp"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### `OCS Param` and `OCS MultiParam`
|
||||
|
||||
Allows specifying parameter inputs that can't be expressed with YAML, such as custom noise.
|
||||
|
||||
#### Node Parameters
|
||||
|
||||
* `key`: Determines the parameter input type.
|
||||
|
||||
#### Input Parameters
|
||||
|
||||
* `value`: Input for the actual parameter - must match the specified input type or you will get an error when you evaluate the workflow.
|
||||
* `params_opt`: Allows connecting another `OCS Param` or `OCS MultiParam` node to specify multiple parameters.
|
||||
|
||||
#### Text Parameters
|
||||
|
||||
Allows specifying extra parameters. You may use this block to rename a key, for example if your key type was `custom_noise` you could enter:
|
||||
|
||||
```yaml
|
||||
rename: test
|
||||
```
|
||||
|
||||
in the `OCS Param` node and:
|
||||
|
||||
```yaml
|
||||
custom_noise: test
|
||||
```
|
||||
|
||||
in the node that was connected to the params to have it use the custom noise specifically named `test`.
|
||||
|
||||
### `OCS MultiParam`
|
||||
|
||||
MultiParam is the same as Param except it has multiple optional inputs like `key_1`, `key_2`, etc.
|
||||
|
||||
#### Text Parameters
|
||||
|
||||
Same as `OCS Param` (see above), however if set you should use an object with a key corresponding to the index of the param. For example, if you wanted to rename `key_1` and `key_2` you would do something like:
|
||||
|
||||
```yaml
|
||||
1:
|
||||
rename: test1
|
||||
2:
|
||||
rename: test2
|
||||
```
|
||||
|
||||
### `OCS SimpleRestartSchedule`
|
||||
|
||||
Generates a restart schedule.
|
||||
|
||||
#### Node Parameters
|
||||
|
||||
* `start_step`: 0-based first step for the restart schedule to apply.
|
||||
|
||||
#### Input Parameters
|
||||
|
||||
* `sigmas`: Sigmas to restartify. Output from any normal schedule node.
|
||||
|
||||
#### Text Parameters
|
||||
|
||||
JSON or YAML schedule in list form.
|
||||
|
||||
```yaml
|
||||
- [4, -3]
|
||||
- [2, -1]
|
||||
- 1
|
||||
```
|
||||
|
||||
Each item should be one of:
|
||||
|
||||
* A pair `[interval, jump]` - after `interval` steps, make a relative jump of `jump` steps.
|
||||
* A single integer `schedule_index`: resume the schedule at the specified 0-based index.
|
||||
|
||||
The example above means:
|
||||
1. After 4 steps, jump back 3 steps.
|
||||
2. After 2 steps, jump back one step.
|
||||
3. Go to the second item (after 2 steps, jump back one step).
|
||||
|
||||
The node `start_step` parameter is effectively the same as `[start_step, 0]` as a schedule item.
|
||||
|
||||
***
|
||||
|
||||
### `OCSNoise to SONAR_CUSTOM_NOISE`
|
||||
|
||||
Adapter that enables using OCS noise generators with nodes that accept `SONAR_CUSTOM_NOISE`.
|
||||
|
||||
Most built-in OCS nodes will accept either type currently.
|
||||
|
||||
***
|
||||
|
||||
### `OCSNoise PerlinSimple`
|
||||
|
||||
Generates 2D or 3D Perlin noise with many tuneable parameters. Can be plugged in to samplers for ancestral or SDE sampling. For initial noise or img2img workflows, use the `NoisyLatentLike` node from `ComfyUI-sonar` (see [Integration](#integration)).
|
||||
|
||||
3D Perlin noise works by taking a slice in the depth dimension each time the noise sampler is called.
|
||||
|
||||
For more tuneable parameters, see the `OCSNoise PerlinAdvanced` node.
|
||||
|
||||
**Note**: The shape of the latent must be a multiple of `lacunarity ** (octaves - 1) * res` (`**` indicates raising something to a power). Most latent types will have one latent pixel equaling eight normal pixels - i.e. if your image is 512x512, the latent would be 64x64.
|
||||
|
||||
#### Node Parameters
|
||||
|
||||
* `depth`: When non-zero, 3D perlin noise will be generated.
|
||||
* `detail_level`: Controls the detail level of the noise when `break_pattern` is non-zero. No effect when using 100% raw Perlin noise.
|
||||
* `octaves`: Generally controls the detail level of the noise. Each octave involves generating a layer of noise so there is a performance cost to increasing octaves.
|
||||
* `persistence`: Controls how rough the generated noise is. Lower values will result in smoother noise, higher values will look more like Gaussian noise. Comma-separated list, multiple items will apply to octaves in sequence.
|
||||
* `lacunarity`: Lacunarity controls the frequency multiplier between successive octaves. Only has an effect when octaves is greater than one. Comma-separated list, multiple items will apply to octaves in sequence.
|
||||
* `res_height`: Number of periods of noise to generate along an axis. Comma-separated list, multiple items will apply to octaves in sequence.
|
||||
* `break_pattern`: Applies a function to break the Perlin pattern, making it more like normal noise. The value is the blend strength, where 1.0 indicates 100% pattern broken noise and 0.5 indicates 50% raw noise and 50% pattern broken noise. Generally should be at least 0.9 unless you want to generate colorful blobs.
|
||||
|
||||
***
|
||||
|
||||
### `OCSNoise PerlinAdvanced`
|
||||
|
||||
Generates 2D or 3D Perlin noise with many tuneable parameters. Can be plugged in to samplers for ancestral or SDE sampling. For initial noise or img2img workflows, use the `NoisyLatentLike` node from `ComfyUI-sonar` (see [Integration](#integration)).
|
||||
|
||||
3D Perlin noise works by taking a slice in the depth dimension each time the noise sampler is called.
|
||||
|
||||
**Note**: The shape of the latent in the relevant dimension _including padding_ must be a multiple of `lacunarity ** (octaves - 1) * res`. Most latent types will have one latent pixel equaling eight normal pixels - i.e. if your image is 512x512, the latent would be 64x64.
|
||||
|
||||
#### Node Parameters
|
||||
|
||||
* `depth`: When non-zero, 3D perlin noise will be generated.
|
||||
* `detail_level`: Controls the detail level of the noise when `break_pattern` is non-zero. No effect when using 100% raw Perlin noise.
|
||||
* `octaves`: Generally controls the detail level of the noise. Each octave involves generating a layer of noise so there is a performance cost to increasing octaves.
|
||||
* `persistence`: Controls how rough the generated noise is. Lower values will result in smoother noise, higher values will look more like Gaussian noise. Comma-separated list, multiple items will apply to octaves in sequence.
|
||||
* `lacunarity_height`: Lacunarity controls the frequency multiplier between successive octaves. Only has an effect when octaves is greater than one. Comma-separated list, multiple items will apply to octaves in sequence.
|
||||
* `lacunarity_width`: " "
|
||||
* `lacunarity_depth`: " "
|
||||
* `res_height`: Number of periods of noise to generate along an axis. Comma-separated list, multiple items will apply to octaves in sequence.
|
||||
* `res_width`: " "
|
||||
* `res_depth`: " "
|
||||
* `break_pattern`: Applies a function to break the Perlin pattern, making it more like normal noise. The value is the blend strength, where 1.0 indicates 100% pattern broken noise and 0.5 indicates 50% raw noise and 50% pattern broken noise. Generally should be at least 0.9 unless you want to generate colorful blobs.
|
||||
* `initial_depth`: First zero-based depth index the noise generator will return. Only has an effect when depth is non-zero.
|
||||
* `wrap_depth`: If non-zero, instead of generating a new chunk of noise when the last slice is used will instead jump back to the specified zero-based depth index. Only has an effect when depth is non-zero. Since this is repeating the same noise, you may need to reduce `s_noise` in samplers especially if your `depth` value is low.
|
||||
* `max_depth`: Basically crops the depth dimension to the specified value (inclusive). Negative values start from the end, the default of -1 does no cropping. Only has an effect when depth is non-zero. The reason you might want to use this is changing `depth` will also effectively change the seed.
|
||||
* `tileable_height`: Makes the specified dimension tileable. (May or may not work correctly.)
|
||||
* `tileable_width`: " "
|
||||
* `tileable_depth`: " "
|
||||
* `blend`: Blending function used when generating Perlin noise. When set to values other than LERP may not work at all or may not actually generate Perlin noise. If you have `ComfyUI-bleh` there will be many more blending options (see [Integration](#integration)).
|
||||
* `pattern_break_blend`: Blending function used to blend pattern broken noise with raw noise. If you have `ComfyUI-bleh` there will be many more blending options (see [Integration](#integration)).
|
||||
* `depth_over_channels`: When disabled, each channel will have its own separate 3D noise pattern. When enabled, depth is multiplied by the number of channels and each channel is a slice of depth. Only has an effect when depth is non-zero.
|
||||
* `pad_height`: Pads the specified dimension by the size. Equal padding will be added on both sides and cropped out after generation.
|
||||
* `pad_width`: " "
|
||||
* `pad_depth`: " "
|
||||
* `initial_amplitude`: Controls the amplitude for the first octave. The amplitude gets multiplied by `persistence` after each octave.
|
||||
* `initial_frequency_height`: Controls the frequency for the first octave for the this axis. The frequency gets multiplied by `lacunarity` after each octave.
|
||||
* `initial_frequency_width`: " "
|
||||
* `initial_frequency_depth`: " "
|
||||
* `normalize`: Controls whether the output noise is normalized after generation.
|
||||
* `device`: Controls what device is used to generate the noise. GPU noise may be slightly faster but you will get different results on different GPUs.
|
||||
|
||||
+11
-4
@@ -1,8 +1,15 @@
|
||||
from .py import nodes
|
||||
|
||||
from .py import custom_noise
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"ComposableSampler": nodes.ComposableSampler,
|
||||
"ComposableStepSampler": nodes.ComposableStepSampler,
|
||||
}
|
||||
"OCS Sampler": nodes.SamplerNode,
|
||||
"OCS Substeps": nodes.SubstepsNode,
|
||||
"OCS Group": nodes.GroupNode,
|
||||
"OCS Param": nodes.ParamNode,
|
||||
"OCS MultiParam": nodes.MultiParamNode,
|
||||
"OCS ModelSetMaxSigma": nodes.ModelSetMaxSigmaNode,
|
||||
"OCS SimpleRestartSchedule": nodes.SimpleRestartSchedule,
|
||||
"OCS ApplyFilterLatent": nodes.ApplyFilterLatent,
|
||||
"OCS ApplyFilterImage": nodes.ApplyFilterImage,
|
||||
} | custom_noise.NODE_CLASS_MAPPINGS
|
||||
__all__ = ["NODE_CLASS_MAPPINGS"]
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
@@ -0,0 +1,166 @@
|
||||
# OCS Expressions
|
||||
|
||||
See [Filters](filter.md) for places where expressions apply.
|
||||
|
||||
## Expressions
|
||||
|
||||
OCS implements a simple expression language.
|
||||
|
||||
Supported math operators: `+`, `-`, `*`, `/`, `//` (integer division), `**` (power)
|
||||
|
||||
Supported logic operators: `||`, `&&`, `==`, `!=`, `>`, `<`, `>=`, `<=`
|
||||
|
||||
Operator precedence should generally work the way you'd expect.
|
||||
|
||||
You may surround a function name with backticks to turn it into a binary operator (only for functions that take two arguments).
|
||||
|
||||
Functions are called via `name(param1, param2)`. Keyword arguments may be passed using the `:>` operator. Example:
|
||||
`name(param1, key :> 123, key2 :> otherfunction(10))`.
|
||||
|
||||
Symbols (simple string type) are defined using `'symbol_name` - note the solitary single quote. They may not contain spaces.
|
||||
|
||||
`;` can be used to sequence operations. I.E. `exp1 ; exp2` evaluates `exp1`, then `exp2` and then result of the expression is whatever `exp2` returned.
|
||||
|
||||
`:=` is used to assign to a temporary variable (see `set_var` below).
|
||||
|
||||
The expression language supports a C/JavaScript style ternary operator: `condition ? true_branch : false_branch` is the equivalent of `if(condition, true_branch, false_branch)`.
|
||||
|
||||
Like Python, a parenthesized expression with a trailing comma can be used to create an empty tuple. Example: `(1,)`
|
||||
|
||||
## Filter Variables
|
||||
|
||||
Indexes like `step` are zero-based: `0` will be the first step.
|
||||
|
||||
### Basic Variables
|
||||
|
||||
* `default`: Context specific default value. i.e. if used in an `input` expression this would be `x`, if used for `output` this would be the current result.
|
||||
* `step`: Current step.
|
||||
* `substep`: Current substep.
|
||||
* `dt`: `sigma_next - sigma`
|
||||
* `sigma_idx`: Index of the current sigma. Note that when using restarts this will be based on the restart sigma chunks, not full sigma list.
|
||||
* `sigma`: The current sigma.
|
||||
* `sigma_next`: The next sigma.
|
||||
* `sigma_down`: The down sigma in ancestral sampling.
|
||||
* `sigma_up`: The up sigma in ancestral sampling.
|
||||
* `sigma_prev`: The previous sigma (may be `None`).
|
||||
* `hist_len`: Current available history length. "Now" counts as one.
|
||||
* `sigma_min`: The minimum sigma (based on the full list).
|
||||
* `sigma_max`: The maximum sigma (based on the full list).
|
||||
* `step_pct`: Percentage for the current step (based on total steps).
|
||||
* `total_steps`: Total steps to be sampled.
|
||||
|
||||
### Extended Variables
|
||||
|
||||
* `denoised`: From the current step or substep. May not be available in model `input` or group `pre_filter`.
|
||||
* `cond`: From the current step or substep. May not be available in model `input` or group `pre_filter`.
|
||||
* `uncond`: From the current step or substep. May not be available in model `input` or group `pre_filter`.
|
||||
* `denoised_prev`: Only available when model history exists.
|
||||
* `cond_prev`: Only available when model history exists.
|
||||
* `cond_prev`: Only available when model history exists.
|
||||
|
||||
### Model Filter Variables
|
||||
|
||||
* `model_call`: Only applicable to `model` filters, will be the model call index. I.E. if the sampler calls the model three times, the filter would be called with model call indexes `0`, `1` and `2`.
|
||||
|
||||
Available in model filters, with the exception of the `input` filter.
|
||||
|
||||
* `denoised_curr`
|
||||
* `cond_curr`
|
||||
* `uncond_curr`
|
||||
|
||||
## Basic Expression Functions
|
||||
|
||||
| | Name | Input | Output |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
|⬤| `all` | `B`\* | `B` |
|
||||
| <td colspan=3 align=left>Evaluates to true if all its arguments evaluate to true. <br/> **Example:** `all(x > 1, y < 1)`</td> |
|
||||
|⬤| `any` | `B`\* | `B` |
|
||||
| <td colspan=3 align=left>Evaluates to true if any of its arguments evaluate to true. <br/> **Example:** `any(x > 1, y < 1)`</td> |
|
||||
|⬤| `between` | value:`N`, from:`N`, to:`N` | `B` |
|
||||
| <td colspan=3 align=left>Boolean range checking. <br/> **Example:** `between(value, low, high)`</td> |
|
||||
|⬤| `comment` | `*` | `null` |
|
||||
| <td colspan=3 align=left>Ignores any arguments passed to it (they won't be evaluated at all but must parse as a valid expression) and returns `None`</td> |
|
||||
|⬤| `dict` | `*`* | `dict` |
|
||||
| <td colspan=3 align=left>Constructs a dictionary from its keyword arguments. _Note_: You may not pass positional arguments. <br/> **Example:** `dict(key1 :> value1, keyN :> valueN)` |
|
||||
|⬤| `get` | name:`SY`, fallback:`*` | `*` |
|
||||
| <td colspan=3 align=left>Returns a variable if set, otherwise the fallback. <br/> **Example:** `get('somevar, 123)`</td> |
|
||||
|⬤| `if` | condition:`B`, then:`*`, else:`*` | `*` |
|
||||
| <td colspan=3 align=left>Conditional expressions. <br/> **Example:** `if(condition, true_expression, false_expression)`</td> |
|
||||
|⬤| `index` | index:`IDX`, value:`S \| T` | `*` |
|
||||
| <td colspan=3 align=left>Index function.</td> |
|
||||
|⬤| `is_set` | name:`SY` | `B` |
|
||||
| <td colspan=3 align=left>Tests whether a variable is set.</td> |
|
||||
|⬤| `max` | values:`SN` | `N` |
|
||||
| <td colspan=3 align=left>Maximum operation. _Note_: Takes one sequence argument. <br/> **Example:** `min((1, 2, 3))`</td> |
|
||||
|⬤| `min` | values: `SN` | `N` |
|
||||
| <td colspan=3 align=left>Minimum operation. _Note_: Takes one sequence argument. <br/> **Example:** `max((1, 2, 3))`</td> |
|
||||
|⬤| `mod` | lhs:`N`, rhs:`N` | `N` |
|
||||
| <td colspan=3 align=left>Modulus operation: <br/> **Example:** `mod(5, 2)`</td> |
|
||||
|⬤| `neg` | `N` | `N` |
|
||||
| <td colspan=3 align=left>Negation. <br/> **Example:** `neg(2)`</td> |
|
||||
|⬤| `not` | `B` | `B` |
|
||||
| <td colspan=3 align=left>Boolean negation</td> |
|
||||
|⬤| `s_` | start:`I(null)`, end:`I(null)`, step:`I(null)` | `slice` |
|
||||
| <td colspan=3 align=left>Creates a slice object from the `start`, `end`, `step` values. See Numpy [s_](https://numpy.org/doc/stable/reference/generatednumpy.s_.html)</td> |
|
||||
|⬤| `set_var` | `SY`, `*` | `*` |
|
||||
| <td colspan=3 align=left>Sets a temporary variable to the specified value and returns the value. Alias for the `:=` assignment operator. <br/> **Example**: `test1 := 2; set_var('test2, 10); test1 * test2`</td> |
|
||||
|⬤| `unsafe_call` | `callable`, `*`\* | `*` |
|
||||
| <td colspan=3 align=left>Allows calling an arbitrary callable. <br/> **Example:** `unsafe_call(some_callable, arg1, arg2, kwarg1 :> 123)`</td>
|
||||
|
||||
**Legend**: `B`=boolean, `N`=numeric, `NS`=scalar numeric, `I`=integer, `F`=float, `T`=tensor, `S`=sequence, `SN`=numeric sequence, `SY`=symbol, `*`=any -- parenthized values indicate argument defaults. `*` following the type indicates variable length arguments. For functions that take keyword arguments, the type will be written like "_name: `TYPE(default_value)`_".
|
||||
|
||||
## Tensor Expression Functions
|
||||
|
||||
*Tensor dimensions hint*: Most tensors you'll be dealing with are laid out as `batch`, `channels`, `height`, `width`. Negative indexes start from the end, so dimension `-1` would mean _width_ just the same as `3`.
|
||||
|
||||
| | Name | Input | Output |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
|⬤| `t_bleh_enhance` | tensor:`T`, mode:`SY`, scale:`N(1.0)` | `T`
|
||||
| <td colspan=3 align=left>Available if you have the [ComfyUI-bleh](https://github.com/blepping/ComfyUI-bleh) node pack installed. See [Filtering](filter.md#bleh_enhance). <br/> **Example:** `bleh_enhance(some_tensor, 'bandpass, 0.5)`</td> |
|
||||
|⬤| `t_blend` | tensor1:`T`, tensor2:`T`, scale:`N(0.5)`, mode:`SY(lerp)` | `T` |
|
||||
| <td colspan=3 align=left>Tensor blend operation. <br/> **Example:** `t_blend(t1, t2, 0.75, 'lerp)`</td> |
|
||||
|⬤| `t_contrast_adaptive_sharpening` | tensor:`T`, scale:`N(0.5)` | `T` |
|
||||
| <td colspan=3 align=left>Contrast adaptive sharpening. _Note_: Not recommended to call on noisy tensors (so `denoised` but probably not `x`). <br/> **Example:** `t_contrast_adaptive_sharpening(some_tensor, 0.1)`</td> |
|
||||
|⬤| `t_flip` | tensor:`T`, dim:`NS`, mirror:`B(false)` | `T` |
|
||||
| <td colspan=3 align=left>Flips a tensor on the specified dimension. If the third argument is true, it will be mirrored around the center in that dimension. <br/> **Example:** `t_flip(some_tensor, -1, true)`</td> |
|
||||
|⬤| `t_mean` | tensor:`T`, dim:`SN(-3, -2, -1)` | `T` |
|
||||
| <td colspan=3 align=left>Tensor mean, second argument is dimensions. <br/> **Example:** `t_mean(some_tensor, (-2, -1))`</td> |
|
||||
|⬤| `t_noise` | tensor:`T`, type:`SY(gaussian)` | `T` |
|
||||
| <td colspan=3 align=left>Generates un-normalized noise (use `t_norm` if you want to normalize it). If you have ComfyUI-sonar you can use any noise type that supports, otherwise only `gaussian`. The generated noise will have the same shape as the supplied tensor (hopefully, may not be true for every exotic noise type but at least should be broadcastable to the tensor). <br/> Example: `t_noise(some_tensor, 'pyramid)`</td> |
|
||||
|⬤| `t_norm` | tensor:`T`, factor:`N(1.0)`, dim:`SN(-3, -2, -1)` | `T` |
|
||||
| <td colspan=3 align=left>Tensor normalization (subtracts mean, divides by std). <br/> **Example:** `t_norm(some_tensor, 1.0, (-2, -1))`</td> |
|
||||
|⬤| `t_sonar_power_filter` | tensor:`T`, filter:`dict` | `T` |
|
||||
| <td colspan=3 align=left>Available if you have [ComfyUI-sonar](https://github.com/blepping/ComfyUI-sonar) installed. See [Filtering](filter.md#sonar_power_filter). Constructs a power filter from a dictionary argument. _Note_: May be slow as the filter is reconstructed on every evaluation. <br/> **Example:** `t_sonar_power_filter(some_tensor, dict(alpha :> 0.1, min_freq :> 0.2, max_freq :> 0.6))`</td> |
|
||||
|⬤| `t_roll` | tensor:`T`, amount:`NS(0.5)`, dim:`SN((-2,))` | `T` |
|
||||
| <td colspan=3 align=left>Rolls a tensor along the specified dimensions. If amount is >= -1.0 and < 1.0 this will be interpreted as a percentage. <br/> **Example:** `t_roll(some_tensor, 10, (-2,))`</td> |
|
||||
|⬤| `t_scale` | tensor:`T`, scale:`SN \| NS`, mode:`SY(bicubic)`, absolute_scale:`B(false)` | `T` |
|
||||
| <td colspan=3 align=left>Scales a tensor. If scale is a tuple, it will be interpreted as `(height, width)`. When `absolute_scale` is not set, the scales will be interpreted as percentages otherwise absolute values will be used. <br/> Example: `t_scale(some_tensor, (0.75, 0.5), 'bilinear)`</td> |
|
||||
|⬤| `t_scale_nnlatentupscale` | tensor:`T`, mode:`SY(sd1)`, scale:`SN(2.0)` | `T` |
|
||||
| <td colspan=3 align=left>Available if you have [ComfyUi_NNLatentUpscale](https://github.com/Ttl/ComfyUi_NNLatentUpscale) installed. `mode` must be one of `sd1` or `sdxl`. `scale` should be between 1.0 and 2.0 (may or may not work out of that range).<br/> **Example:** `t_scale_nnlatentupscale(some_tensor, 'sdxl, 1.5)`</td> |
|
||||
|⬤| `t_shape` | tensor:`T` | `SN` |
|
||||
| <td colspan=3 align=left>Returns a tensor's shape as a tuple. <br/> Example: `shp := t_shape(some_tensor); width := shp[-1]; height := shp[-2]`</td> |
|
||||
|⬤| `t_std` | tensor:`T`, dim:`SN(-3, -2, -1)` | `T` |
|
||||
| <td colspan=3 align=left>Tensor std, second argument is dimensions. <br/> **Example:** `t_std(some_tensor, (-2, -1))`</td> |
|
||||
|⬤| `t_taesd_decode` | tensor:`T`, mode:`SY(sd15)` | `T` |
|
||||
| <td colspan=3 align=left>Decodes a latent tensor used TAESD. Mode must be one of `sd15`, `sdxl`. Only works if the appropriate models are in `vae_approx` <br/> **Example:** `t_taesd_decode(some_tensor, 'sd15)`</td> |
|
||||
|⬤| `unsafe_tensor_method` | `T`, `SY`, `*`\* | `*` |
|
||||
| <td colspan=3 align=left>Unsafe tensor method call. See note below. <br/> **Example:** `unsafe_tensor_method(some_tensor, 'mul, 10)`</td> |
|
||||
|⬤| `unsafe_torch` | path:`SY` | `*` |
|
||||
| <td colspan=3 align=left>Unsafe Torch module attribute access. See note below. <br/> **Example:** `unsafe_torch('nn.functional.interpolate)`</td> |
|
||||
|
||||
**Note on `unsafe_tensor_method` and `unsafe_torch`**: These functions are disabled by default. If the environment variable `COMFYUI_OCS_ALLOW_UNSAFE_EXPRESSIONS` is set to anything then you can use `unsafe_tensor_method` with a whitelisted set of methods (best effort to avoid anything actually unsafe). If the environment variable `COMFYUI_OCS_ALLOW_ALL_UNSAFE` is set to anything then `unsafe_torch` is enabled and `unsafe_tensor_method` will allow calling any method. ***WARNING***: Allowing _all_ unsafe with workflows you don't trust is _not_ recommended and a malicious workflow will likely have access to anything ComfyUI can access. It is effectively the same as letting the workflow run an arbitrary script on your system.
|
||||
|
||||
Documentation TBD (check the source if you want to use them now): `t_copysign`, `t_gaussianblur2d`, `t_rgb_latent`, `t_snf_guidance`
|
||||
|
||||
## Image Expression Functions
|
||||
|
||||
`IMG` used here to donate the type for functions that take an image. This may actually be an image batch rather than a single image.
|
||||
|
||||
| | Name | Input | Output |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
|⬤| `img_pil_resize` | image:`IMG`, size:`SN \| NS`, resample_mode:`SY(bicubic)`, absolute_scale:`B(false)` | `IMG` |
|
||||
| <td colspan=3 align=left>Scales an image batch using Pillow's [`Image.resize`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.resize) function (follow link for information about resample modes, etc). If scale is a tuple, it will be interpreted as `(height, width)`. When `absolute_scale` is not set, the scales will be interpreted as percentages otherwise absolute values will be used. <br/> Example: `img_pil_resize(image_batch, (0.75, 0.5), 'lanczos)`</td> |
|
||||
|⬤| `img_shape` | image:`IMG` | `SN` |
|
||||
| <td colspan=3 align=left>Returns an image's shape as a tuple. Will fail if all the images in the batch aren't the same size. <br/> Example: `shp := img_shape(image_batch); width := shp[-1]; height := shp[-2]`</td> |
|
||||
|⬤| `img_taesd_encode` | image:`IMG`, reference_latent: `T`, mode:`SY(sd15)` | `T` |
|
||||
| <td colspan=3 align=left>Encodes an image batch into a latent tensor. The reference latent is only used to determine what device and type the output should be. Mode must be one of `sd15`, `sdxl`. Only works if the appropriate models are in `vae_approx`. <br/> **Example:** `img_taesd_encode(image_batch, some_tensor, 'sd15)`</td> |
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
# OCS Filters
|
||||
|
||||
Filters allow changing sampler inputs/outputs, model input/outputs, generated noise and so on. They are
|
||||
configured by the advanced YAML/JSON parameter block in the node.
|
||||
|
||||
## Filter Support
|
||||
|
||||
### `OCS Substeps`
|
||||
|
||||
Set via the `pre_filter` and `post_filter` keys.
|
||||
|
||||
### `OCS Group`
|
||||
|
||||
Set via the `pre_filter` and `post_filter` keys.
|
||||
|
||||
*Note*: Since the group pre-filter may be called before any model calls, variables like `denoised` may not be available
|
||||
in expressions.
|
||||
|
||||
### `OCS Sampler`
|
||||
|
||||
**Noise**
|
||||
|
||||
```yaml
|
||||
noise:
|
||||
# Or set to a valid filter definition.
|
||||
filter: null
|
||||
```
|
||||
|
||||
**Model**
|
||||
|
||||
*Note*: Since the model filters may be called before any other model calls, variables like `denoised` may not be available
|
||||
in expressions. With the exception of the `input` filter you will have access to `denoised_curr`, `cond_curr`, etc.
|
||||
See [Expressions](expression.md#model-filter-variables).
|
||||
|
||||
```yaml
|
||||
model:
|
||||
filter:
|
||||
# Applies to the input passed to the model.
|
||||
input: null
|
||||
|
||||
# Applies to denoised output.
|
||||
denoised: null
|
||||
|
||||
# Applies to JVP denoised output (only used by TTM sampler)
|
||||
jdenoised: null
|
||||
|
||||
# Applies to cond output.
|
||||
cond: null
|
||||
|
||||
# Applies to uncond output.
|
||||
uncond: null
|
||||
|
||||
```
|
||||
|
||||
### Immiscible
|
||||
|
||||
`immiscible` is a special type of filter: in this case, you do not set `filter_type`. Normal filter keys
|
||||
apply in the places where `immiscible` can be set.
|
||||
|
||||
## Filter Definitions
|
||||
|
||||
For information about expressions, see [Expressions](expression.md).
|
||||
|
||||
A basic filter supports these keys:
|
||||
|
||||
```yaml
|
||||
enabled: true
|
||||
|
||||
filter_type: simple
|
||||
|
||||
# Expression that is evaluated to determine whether the filter applies. May be null.
|
||||
# If set, should evaluate to a boolean.
|
||||
when: null
|
||||
|
||||
blend_mode: lerp
|
||||
|
||||
# Blend strength applied to output.
|
||||
strength: 1.0
|
||||
|
||||
# Input expression. input, ref, output and final should evaluate to a tensor.
|
||||
input: default
|
||||
|
||||
# Reference expression (only used for immiscible noise currently).
|
||||
ref: default
|
||||
|
||||
# Output expression.
|
||||
output: default
|
||||
|
||||
# Final expression - occurs *after* blending.
|
||||
final: default
|
||||
```
|
||||
|
||||
There may be additional keys depending on the filter type.
|
||||
|
||||
If you have [ComfyUI-bleh](https://github.com/blepping/ComfyUI-bleh) available, you can use any blend mode it supports. Otherwise OCS provides these built-in blend modes: `lerp`, `a_only`, `b_only`. _Note_: `a` is considered the original value, `b` the changed value. `a_only` and `b_only` will still scale their output by the `strength`.
|
||||
|
||||
## Filter Types
|
||||
|
||||
### `simple`
|
||||
|
||||
Base filter, no special behavior. No additional parameters.
|
||||
|
||||
### `blend`
|
||||
|
||||
Blends the result of two other filters.
|
||||
|
||||
Keys:
|
||||
|
||||
```yaml
|
||||
# No default, value for example purpose only.
|
||||
filter1:
|
||||
filter_type: simple
|
||||
|
||||
# No default, value for example purpose only.
|
||||
filter2:
|
||||
filter_type: simple
|
||||
```
|
||||
|
||||
### `list`
|
||||
|
||||
A list of filters. The output of the previous is given to the next as input.
|
||||
The `list` filter's blend applies to the output from the final filter in the list.
|
||||
|
||||
Keys:
|
||||
|
||||
```yaml
|
||||
# Values for example only, default is an empty list.
|
||||
filters:
|
||||
- filter_type: simple
|
||||
strength: 1.0
|
||||
- filter_type: simple
|
||||
strength: 1.0
|
||||
```
|
||||
|
||||
### `bleh_enhance`
|
||||
|
||||
Available if you have the [ComfyUI-bleh](https://github.com/blepping/ComfyUI-bleh) node pack installed. See:
|
||||
https://github.com/blepping/ComfyUI-bleh#enhancement-types
|
||||
|
||||
Keys:
|
||||
|
||||
```yaml
|
||||
enhance_mode: null
|
||||
enhance_scale: 1.0
|
||||
```
|
||||
|
||||
### `bleh_ops`
|
||||
|
||||
Available if you have the [ComfyUI-bleh](https://github.com/blepping/ComfyUI-bleh) node pack installed. See:
|
||||
https://github.com/blepping/ComfyUI-bleh#blehblockops
|
||||
|
||||
Keys:
|
||||
|
||||
```yaml
|
||||
# May be specified as a string containing the YAML rule definitions or inline.
|
||||
# Values for example only, default is an empty list of ops.
|
||||
ops:
|
||||
- if:
|
||||
to_percent: 0.5
|
||||
ops: # Not recommended to actually do this.
|
||||
- [flip, { direction: h }]
|
||||
- [roll, { direction: channels, amount: -2 }]
|
||||
```
|
||||
|
||||
### `sonar_power_filter`
|
||||
|
||||
Available if you have [ComfyUI-sonar](https://github.com/blepping/ComfyUI-sonar) installed. See:
|
||||
https://github.com/blepping/ComfyUI-sonar/blob/main/docs/advanced_power_noise.md
|
||||
|
||||
Keys:
|
||||
|
||||
```yaml
|
||||
power_filter:
|
||||
mix: 1.0
|
||||
normalization_factor: 1.0
|
||||
common_mode: 0.0
|
||||
channel_correlation: "1,1,1,1,1,1"
|
||||
alpha: 0.0
|
||||
min_freq: 0.0
|
||||
max_freq: 0.7071
|
||||
stretch: 1.0
|
||||
rotate: 0.0
|
||||
pnorm: 2.0
|
||||
scale: 1.0
|
||||
compose_mode: max
|
||||
|
||||
# If specified should be another power filter definition.
|
||||
compose_with: null
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
from . import nodes
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"OCSNoise PerlinSimple": nodes.PerlinSimpleNode,
|
||||
"OCSNoise PerlinAdvanced": nodes.PerlinAdvancedNode,
|
||||
"OCSNoise ImmiscibleReference": nodes.ImmiscibleReferenceNoiseNode,
|
||||
"OCSNoise to SONAR_CUSTOM_NOISE": nodes.ToSonarNode,
|
||||
"OCSNoise Conditioning": nodes.NoiseConditioningNode,
|
||||
"OCSNoise OverrideSamplerNoise": nodes.SamplerNodeConfigOverride,
|
||||
"OCSNoise ExpressionFilteredNoise": nodes.ExpressionFilteredNoiseNode,
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import abc
|
||||
import torch
|
||||
|
||||
from typing import Callable, Any
|
||||
|
||||
from ..external import IntegratedNode
|
||||
from ..noise import scale_noise
|
||||
from ..nodes import WILDCARD_NOISE, NOISE_INPUT_TYPES_HINT
|
||||
|
||||
|
||||
class CustomNoiseItemBase(abc.ABC):
|
||||
def __init__(self, factor, **kwargs):
|
||||
self.factor = factor
|
||||
self.keys = set(kwargs.keys())
|
||||
for k, v in kwargs.items():
|
||||
setattr(self, k, v)
|
||||
|
||||
def clone_key(self, k):
|
||||
return getattr(self, k)
|
||||
|
||||
def clone(self):
|
||||
return self.__class__(self.factor, **{k: self.clone_key(k) for k in self.keys})
|
||||
|
||||
def set_factor(self, factor):
|
||||
self.factor = factor
|
||||
return self
|
||||
|
||||
def get_normalize(self, k, default=None):
|
||||
val = getattr(self, k, None)
|
||||
return default if val is None else val
|
||||
|
||||
@abc.abstractmethod
|
||||
def make_noise_sampler(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
sigma_min=None,
|
||||
sigma_max=None,
|
||||
seed=None,
|
||||
cpu=True,
|
||||
normalized=True,
|
||||
):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class CustomNoiseChain:
|
||||
def __init__(self, items=None):
|
||||
self.items = items if items is not None else []
|
||||
|
||||
def clone(self):
|
||||
return CustomNoiseChain(
|
||||
[i.clone() for i in self.items],
|
||||
)
|
||||
|
||||
def add(self, item):
|
||||
if item is None:
|
||||
raise ValueError("Attempt to add nil item")
|
||||
self.items.append(item)
|
||||
|
||||
@property
|
||||
def factor(self):
|
||||
return sum(abs(i.factor) for i in self.items)
|
||||
|
||||
def rescaled(self, scale=1.0):
|
||||
divisor = self.factor / scale
|
||||
divisor = divisor if divisor != 0 else 1.0
|
||||
result = self.clone()
|
||||
if divisor != 1:
|
||||
for i in result.items:
|
||||
i.set_factor(i.factor / divisor)
|
||||
return result
|
||||
|
||||
@torch.no_grad()
|
||||
def make_noise_sampler(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
sigma_min=None,
|
||||
sigma_max=None,
|
||||
seed=None,
|
||||
cpu=True,
|
||||
normalized=True,
|
||||
) -> Callable:
|
||||
noise_samplers = tuple(
|
||||
i.make_noise_sampler(
|
||||
x,
|
||||
sigma_min,
|
||||
sigma_max,
|
||||
seed=seed,
|
||||
cpu=cpu,
|
||||
normalized=False,
|
||||
)
|
||||
for i in self.items
|
||||
)
|
||||
if not noise_samplers or not all(noise_samplers):
|
||||
raise ValueError("Failed to get noise sampler")
|
||||
factor = self.factor
|
||||
|
||||
def noise_sampler(sigma, sigma_next):
|
||||
result = None
|
||||
for ns in noise_samplers:
|
||||
noise = ns(sigma, sigma_next)
|
||||
if result is None:
|
||||
result = noise
|
||||
else:
|
||||
result += noise
|
||||
return scale_noise(result, factor, normalized=normalized)
|
||||
|
||||
return noise_sampler
|
||||
|
||||
|
||||
class CustomNoiseNodeBase(metaclass=IntegratedNode):
|
||||
DESCRIPTION = "An Overly Complicated Sampling custom noise item."
|
||||
RETURN_TYPES = ("OCS_NOISE",)
|
||||
OUTPUT_TOOLTIPS = ("A custom noise chain.",)
|
||||
CATEGORY = "OveryComplicatedSampling/noise"
|
||||
FUNCTION = "go"
|
||||
|
||||
@abc.abstractmethod
|
||||
def get_item_class(self):
|
||||
raise NotImplementedError
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls, *, include_rescale=True, include_chain=True):
|
||||
result = {
|
||||
"required": {
|
||||
"factor": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": -100.0,
|
||||
"max": 100.0,
|
||||
"step": 0.001,
|
||||
"round": False,
|
||||
"tooltip": "Scaling factor for the generated noise of this type.",
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {},
|
||||
}
|
||||
if include_rescale:
|
||||
result["required"] |= {
|
||||
"rescale": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.0,
|
||||
"min": 0.0,
|
||||
"max": 100.0,
|
||||
"step": 0.001,
|
||||
"round": False,
|
||||
"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.",
|
||||
},
|
||||
),
|
||||
}
|
||||
if include_chain:
|
||||
result["optional"] |= {
|
||||
"ocs_noise_opt": (
|
||||
WILDCARD_NOISE,
|
||||
{
|
||||
"tooltip": f"Optional input for more custom noise items.\n{NOISE_INPUT_TYPES_HINT}",
|
||||
},
|
||||
),
|
||||
}
|
||||
return result
|
||||
|
||||
def go(
|
||||
self,
|
||||
factor=1.0,
|
||||
rescale=0.0,
|
||||
ocs_noise_opt=None,
|
||||
**kwargs: dict[str, Any],
|
||||
):
|
||||
nis = ocs_noise_opt.clone() if ocs_noise_opt else CustomNoiseChain()
|
||||
if factor != 0:
|
||||
nis.add(self.get_item_class()(factor, **kwargs))
|
||||
return (nis if rescale == 0 else nis.rescaled(rescale),)
|
||||
|
||||
|
||||
class NormalizeNoiseNodeMixin:
|
||||
@staticmethod
|
||||
def get_normalize(val: str) -> None | bool:
|
||||
return None if val == "default" else val == "forced"
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,156 @@
|
||||
import torch
|
||||
|
||||
from ..noise import scale_noise, ImmiscibleNoise
|
||||
from .base import CustomNoiseItemBase
|
||||
|
||||
|
||||
class ImmiscibleReferenceItem(CustomNoiseItemBase):
|
||||
def __init__(
|
||||
self,
|
||||
factor,
|
||||
*,
|
||||
size: int,
|
||||
batching: str,
|
||||
normalize_ref_scale: float,
|
||||
normalize_noise_scale: float,
|
||||
maximize: bool,
|
||||
distance_scale: float,
|
||||
distance_scale_ref: float,
|
||||
blend: float,
|
||||
noise,
|
||||
blend_function,
|
||||
normalize=None,
|
||||
reference=None,
|
||||
custom_noise_blend=None,
|
||||
custom_noise_ref=None,
|
||||
):
|
||||
if reference is None and custom_noise_ref is None:
|
||||
raise ValueError(
|
||||
"Either the reference latent or custom_noise_ref need to be supplied."
|
||||
)
|
||||
if reference is not None and custom_noise_ref is not None:
|
||||
raise ValueError(
|
||||
"One of reference latent or custom_noise_ref need to be supplied, but not both."
|
||||
)
|
||||
super().__init__(
|
||||
factor,
|
||||
size=size,
|
||||
batching=batching,
|
||||
normalize_ref_scale=normalize_ref_scale,
|
||||
normalize_noise_scale=normalize_noise_scale,
|
||||
maximize=maximize,
|
||||
distance_scale=distance_scale,
|
||||
distance_scale_ref=distance_scale_ref,
|
||||
blend=blend,
|
||||
blend_function=blend_function,
|
||||
noise=noise,
|
||||
reference=reference,
|
||||
normalize=normalize,
|
||||
custom_noise_ref=custom_noise_ref,
|
||||
custom_noise_blend=custom_noise_blend,
|
||||
)
|
||||
|
||||
def clone_key(self, k):
|
||||
if k == "noise":
|
||||
return self.noise.clone()
|
||||
if k == "reference" and self.reference is not None:
|
||||
return self.reference.clone()
|
||||
if k == "custom_noise_ref" and self.custom_noise_ref is not None:
|
||||
return self.custom_noise_ref.clone()
|
||||
if k == "custom_noise_blend" and self.custom_noise_blend is not None:
|
||||
return self.custom_noise_blend.clone()
|
||||
return super().clone_key(k)
|
||||
|
||||
def make_noise_sampler(self, x, *args, normalized=True, **kwargs):
|
||||
factor = self.factor
|
||||
norm_noise_scale = self.normalize_noise_scale
|
||||
normalize = self.get_normalize("normalize", normalized)
|
||||
norm_ref = self.normalize_ref_scale
|
||||
|
||||
ns = self.noise.make_noise_sampler(x, *args, normalized=False, **kwargs)
|
||||
batching = self.batching
|
||||
if "_" in batching:
|
||||
batchings = batching.split("_")
|
||||
batching = batchings[0]
|
||||
dual_mode = True
|
||||
else:
|
||||
dual_mode = False
|
||||
immiscible = ImmiscibleNoise(
|
||||
size=self.size,
|
||||
batching=batching,
|
||||
distance_scale=self.distance_scale,
|
||||
distance_scale_ref=self.distance_scale_ref,
|
||||
maximize=self.maximize,
|
||||
)
|
||||
if dual_mode:
|
||||
immiscible2 = immiscible = ImmiscibleNoise(
|
||||
size=self.size,
|
||||
batching=batchings[-1],
|
||||
distance_scale=self.distance_scale,
|
||||
distance_scale_ref=self.distance_scale_ref,
|
||||
maximize=self.maximize,
|
||||
)
|
||||
if self.reference is not None:
|
||||
ns_ref = None
|
||||
ref_latent = self.reference.detach().clone().to(x)
|
||||
if norm_ref:
|
||||
ref_latent = scale_noise(ref_latent, norm_ref, normalized=True)
|
||||
else:
|
||||
ref_latent = None
|
||||
ns_ref = self.custom_noise_ref.make_noise_sampler(
|
||||
x, *args, normalized=False, **kwargs
|
||||
)
|
||||
blend = self.blend
|
||||
blend_function = self.blend_function
|
||||
blending = self.blend != 1.0
|
||||
if self.custom_noise_blend is not None and blending:
|
||||
ns_blend = self.custom_noise_blend.make_noise_sampler(
|
||||
x, *args, normalized=False, **kwargs
|
||||
)
|
||||
else:
|
||||
ns_blend = None
|
||||
repeat_count = max(1, self.size) + int(blending)
|
||||
batch_size = x.shape[0]
|
||||
blend_in_batch = blending and ns_blend is None
|
||||
|
||||
def noise_sampler(s, sn, *args, **kwargs):
|
||||
if ns_ref is not None:
|
||||
ref_latent = ns_ref(s, sn)
|
||||
if norm_ref:
|
||||
ref_latent = scale_noise(ref_latent, norm_ref, normalized=True)
|
||||
|
||||
noise_batch = torch.cat(tuple(ns(s, sn) for _ in range(repeat_count)))
|
||||
nb_input = scale_noise(
|
||||
noise_batch[batch_size * int(blend_in_batch) :],
|
||||
1.0 if norm_noise_scale == 0 else norm_noise_scale,
|
||||
normalized=norm_noise_scale != 0,
|
||||
)
|
||||
immiscible_noise = immiscible.unbatch(
|
||||
immiscible.immiscible(
|
||||
immiscible.batch(nb_input),
|
||||
immiscible.batch(ref_latent),
|
||||
),
|
||||
ref_latent.shape,
|
||||
)
|
||||
if dual_mode:
|
||||
immiscible_noise = (
|
||||
immiscible2.unbatch(
|
||||
immiscible2.immiscible(
|
||||
immiscible2.batch(nb_input),
|
||||
immiscible2.batch(ref_latent),
|
||||
),
|
||||
ref_latent.shape,
|
||||
)
|
||||
.add_(immiscible_noise)
|
||||
.mul_(0.5)
|
||||
)
|
||||
immiscible_noise = scale_noise(immiscible_noise, normalized=normalize)
|
||||
if blend != 1:
|
||||
immiscible_noise = blend_function(
|
||||
noise_batch[:batch_size] if ns_blend is None else ns_blend(s, sn),
|
||||
immiscible_noise,
|
||||
blend,
|
||||
)
|
||||
return scale_noise(immiscible_noise, factor, normalized=normalize)
|
||||
|
||||
return noise_sampler
|
||||
@@ -0,0 +1,495 @@
|
||||
import itertools
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
from comfy import model_management
|
||||
|
||||
from .. import filtering
|
||||
from ..latent import normalize_to_scale
|
||||
from ..noise import scale_noise
|
||||
from .base import CustomNoiseItemBase, NormalizeNoiseNodeMixin
|
||||
|
||||
# Perlin generation routines based on https://github.com/Extraltodeus/noise_latent_perlinpinpin which was based on https://gist.github.com/vadimkantorov/ac1b097753f217c5c11bc2ff396e0a57 which was based on https://github.com/pvigier/perlin-numpy
|
||||
|
||||
|
||||
def smoothstep_function(t):
|
||||
return 6 * t**5 - 15 * t**4 + 10 * t**3
|
||||
|
||||
|
||||
class DEFAULTS:
|
||||
depth = 16
|
||||
res = ((1,), (1,), (1,))
|
||||
octaves = 2
|
||||
persistence = (1.0,)
|
||||
lacunarity = ((2,), (2,), (2,))
|
||||
initial_amplitude = 1.0
|
||||
initial_frequency = (1.0, 1.0, 1.0)
|
||||
break_pattern = 1.0
|
||||
detail_level = 0.0
|
||||
tileable = (False, False, False)
|
||||
fade = smoothstep_function
|
||||
blend = "lerp"
|
||||
pattern_break_blend = "lerp"
|
||||
depth_over_channels = False
|
||||
initial_depth = 0
|
||||
wrap_depth = 0
|
||||
max_depth = -1
|
||||
pad = (0, 0, 0)
|
||||
generator = None
|
||||
device = "default"
|
||||
|
||||
@classmethod
|
||||
def get_commasep(cls, key, idx=None):
|
||||
val = getattr(cls, key)
|
||||
if idx is not None:
|
||||
val = val[idx]
|
||||
return ", ".join(repr(v) for v in val)
|
||||
|
||||
|
||||
def rand_perlin(
|
||||
shape,
|
||||
res,
|
||||
*,
|
||||
tileable=DEFAULTS.tileable,
|
||||
fade=DEFAULTS.fade,
|
||||
blend=torch.lerp,
|
||||
generator=DEFAULTS.generator,
|
||||
device=DEFAULTS.device,
|
||||
):
|
||||
dims = len(res)
|
||||
didxs = tuple(range(dims))
|
||||
delta, d = zip(*((res[i] / shape[i], int(round(shape[i] / res[i]))) for i in didxs))
|
||||
|
||||
grid = (
|
||||
torch.stack(
|
||||
torch.meshgrid(*(torch.arange(0, res[i], delta[i]) for i in didxs)),
|
||||
dim=-1,
|
||||
)
|
||||
% 1
|
||||
).to(device=device)
|
||||
|
||||
noise = (
|
||||
2
|
||||
* math.pi
|
||||
* torch.rand(
|
||||
max(1, dims - 1),
|
||||
*(round(res[i]) + 1 for i in didxs),
|
||||
generator=generator,
|
||||
device=device,
|
||||
)
|
||||
)
|
||||
if dims == 1:
|
||||
gradients = torch.cos(noise[0])
|
||||
elif dims == 2:
|
||||
gradients = torch.stack((torch.cos(noise[0]), torch.sin(noise[0])), dim=-1)
|
||||
elif dims == 3:
|
||||
gradients = torch.stack(
|
||||
(
|
||||
torch.sin(noise[0]) * torch.cos(noise[1]),
|
||||
torch.sin(noise[0]) * torch.sin(noise[1]),
|
||||
torch.cos(noise[0]),
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
elif dims == 4:
|
||||
# No idea if this makes sense.
|
||||
gradients = torch.stack(
|
||||
(
|
||||
torch.sin(noise[0]) * torch.cos(noise[1]),
|
||||
torch.sin(noise[0]) * torch.sin(noise[1]),
|
||||
torch.sin(noise[1]) * torch.cos(noise[2]),
|
||||
torch.sin(noise[1]) * torch.sin(noise[2]),
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
else:
|
||||
raise ValueError("Currently only dimensions up to 4 are supported")
|
||||
del noise
|
||||
|
||||
for tidx, tile in enumerate(tileable[:dims]):
|
||||
if not tile:
|
||||
continue
|
||||
gradients[tuple(-1 if didx == tidx else None for didx in didxs)] = gradients[
|
||||
tuple(0 if didx == tidx else None for didx in didxs)
|
||||
]
|
||||
|
||||
shape_slices = tuple(slice(0, shape[i]) for i in didxs)
|
||||
|
||||
def tile_grads(slices):
|
||||
result = gradients[tuple(slice(*slices[i]) for i in didxs)]
|
||||
for i in didxs:
|
||||
result = result.repeat_interleave(d[i], i)
|
||||
return result
|
||||
|
||||
def dot(grad, shift):
|
||||
return (
|
||||
torch.stack(
|
||||
tuple(grid[(*shape_slices, i)] + shift[i] for i in didxs), dim=-1
|
||||
)
|
||||
* grad[shape_slices]
|
||||
).sum(dim=-1)
|
||||
|
||||
# It's just binary with the bits reversed and -1 for enabled columns.
|
||||
def get_shift(n, dims, *, on_value, off_value):
|
||||
return tuple(
|
||||
on_value if n & (1 << bitidx) else off_value for bitidx in range(dims)
|
||||
)
|
||||
|
||||
def blend_reduce(vals, t, depth=0):
|
||||
curr_t = t[..., depth]
|
||||
if len(vals) == 2:
|
||||
return blend(*vals, curr_t)
|
||||
return blend_reduce(
|
||||
tuple(blend(v1, v2, curr_t) for v1, v2 in itertools.batched(vals, 2)),
|
||||
t,
|
||||
depth + 1,
|
||||
)
|
||||
|
||||
ns = tuple(
|
||||
dot(
|
||||
tile_grads(get_shift(i, dims, off_value=(None, -1), on_value=(1, None))),
|
||||
get_shift(i, dims, off_value=0, on_value=-1),
|
||||
)
|
||||
for i in range(1 << dims)
|
||||
)
|
||||
return math.sqrt(2) * blend_reduce(ns, fade(grid[shape_slices]))
|
||||
|
||||
|
||||
def generate_fractal_noise(
|
||||
shape,
|
||||
res=DEFAULTS.res,
|
||||
octaves=DEFAULTS.octaves,
|
||||
persistence=DEFAULTS.persistence,
|
||||
lacunarity=DEFAULTS.lacunarity,
|
||||
initial_amplitude=DEFAULTS.initial_amplitude,
|
||||
initial_frequency=DEFAULTS.initial_frequency,
|
||||
tileable=DEFAULTS.tileable,
|
||||
fade=DEFAULTS.fade,
|
||||
blend=torch.lerp,
|
||||
generator=DEFAULTS.generator,
|
||||
device=DEFAULTS.device,
|
||||
):
|
||||
ndim = len(shape)
|
||||
|
||||
def get_wrap_dim(val, *dims):
|
||||
for dim in dims:
|
||||
nelem = len(val) if not isinstance(val, torch.Tensor) else val.shape[0]
|
||||
val = val[dim % nelem]
|
||||
return val
|
||||
|
||||
def get_unwrapped_octaves_dims(val):
|
||||
return torch.tensor(
|
||||
tuple(
|
||||
get_wrap_dim(val, didx, oidx)
|
||||
for oidx in range(octaves)
|
||||
for didx in range(ndim)
|
||||
),
|
||||
dtype=torch.float,
|
||||
device="cpu",
|
||||
).view(octaves, ndim)
|
||||
|
||||
res = get_unwrapped_octaves_dims(res)
|
||||
lacunarity = get_unwrapped_octaves_dims(lacunarity)
|
||||
initial_frequency = initial_frequency[-ndim:]
|
||||
persistence = persistence[:octaves]
|
||||
noise = torch.zeros(shape, dtype=torch.float32, device=device)
|
||||
frequency = torch.ones(ndim, dtype=torch.float, device="cpu")
|
||||
frequency[: len(initial_frequency)] = frequency.new(initial_frequency)
|
||||
amplitude = initial_amplitude
|
||||
|
||||
for octave in range(octaves):
|
||||
noise += amplitude * rand_perlin(
|
||||
shape,
|
||||
tuple(
|
||||
frequency[didx].item() * res[octave][didx].item()
|
||||
for didx in range(ndim)
|
||||
),
|
||||
tileable=tileable,
|
||||
fade=fade,
|
||||
blend=blend,
|
||||
generator=generator,
|
||||
device=device,
|
||||
)
|
||||
# print(
|
||||
# f"Octave {octave}: freq={frequency}, amp={amplitude}, lac={lacunarity[octave]}, pers={get_wrap_dim(persistence, octave)}"
|
||||
# )
|
||||
frequency *= lacunarity[octave]
|
||||
amplitude *= get_wrap_dim(persistence, octave)
|
||||
# print(f"Octave {octave}: POST: freq={frequency}, amp={amplitude}")
|
||||
return noise
|
||||
|
||||
|
||||
def create_noisy_latents_perlin(
|
||||
width,
|
||||
height,
|
||||
depth,
|
||||
*,
|
||||
batch_size=1,
|
||||
detail_level=DEFAULTS.detail_level,
|
||||
octaves=DEFAULTS.octaves,
|
||||
persistence=DEFAULTS.persistence,
|
||||
lacunarity=DEFAULTS.lacunarity,
|
||||
tileable=DEFAULTS.tileable,
|
||||
res=DEFAULTS.res,
|
||||
break_pattern=DEFAULTS.break_pattern,
|
||||
channels=4,
|
||||
blend=torch.lerp,
|
||||
pattern_break_blend=torch.lerp,
|
||||
depth_over_channels=DEFAULTS.depth_over_channels,
|
||||
pad=DEFAULTS.pad,
|
||||
initial_frequency=DEFAULTS.initial_frequency,
|
||||
initial_amplitude=DEFAULTS.initial_amplitude,
|
||||
generator=DEFAULTS.generator,
|
||||
device=DEFAULTS.device,
|
||||
):
|
||||
pad_depth, pad_height, pad_width = pad
|
||||
if depth < 1:
|
||||
depth_over_channels = False
|
||||
pad_depth = 0
|
||||
shape = (height, width)
|
||||
eff_shape = (
|
||||
height + pad_height * 2,
|
||||
width + pad_width * 2,
|
||||
)
|
||||
eff_channels = channels if not depth_over_channels else 1
|
||||
eff_depth = depth if not depth_over_channels else depth * channels
|
||||
if depth > 0:
|
||||
shape = (depth, height, width)
|
||||
eff_shape = (
|
||||
eff_depth + pad_depth * 2,
|
||||
height + pad_height * 2,
|
||||
width + pad_width * 2,
|
||||
)
|
||||
noise = torch.zeros(
|
||||
(batch_size, channels, *shape),
|
||||
dtype=torch.float32,
|
||||
device=device,
|
||||
)
|
||||
noise_dims = len(shape)
|
||||
for i in range(batch_size):
|
||||
for j in range(eff_channels):
|
||||
noise_values = generate_fractal_noise(
|
||||
eff_shape,
|
||||
res=res,
|
||||
octaves=octaves,
|
||||
persistence=persistence,
|
||||
lacunarity=lacunarity,
|
||||
tileable=tileable,
|
||||
blend=blend,
|
||||
initial_frequency=initial_frequency,
|
||||
initial_amplitude=initial_amplitude,
|
||||
generator=generator,
|
||||
device=device,
|
||||
)
|
||||
noise_values = normalize_to_scale(noise_values, -1.0, 1.0, dim=())
|
||||
if break_pattern != 0:
|
||||
result = torch.remainder(torch.abs(noise_values) * 1000000, 11) / 11
|
||||
result = (
|
||||
((1 + detail_level / 10) * torch.erfinv(2 * result - 1) * (2**0.5))
|
||||
.mul_(0.2)
|
||||
.clamp_(-1, 1)
|
||||
)
|
||||
result = pattern_break_blend(noise_values, result, break_pattern)
|
||||
else:
|
||||
result = noise_values
|
||||
if pad_width + pad_height + pad_depth > 0:
|
||||
result = (
|
||||
result[
|
||||
...,
|
||||
pad_depth : eff_depth + pad_depth,
|
||||
pad_height : height + pad_height,
|
||||
pad_width : width + pad_width,
|
||||
]
|
||||
if noise_dims == 3
|
||||
else result[
|
||||
...,
|
||||
pad_height : height + pad_height,
|
||||
pad_width : width + pad_width,
|
||||
]
|
||||
)
|
||||
if not depth_over_channels:
|
||||
noise[i, j, ...] = result
|
||||
continue
|
||||
noise[i, ...] = result.view(depth, channels, height, width).movedim(0, 1)
|
||||
return noise.movedim(-3, 0) if noise_dims == 3 else noise
|
||||
|
||||
|
||||
class PerlinItem(CustomNoiseItemBase):
|
||||
def __init__(
|
||||
self,
|
||||
factor,
|
||||
*,
|
||||
depth=20,
|
||||
detail_level=DEFAULTS.detail_level,
|
||||
octaves=DEFAULTS.octaves,
|
||||
persistence=DEFAULTS.persistence,
|
||||
lacunarity_depth=DEFAULTS.lacunarity[0],
|
||||
lacunarity_height=DEFAULTS.lacunarity[1],
|
||||
lacunarity_width=DEFAULTS.lacunarity[2],
|
||||
lacunarity=None,
|
||||
tileable_depth=DEFAULTS.tileable[0],
|
||||
tileable_height=DEFAULTS.tileable[1],
|
||||
tileable_width=DEFAULTS.tileable[2],
|
||||
tileable=None,
|
||||
res_depth=DEFAULTS.res[0],
|
||||
res_height=DEFAULTS.res[1],
|
||||
res_width=DEFAULTS.res[2],
|
||||
res=None,
|
||||
initial_frequency_depth=DEFAULTS.initial_frequency[0],
|
||||
initial_frequency_height=DEFAULTS.initial_frequency[1],
|
||||
initial_frequency_width=DEFAULTS.initial_frequency[2],
|
||||
initial_frequency=None,
|
||||
initial_amplitude=DEFAULTS.initial_amplitude,
|
||||
wrap_depth=DEFAULTS.wrap_depth,
|
||||
initial_depth=DEFAULTS.initial_depth,
|
||||
max_depth=DEFAULTS.max_depth,
|
||||
break_pattern=DEFAULTS.break_pattern,
|
||||
blend=DEFAULTS.blend,
|
||||
pattern_break_blend=DEFAULTS.pattern_break_blend,
|
||||
depth_over_channels=DEFAULTS.depth_over_channels,
|
||||
pad=None,
|
||||
pad_depth=DEFAULTS.pad[0],
|
||||
pad_height=DEFAULTS.pad[1],
|
||||
pad_width=DEFAULTS.pad[2],
|
||||
device=None,
|
||||
normalized=None,
|
||||
**kwargs,
|
||||
):
|
||||
if tileable is None:
|
||||
tileable = (tileable_depth, tileable_height, tileable_width)[
|
||||
int(depth == 0) :
|
||||
]
|
||||
if res is None:
|
||||
res = self.maybe_parse_dhw_triple(
|
||||
(res_depth, res_height, res_width), depth, int
|
||||
)
|
||||
if lacunarity is None:
|
||||
lacunarity = self.maybe_parse_dhw_triple(
|
||||
(
|
||||
lacunarity_depth,
|
||||
lacunarity_height,
|
||||
lacunarity_width,
|
||||
),
|
||||
depth,
|
||||
)
|
||||
if pad is None:
|
||||
pad = (pad_depth, pad_height, pad_width)
|
||||
if initial_frequency is None:
|
||||
initial_frequency = (
|
||||
initial_frequency_depth,
|
||||
initial_frequency_height,
|
||||
initial_frequency_width,
|
||||
)[int(depth == 0) :]
|
||||
persistence = self.maybe_parse_commasep_list(persistence)
|
||||
super().__init__(
|
||||
factor,
|
||||
depth=depth,
|
||||
detail_level=detail_level,
|
||||
octaves=octaves,
|
||||
persistence=persistence,
|
||||
lacunarity=lacunarity,
|
||||
tileable=tileable,
|
||||
res=res,
|
||||
initial_frequency=initial_frequency,
|
||||
initial_amplitude=initial_amplitude,
|
||||
initial_depth=initial_depth,
|
||||
wrap_depth=wrap_depth,
|
||||
max_depth=max_depth,
|
||||
break_pattern=break_pattern,
|
||||
blend=blend,
|
||||
pattern_break_blend=pattern_break_blend,
|
||||
depth_over_channels=depth_over_channels,
|
||||
pad=pad,
|
||||
device=device,
|
||||
normalized=normalized
|
||||
if not isinstance(normalized, str)
|
||||
else NormalizeNoiseNodeMixin.get_normalize(normalized),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def maybe_parse_dhw_triple(cls, val, depth, convert=float):
|
||||
return tuple(cls.maybe_parse_commasep_list(v) for v in val)[int(depth == 0) :]
|
||||
|
||||
@classmethod
|
||||
def maybe_parse_commasep_list(cls, val, convert=float):
|
||||
if not isinstance(val, str):
|
||||
return val
|
||||
return tuple(convert(v) for v in val.strip().split(",") if v.strip())
|
||||
|
||||
def make_noise_sampler(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
sigma_min: float | None,
|
||||
sigma_max: float | None,
|
||||
seed: int | None,
|
||||
cpu: bool = True,
|
||||
normalized=True,
|
||||
):
|
||||
normalized = self.get_normalize("normalized", normalized)
|
||||
cpu = cpu if self.device == "default" else self.device == "cpu"
|
||||
device = "cpu" if cpu else model_management.get_torch_device()
|
||||
noise_chunk = None
|
||||
noise_index = self.initial_depth
|
||||
max_idx = None
|
||||
if x.ndim < 4:
|
||||
raise ValueError("Can only handle latents with 4+ dimensions")
|
||||
orig_shape = x.shape
|
||||
b = x.shape[0]
|
||||
c = math.prod(x.shape[1:-2]) # Hack to deal with video models.
|
||||
h, w = x.shape[-2:]
|
||||
x_device, x_dtype = x.device, x.dtype
|
||||
del x
|
||||
blend = filtering.BLENDING_MODES[self.blend]
|
||||
pattern_break_blend = filtering.BLENDING_MODES[self.pattern_break_blend]
|
||||
|
||||
def noise_sampler(_s, _sn):
|
||||
nonlocal noise_chunk, noise_index, max_idx
|
||||
if noise_chunk is None:
|
||||
# print("-->", noise_index, self.depth)
|
||||
noise_chunk = create_noisy_latents_perlin(
|
||||
w,
|
||||
h,
|
||||
self.depth,
|
||||
batch_size=b,
|
||||
channels=c,
|
||||
detail_level=self.detail_level,
|
||||
octaves=self.octaves,
|
||||
persistence=self.persistence,
|
||||
lacunarity=self.lacunarity,
|
||||
initial_frequency=self.initial_frequency,
|
||||
initial_amplitude=self.initial_amplitude,
|
||||
break_pattern=self.break_pattern,
|
||||
res=self.res,
|
||||
tileable=self.tileable,
|
||||
blend=blend,
|
||||
pattern_break_blend=pattern_break_blend,
|
||||
depth_over_channels=self.depth_over_channels,
|
||||
pad=self.pad,
|
||||
device=device,
|
||||
).to(device=x_device, dtype=x_dtype)
|
||||
if self.depth < 1: # 2D mode
|
||||
noise = noise_chunk
|
||||
noise_chunk = None
|
||||
return scale_noise(noise, self.factor, normalized=normalized)
|
||||
if self.max_depth != 0 and self.max_depth != -1:
|
||||
noise_chunk = noise_chunk[: self.max_depth]
|
||||
chunk_shape = noise_chunk.shape
|
||||
max_idx = (
|
||||
chunk_shape[0] - 1
|
||||
if self.wrap_depth == 0
|
||||
else min(self.wrap_depth, chunk_shape[0] - 1)
|
||||
)
|
||||
if max_idx < 0:
|
||||
max_idx += chunk_shape[0]
|
||||
noise = noise_chunk[noise_index]
|
||||
noise_index += 1
|
||||
if noise_index > max_idx:
|
||||
noise_index = 0
|
||||
if not self.wrap_depth:
|
||||
noise_chunk = None
|
||||
result = scale_noise(noise, self.factor, normalized=normalized)
|
||||
return result.reshape(orig_shape) if result.shape != orig_shape else result
|
||||
|
||||
return noise_sampler
|
||||
@@ -0,0 +1,19 @@
|
||||
from . import types, expression, handler, util, validation
|
||||
|
||||
from .expression import Expression
|
||||
from .validation import Arg, ValidateArg
|
||||
from .handler import BASIC_HANDLERS, BaseHandler, HandlerContext
|
||||
|
||||
__all__ = (
|
||||
"Arg",
|
||||
"BaseHandler",
|
||||
"BASIC_HANDLERS",
|
||||
"expression",
|
||||
"Expression",
|
||||
"handler",
|
||||
"HandlerContext",
|
||||
"types",
|
||||
"util",
|
||||
"ValidateArg",
|
||||
"validation",
|
||||
)
|
||||
@@ -0,0 +1,272 @@
|
||||
import re
|
||||
import operator
|
||||
|
||||
from tqdm import tqdm
|
||||
|
||||
from .parser import Parser, ParserSpec, ParseError
|
||||
from .types import (
|
||||
Empty,
|
||||
ExpBase,
|
||||
ExpOp,
|
||||
ExpBinOp,
|
||||
ExpSym,
|
||||
ExpStatements,
|
||||
ExpFunAp,
|
||||
ExpTuple,
|
||||
ExpDict,
|
||||
ExpKV,
|
||||
)
|
||||
|
||||
COMMA_PRECEDENCE = 2
|
||||
|
||||
|
||||
class Expression:
|
||||
EXPR_RE = re.compile(
|
||||
r"""
|
||||
\s*
|
||||
(
|
||||
\d+ # Numeric literal
|
||||
(?: \. \d* )? # Floating point
|
||||
(?: e [+-] \d+)? # Scientific notation
|
||||
| (?: \*\* | // ) # Doubled operators
|
||||
| [<>]=? # Relative comparison
|
||||
| [!=]= # Equality
|
||||
| (?: \|\| | && ) # Logic
|
||||
| [-+*/|!(),] # Operators
|
||||
| :> # Key value binop
|
||||
| := # Assignment
|
||||
| ; # Sequencing
|
||||
| [?:] # Ternary
|
||||
| \[ | ] # Index
|
||||
| \.\.\. # Index ellipsis
|
||||
| '[-\w.]+ # Symbol
|
||||
| `?[a-z][\w.]*`? # Function/variable names
|
||||
)
|
||||
\s*
|
||||
""",
|
||||
re.I | re.S | re.X | re.A,
|
||||
)
|
||||
|
||||
def __init__(self, toks):
|
||||
if isinstance(toks, str):
|
||||
toks = tuple(self.tokenize(toks))
|
||||
self.expr = Parser(ExprParserSpec(), iter(toks)).go()
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Expr{self.expr!r}>"
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
return self.eval(*args, **kwargs)
|
||||
|
||||
def eval(self, handlers, *args, **kwargs):
|
||||
if self.expr != ExpOp("default"):
|
||||
tqdm.write(f"* OCS: EVAL: {self.expr}")
|
||||
if not isinstance(self.expr, ExpBase):
|
||||
return self.expr
|
||||
return self.expr.eval(handlers, *args, **kwargs)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.expr)
|
||||
|
||||
def pretty_string(self, depth=0):
|
||||
sval = (
|
||||
repr(self.expr)
|
||||
if not isinstance(self.expr, ExpBase)
|
||||
else self.expr.pretty_string(depth=depth + 1)
|
||||
)
|
||||
pad = " " * (depth + 1) * 2
|
||||
return f"<Expr:\n{pad}{sval}\n{pad[:-2]}>"
|
||||
|
||||
FIXUP = {"true": True, "false": False, "...": Ellipsis, "none": None}
|
||||
|
||||
@classmethod
|
||||
def fixup_token(cls, t):
|
||||
if t == "":
|
||||
return t
|
||||
if t[0] == "'":
|
||||
return ExpSym(t[1:])
|
||||
t = t.lower()
|
||||
val = cls.FIXUP.get(t, Empty)
|
||||
if val is not Empty:
|
||||
return val
|
||||
if t[0] == "`":
|
||||
return ExpBinOp(t.strip("`"))
|
||||
if (len(t) > 1 and t[0] == "-" and t[1].isdigit()) or t[0].isdigit():
|
||||
return float(t) if "." in t else int(t)
|
||||
return ExpOp(t)
|
||||
|
||||
@classmethod
|
||||
def tokenize(cls, s):
|
||||
s = "\n".join(
|
||||
line.rstrip("\r")
|
||||
for line in s.split("\n")
|
||||
if not line.lstrip().startswith("#")
|
||||
)
|
||||
yield from (cls.fixup_token(m.group(1)) for m in cls.EXPR_RE.finditer(s))
|
||||
|
||||
|
||||
CONST_OP_HANDLERS = {
|
||||
"+": operator.add,
|
||||
"-": operator.sub,
|
||||
"*": operator.mul,
|
||||
"/": operator.truediv,
|
||||
"//": operator.floordiv,
|
||||
"**": operator.pow,
|
||||
"%": operator.mod,
|
||||
"add": operator.add,
|
||||
"sub": operator.sub,
|
||||
"mul": operator.mul,
|
||||
"div": operator.truediv,
|
||||
"idiv": operator.floordiv,
|
||||
"pow": operator.pow,
|
||||
"mod": operator.mod,
|
||||
"neg": operator.neg,
|
||||
">": operator.gt,
|
||||
"<": operator.lt,
|
||||
">=": operator.ge,
|
||||
"<=": operator.le,
|
||||
"!=": operator.ne,
|
||||
"==": operator.eq,
|
||||
}
|
||||
|
||||
|
||||
def is_const_value(val):
|
||||
return val in (None, True, False) or isinstance(val, (int, float, ExpSym))
|
||||
|
||||
|
||||
def make_funap(op, args=(), kwargs=None):
|
||||
if kwargs is None:
|
||||
kwargs = ExpDict()
|
||||
argc = len(args)
|
||||
if argc > 2 or len(kwargs) or not all(is_const_value(v) for v in args):
|
||||
return ExpFunAp(op, args, kwargs)
|
||||
if argc == 1 and op in "-+":
|
||||
return -args[0] if op == "-" else args[0]
|
||||
h = CONST_OP_HANDLERS.get(op)
|
||||
if h is None:
|
||||
return ExpFunAp(op, args, kwargs)
|
||||
return h(*args)
|
||||
|
||||
|
||||
class ExprParserSpec(ParserSpec):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.populate()
|
||||
|
||||
@staticmethod
|
||||
def split_funap_args(toks):
|
||||
if not isinstance(toks, (list, tuple)):
|
||||
return ExpTuple((toks,)), ExpDict()
|
||||
return ExpTuple(t for t in toks if not isinstance(t, ExpKV)), ExpDict({
|
||||
str(t.k): t.v for t in toks if isinstance(t, ExpKV)
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
def null_constant(p, token, bp):
|
||||
return token
|
||||
|
||||
@staticmethod
|
||||
def null_paren(p, token, bp):
|
||||
result = p.parse_until(bp) if p.token != ")" else ExpTuple()
|
||||
if p.token == ",":
|
||||
p.advance()
|
||||
p.expect(")")
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def null_prefixop(p, token, bp):
|
||||
val = p.parse_until(bp)
|
||||
return make_funap(token, ExpTuple((val,)))
|
||||
|
||||
@classmethod
|
||||
def left_binop(cls, p, token, left, bp):
|
||||
return make_funap(token, *cls.split_funap_args((left, p.parse_until(bp))))
|
||||
|
||||
@staticmethod
|
||||
def left_kv(p, token, left, bp):
|
||||
if not isinstance(left, (ExpOp, ExpSym)):
|
||||
raise ParseError(f"{left!r} is not a valid key")
|
||||
return ExpKV(left, p.parse_until(bp))
|
||||
|
||||
@classmethod
|
||||
def left_funcall(cls, p, token, left, bp):
|
||||
if not isinstance(left, ExpOp):
|
||||
raise ParseError(f"{left!r} is not a valid function/variable name")
|
||||
args = []
|
||||
while p.lexer and p.token != ")":
|
||||
args.append(p.parse_until(COMMA_PRECEDENCE))
|
||||
if p.token == ",":
|
||||
p.advance()
|
||||
p.expect(")")
|
||||
return make_funap(left, *cls.split_funap_args(args))
|
||||
|
||||
@staticmethod
|
||||
def left_comma(p, token, left, bp):
|
||||
if p.token == ")":
|
||||
return left if isinstance(left, ExpTuple) else ExpTuple((left,))
|
||||
r = p.parse_until(bp)
|
||||
return ExpTuple((*left, r) if isinstance(left, ExpTuple) else (left, r))
|
||||
|
||||
@staticmethod
|
||||
def left_semicolon(p, token, left, bp):
|
||||
r = None if p.token in (None, ")", ";") else p.parse_until(0)
|
||||
return ExpStatements(
|
||||
ExpTuple((*left.statements, r))
|
||||
if isinstance(left, ExpStatements)
|
||||
else ExpTuple((left, r))
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def left_index(p, token, left, bp):
|
||||
idx = p.parse_until(0)
|
||||
p.expect("]")
|
||||
return make_funap("index", ExpTuple((idx, left)))
|
||||
|
||||
@staticmethod
|
||||
def left_assign(p, token, left, bp):
|
||||
if not isinstance(left, (ExpOp, ExpSym)):
|
||||
raise ParseError(f"bad LHS type for assignment operation {type(left)}")
|
||||
val = p.parse_until(bp)
|
||||
return make_funap("set_var", ExpTuple((ExpSym(left), val)))
|
||||
|
||||
@staticmethod
|
||||
def left_ternary(p, token, left, bp):
|
||||
true_branch = p.parse_until(0)
|
||||
p.expect(":")
|
||||
false_branch = p.parse_until(bp)
|
||||
return make_funap("if", ExpTuple((left, true_branch, false_branch)))
|
||||
|
||||
@staticmethod
|
||||
def get_type(token):
|
||||
if isinstance(token, (int, float)):
|
||||
return "number"
|
||||
if isinstance(token, ExpSym):
|
||||
return "sym"
|
||||
if isinstance(token, ExpBinOp):
|
||||
return "binop"
|
||||
if isinstance(token, ExpOp) and token[0].isalpha():
|
||||
return "op"
|
||||
return token
|
||||
|
||||
def populate(self):
|
||||
self.add_left(31, self.left_funcall, ("(",))
|
||||
self.add_left(31, self.left_index, ("[",))
|
||||
self.add_leftright(29, self.left_binop, ("**",))
|
||||
self.add_null(27, self.null_prefixop, ("+", "-", "!"))
|
||||
self.add_left(25, self.left_binop, ("*", "/"))
|
||||
self.add_left(23, self.left_binop, ("+", "-"))
|
||||
self.add_left(22, self.left_binop, ("binop",))
|
||||
self.add_left(19, self.left_binop, ("<", ">", "<=", ">="))
|
||||
self.add_left(19, self.left_binop, ("==", "!="))
|
||||
self.add_left(9, self.left_binop, ("&&",))
|
||||
self.add_left(7, self.left_binop, ("||",))
|
||||
self.add_left(6, self.left_kv, (":>",))
|
||||
self.add_leftright(5, self.left_ternary, ("?",))
|
||||
self.add_leftright(4, self.left_assign, (":=",))
|
||||
self.add_left(COMMA_PRECEDENCE, self.left_comma, (",",))
|
||||
self.add_left(1, self.left_semicolon, (";",))
|
||||
self.add_null(0, self.null_paren, ("(",))
|
||||
self.add_null(
|
||||
-1, self.null_constant, ("number", "op", "sym", Ellipsis, True, False, None)
|
||||
)
|
||||
self.add_null(-1, ParserSpec.null_error, (")", "]", ":"))
|
||||
@@ -0,0 +1,425 @@
|
||||
import operator
|
||||
|
||||
from .validation import ValidateArg, Arg, ValidateError
|
||||
from .types import Empty, ExpDict, ExpOp
|
||||
from .util import torch
|
||||
|
||||
|
||||
class HandlerError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class HandlerContext:
|
||||
def __init__(self, handlers=None, constants=None, variables=None):
|
||||
self.handlers = handlers if handlers is not None else {}
|
||||
self.constants = constants if constants is not None else {}
|
||||
self.variables = variables if variables is not None else {}
|
||||
|
||||
def get_handler(self, k, default=Empty):
|
||||
return self.handlers.get(k, default)
|
||||
|
||||
def get_var(self, k, default=Empty):
|
||||
result = self.constants.get(k, Empty)
|
||||
if result is Empty:
|
||||
result = self.variables.get(k, Empty)
|
||||
return default if result is Empty else result
|
||||
|
||||
def set_var(self, k, v):
|
||||
if k in self.constants:
|
||||
raise KeyError(
|
||||
f"Cannot set variable with key {k}: already exists as a constant"
|
||||
)
|
||||
self.variables[k] = v
|
||||
|
||||
def unset_var(self, k):
|
||||
if k in self.variables:
|
||||
del self.variables[k]
|
||||
return True
|
||||
return False
|
||||
|
||||
def __contains__(self, k):
|
||||
return any(
|
||||
k in coll for coll in (self.handlers, self.constants, self.variables)
|
||||
)
|
||||
|
||||
def clone(self, *, handlers=Empty, constants=Empty, variables=Empty):
|
||||
return self.__class__(
|
||||
self.handlers if handlers is Empty else handlers,
|
||||
self.constants if constants is Empty else constants,
|
||||
self.variables if variables is Empty else variables,
|
||||
)
|
||||
|
||||
|
||||
class BaseHandler:
|
||||
input_validators = ()
|
||||
|
||||
def __init__(self):
|
||||
self.input_validators_by_key = {
|
||||
v.name: (idx, v) for idx, v in enumerate(self.input_validators)
|
||||
}
|
||||
|
||||
def __call__(self, obj, *, getter):
|
||||
try:
|
||||
val = self.handle(obj, getter)
|
||||
return self.validate_output(obj, val)
|
||||
except Exception as exc:
|
||||
raise HandlerError(f'Error evaluating "{obj.name}":\n {exc!r}') from exc
|
||||
|
||||
def safe_get(self, key, obj, getter=None, *, default=Empty):
|
||||
str_key = isinstance(key, str)
|
||||
if str_key:
|
||||
argidx, validator = self.input_validators_by_key.get(key, (-1, None))
|
||||
else:
|
||||
argidx, validator = (
|
||||
key,
|
||||
(
|
||||
self.input_validators[key]
|
||||
if key < len(self.input_validators)
|
||||
else None
|
||||
),
|
||||
)
|
||||
default = (
|
||||
default
|
||||
if default is not Empty or validator is None
|
||||
else getattr(validator, "default", Empty)
|
||||
)
|
||||
if argidx >= 0 and argidx < len(obj.args):
|
||||
eff_key = argidx
|
||||
str_eff_key = False
|
||||
elif str_key:
|
||||
eff_key = key
|
||||
str_eff_key = True
|
||||
else:
|
||||
raise ValidateError(
|
||||
f"Error validating input argument {key} for {obj.name}, out of range for actual function arguments"
|
||||
)
|
||||
if getter is None:
|
||||
if str_eff_key:
|
||||
val = obj.kwargs.get(eff_key)
|
||||
else:
|
||||
val = default if eff_key > len(obj.args) else obj.args[eff_key]
|
||||
else:
|
||||
val = getter(eff_key, default=default)
|
||||
if validator is None:
|
||||
return val
|
||||
try:
|
||||
return validator(key, val)
|
||||
except ValidateError as exc:
|
||||
raise ValidateError(
|
||||
f"Error validating input argument {key} for {obj.name}, type {type(val)}: {exc!r}"
|
||||
)
|
||||
|
||||
def safe_get_multi(self, keys, obj, getter=None, *, default=Empty):
|
||||
return (self.safe_get(k, obj, getter, default=default) for k in keys)
|
||||
|
||||
def safe_get_all(self, obj, getter=None, *, default=Empty):
|
||||
return self.safe_get_multi(
|
||||
(v.name for v in self.input_validators), obj, getter, default=default
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
raise NotImplementedError
|
||||
|
||||
def validate_output(self, obj, value):
|
||||
return value
|
||||
|
||||
|
||||
class BinopLogicHandler(BaseHandler):
|
||||
input_validators = (
|
||||
Arg.present("lhs"),
|
||||
Arg.present("rhs"),
|
||||
)
|
||||
|
||||
def validate_output(self, obj, value):
|
||||
return operator.truth(value)
|
||||
|
||||
|
||||
class OrHandler(BinopLogicHandler):
|
||||
def handle(self, obj, getter):
|
||||
return operator.truth(
|
||||
self.safe_get("lhs", obj, getter=getter)
|
||||
) or operator.truth(self.safe_get("rhs", obj, getter=getter))
|
||||
|
||||
|
||||
class AndHandler(BinopLogicHandler):
|
||||
def handle(self, obj, getter):
|
||||
return operator.truth(
|
||||
self.safe_get("lhs", obj, getter=getter)
|
||||
) and operator.truth(self.safe_get("rhs", obj, getter=getter))
|
||||
|
||||
|
||||
class AllHandler(BinopLogicHandler):
|
||||
input_validators = ()
|
||||
|
||||
def handle(self, obj, getter):
|
||||
return all(
|
||||
operator.truth(self.safe_get(idx, obj, getter=getter))
|
||||
for idx in range(len(obj.args))
|
||||
) and all(
|
||||
operator.truth(self.safe_get(key, obj, getter=getter)) for key in obj.kwargs
|
||||
)
|
||||
|
||||
|
||||
class AnyHandler(BinopLogicHandler):
|
||||
def handle(self, obj, getter):
|
||||
return any(
|
||||
operator.truth(self.safe_get(idx, obj, getter=getter))
|
||||
for idx in range(len(obj.args))
|
||||
) or any(
|
||||
operator.truth(self.safe_get(key, obj, getter=getter)) for key in obj.kwargs
|
||||
)
|
||||
|
||||
|
||||
class EqHandler(BinopLogicHandler):
|
||||
def handle(self, obj, getter):
|
||||
a1, a2 = self.safe_get_all(obj, getter)
|
||||
if isinstance(a1, torch.Tensor) and isinstance(a2, torch.Tensor):
|
||||
return torch.equal(a1, a2)
|
||||
return a1 == a2
|
||||
|
||||
|
||||
class NeqHandler(EqHandler):
|
||||
def handle(self, *args, **kwargs):
|
||||
return not super().handle(*args, **kwargs)
|
||||
|
||||
|
||||
class NotHandler(BinopLogicHandler):
|
||||
input_validators = (Arg.present("value"),)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
return not operator.truth(self.safe_get("value", obj, getter=getter))
|
||||
|
||||
|
||||
class IfHandler(BaseHandler):
|
||||
input_validators = (
|
||||
Arg.present("condition"),
|
||||
Arg.present("then"),
|
||||
Arg.present("else"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
if operator.truth(self.safe_get("condition", obj, getter=getter)):
|
||||
return self.safe_get("then", obj, getter=getter)
|
||||
return self.safe_get("else", obj, getter=getter)
|
||||
|
||||
|
||||
class BetweenHandler(BaseHandler): # Inclusive
|
||||
input_validators = (
|
||||
Arg.numeric("value"),
|
||||
Arg.numeric("from", 0.0),
|
||||
Arg.numeric("to"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
value, low, high = self.safe_get_all(obj, getter)
|
||||
if low > high:
|
||||
low, high = high, low
|
||||
return low <= value <= high
|
||||
|
||||
|
||||
class SimpleMathHandler(BaseHandler):
|
||||
input_validators = (Arg.numeric("lhs"), Arg.numeric("rhs"))
|
||||
|
||||
def __init__(self, handler):
|
||||
super().__init__()
|
||||
self.handler = handler
|
||||
|
||||
def validate_output(self, obj, value):
|
||||
return ValidateArg.validate_numeric(-1, value)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
args = (
|
||||
self.safe_get(idx, obj, getter=getter)
|
||||
for idx in range(len(self.input_validators))
|
||||
)
|
||||
return self.handler(*args)
|
||||
|
||||
|
||||
class MinusHandler(SimpleMathHandler):
|
||||
input_validators = (Arg.numeric("lhs"), Arg.numeric("rhs", default=Empty))
|
||||
|
||||
__init__ = BaseHandler.__init__
|
||||
|
||||
def handle(self, obj, getter):
|
||||
lhs, rhs = self.safe_get_all(obj, getter)
|
||||
if rhs is Empty:
|
||||
return operator.neg(lhs)
|
||||
return operator.sub(lhs, rhs)
|
||||
|
||||
|
||||
class RelComparisonHandler(SimpleMathHandler):
|
||||
def validate_output(self, obj, value):
|
||||
return operator.truth(value)
|
||||
|
||||
|
||||
class UnarySimpleMathHandler(SimpleMathHandler):
|
||||
input_validators = (Arg.numeric("lhs"),)
|
||||
|
||||
|
||||
class IsSetHandler(BaseHandler):
|
||||
input_validators = (Arg.string("name"),)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
key = self.safe_get(0, obj, getter=getter)
|
||||
return key in getter.ctx
|
||||
|
||||
def validate_output(self, obj, value):
|
||||
return operator.truth(value)
|
||||
|
||||
|
||||
class GetHandler(BaseHandler):
|
||||
input_validators = (
|
||||
Arg.string("name"),
|
||||
Arg.present("fallback"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
key = self.safe_get("name", obj, getter=getter)
|
||||
result = getter.ctx.get_var(key)
|
||||
if result is Empty:
|
||||
return self.safe_get("fallback", obj, getter=getter)
|
||||
return ExpOp(key).eval(getter.ctx, *getter.args, **getter.kwargs)
|
||||
|
||||
|
||||
class S_Handler(BaseHandler):
|
||||
input_validators = (
|
||||
Arg.one_of(
|
||||
"start",
|
||||
(ValidateArg.validate_none, ValidateArg.validate_integer),
|
||||
default=None,
|
||||
),
|
||||
Arg.one_of(
|
||||
"end",
|
||||
(ValidateArg.validate_none, ValidateArg.validate_integer),
|
||||
default=None,
|
||||
),
|
||||
Arg.integer("step", 1),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
return slice(*self.safe_get_all(obj, getter=getter))
|
||||
|
||||
|
||||
class IndexHandler(BaseHandler):
|
||||
input_validators = (
|
||||
Arg.present("index"),
|
||||
Arg.one_of(
|
||||
"value", (ValidateArg.validate_sequence, ValidateArg.validate_tensor)
|
||||
),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
idx, value = self.safe_get_all(obj, getter=getter)
|
||||
return value[idx]
|
||||
|
||||
|
||||
class MinHandler(BaseHandler):
|
||||
input_validators = (Arg.numscalar_sequence("values"),)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
return min(*self.safe_get("values", obj, getter))
|
||||
|
||||
def validate_output(self, obj, value):
|
||||
return ValidateArg.validate_numeric(-1, value)
|
||||
|
||||
|
||||
class MaxHandler(MinHandler):
|
||||
def handle(self, obj, getter):
|
||||
return max(*self.safe_get("values", obj, getter))
|
||||
|
||||
|
||||
class UnsafeCallHandler(BaseHandler):
|
||||
input_validators = (Arg.present("__callable"),)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
if "__callable" in obj.kwargs:
|
||||
raise ValueError(
|
||||
"unsafe_call does not support passing the callable via keyword arg"
|
||||
)
|
||||
fun = self.safe_get("__callable", obj, getter)
|
||||
if not callable(fun):
|
||||
raise ValueError("Cannot call supplied value: not a callable")
|
||||
args = (self.safe_get(idx, obj, getter) for idx in range(1, len(obj.args)))
|
||||
kwargs = {k: self.safe_get(k, obj, getter) for k in obj.kwargs}
|
||||
return fun(*args, **kwargs)
|
||||
|
||||
|
||||
class DictHandler(BaseHandler):
|
||||
def handle(self, obj, getter):
|
||||
if len(obj.args):
|
||||
raise ValueError("Non-KV items passed to dict constructor")
|
||||
return ExpDict({k: self.safe_get(k, obj, getter) for k in obj.kwargs.keys()})
|
||||
|
||||
|
||||
class CommentHandler(BaseHandler):
|
||||
def handle(self, obj, getter):
|
||||
return None
|
||||
|
||||
|
||||
class SetVarHandler(BaseHandler):
|
||||
input_validators = (Arg.string("lhs"), Arg.present("rhs"))
|
||||
|
||||
def handle(self, obj, getter):
|
||||
key, val = self.safe_get_all(obj, getter)
|
||||
getter.ctx.set_var(key, val)
|
||||
return val
|
||||
|
||||
|
||||
LOGIC_HANDLERS = {
|
||||
"||": OrHandler(),
|
||||
"&&": AndHandler(),
|
||||
"==": EqHandler(),
|
||||
"!=": NeqHandler(),
|
||||
"not": NotHandler(),
|
||||
"if": IfHandler(),
|
||||
"all": AllHandler(),
|
||||
"any": AnyHandler(),
|
||||
}
|
||||
for k, alias in (
|
||||
("||", "or"),
|
||||
("&&", "and"),
|
||||
("==", "eq"),
|
||||
("!=", "neq"),
|
||||
):
|
||||
LOGIC_HANDLERS[alias] = LOGIC_HANDLERS[k]
|
||||
|
||||
|
||||
MATH_HANDLERS = {
|
||||
"+": SimpleMathHandler(operator.add),
|
||||
"-": MinusHandler(),
|
||||
"*": SimpleMathHandler(operator.mul),
|
||||
"/": SimpleMathHandler(operator.truediv),
|
||||
"//": SimpleMathHandler(operator.floordiv),
|
||||
"**": SimpleMathHandler(operator.pow),
|
||||
"mod": SimpleMathHandler(operator.mod),
|
||||
"neg": UnarySimpleMathHandler(operator.neg),
|
||||
"between": BetweenHandler(),
|
||||
"<": RelComparisonHandler(operator.lt),
|
||||
"<=": RelComparisonHandler(operator.le),
|
||||
">": RelComparisonHandler(operator.gt),
|
||||
">=": RelComparisonHandler(operator.ge),
|
||||
"min": MinHandler(),
|
||||
"max": MaxHandler(),
|
||||
}
|
||||
for k, alias in (
|
||||
("+", "add"),
|
||||
("-", "sub"),
|
||||
("*", "mul"),
|
||||
("/", "div"),
|
||||
("//", "idiv"),
|
||||
("**", "pow"),
|
||||
):
|
||||
MATH_HANDLERS[alias] = MATH_HANDLERS[k]
|
||||
|
||||
MISC_HANDLERS = {
|
||||
"is_set": IsSetHandler(),
|
||||
"get": GetHandler(),
|
||||
"index": IndexHandler(),
|
||||
"s_": S_Handler(),
|
||||
"unsafe_call": UnsafeCallHandler(),
|
||||
"dict": DictHandler(),
|
||||
"comment": CommentHandler(),
|
||||
"set_var": SetVarHandler(),
|
||||
}
|
||||
|
||||
BASIC_HANDLERS = LOGIC_HANDLERS | MATH_HANDLERS | MISC_HANDLERS
|
||||
@@ -0,0 +1,112 @@
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
# Pratt parsing referenced from https://github.com/andychu/pratt-parsing-demo
|
||||
class ParserSpec:
|
||||
@staticmethod
|
||||
def null_error(p, token, bp):
|
||||
raise ParseError(f"{token!r} cannot be used in prefix position")
|
||||
|
||||
@staticmethod
|
||||
def left_error(p, token, bp):
|
||||
raise ParseError(f"{token!r} cannot be used in infix position")
|
||||
|
||||
class LeftInfo:
|
||||
def __init__(self, led=None, lbp=0, rbp=0):
|
||||
self.led, self.lbp, self.rbp = led or ParserSpec.left_error, lbp, rbp
|
||||
|
||||
class NullInfo:
|
||||
def __init__(self, nud=None, bp=0):
|
||||
self.nud, self.bp = nud or ParserSpec.null_error, bp
|
||||
|
||||
def __init__(self):
|
||||
self.null_lookup = {}
|
||||
self.left_lookup = {}
|
||||
|
||||
def add_null(self, bp, nud, tokens):
|
||||
for token in tokens:
|
||||
self.null_lookup[token] = self.NullInfo(nud, bp)
|
||||
if token not in self.left_lookup:
|
||||
self.left_lookup[token] = self.LeftInfo()
|
||||
|
||||
def add_led(self, lbp, rbp, led, tokens):
|
||||
for token in tokens:
|
||||
self.left_lookup[token] = self.LeftInfo(led, lbp, rbp)
|
||||
if token not in self.null_lookup:
|
||||
self.null_lookup[token] = self.NullInfo(self.null_error)
|
||||
|
||||
def add_left(self, bp, led, tokens):
|
||||
return self.add_led(bp, bp, led, tokens)
|
||||
|
||||
def add_leftright(self, bp, led, tokens):
|
||||
return self.add_led(bp, bp - 1, led, tokens)
|
||||
|
||||
def lookup(self, token, is_left):
|
||||
result = (self.left_lookup if is_left else self.null_lookup).get(token)
|
||||
if result is None:
|
||||
raise ParseError(f"Unexpected token {token!r}")
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def get_type(token):
|
||||
if isinstance(token, (int, float)):
|
||||
return "number"
|
||||
if isinstance(token, str) and token.isidentifier():
|
||||
return "op"
|
||||
return token
|
||||
|
||||
|
||||
class Parser:
|
||||
def __init__(self, spec, lexer):
|
||||
self.spec = spec
|
||||
self.lexer = lexer
|
||||
self.token = None
|
||||
self.token_type = None
|
||||
self.pos = -1
|
||||
|
||||
def advance(self):
|
||||
if self.lexer is None:
|
||||
self.token_type = self.token = None
|
||||
return None
|
||||
try:
|
||||
self.token = next(self.lexer)
|
||||
self.token_type = self.spec.get_type(self.token)
|
||||
self.pos += 1
|
||||
except StopIteration:
|
||||
self.token = self.token_type = self.lexer = None
|
||||
return self.token
|
||||
|
||||
def expect(self, val):
|
||||
if val is not None and (self.lexer is None or self.token != val):
|
||||
raise ParseError(f"expected {val!r}, got {self.token!r}")
|
||||
return self.advance()
|
||||
|
||||
def parse_until(self, rbp):
|
||||
if self.lexer is None:
|
||||
raise ParseError("unexpected end of input")
|
||||
spec = self.spec
|
||||
token, token_type = self.token, self.token_type
|
||||
self.advance()
|
||||
ni = spec.lookup(token_type, False)
|
||||
node = ni.nud(self, token, ni.bp)
|
||||
while self.lexer:
|
||||
token, token_type = self.token, self.token_type
|
||||
li = spec.lookup(token_type, True)
|
||||
if rbp >= li.lbp:
|
||||
break
|
||||
self.advance()
|
||||
node = li.led(self, token, node, li.rbp)
|
||||
return node
|
||||
|
||||
def go(self):
|
||||
self.advance()
|
||||
try:
|
||||
result = self.parse_until(0)
|
||||
except ParseError as exc:
|
||||
raise ParseError(
|
||||
f"pos {self.pos} at token {self.token!r}: parse error: {exc}"
|
||||
) from None
|
||||
if self.lexer:
|
||||
raise ParseError(f"pos {self.pos}: unexpected end of input")
|
||||
return result
|
||||
@@ -0,0 +1,213 @@
|
||||
class Empty:
|
||||
def __bool__(self):
|
||||
return False
|
||||
|
||||
|
||||
class ExpBase:
|
||||
def __bool__(self):
|
||||
return True
|
||||
|
||||
def pretty_string(self, *, depth=0):
|
||||
return repr(self)
|
||||
|
||||
def eval(self, *args, **kwargs):
|
||||
return self
|
||||
|
||||
def clone(self, *, mapper=None):
|
||||
return self if not mapper else mapper(self)
|
||||
|
||||
|
||||
class ExpOp(str, ExpBase):
|
||||
__slots__ = ()
|
||||
|
||||
def eval(self, handlers, *args, **kwargs):
|
||||
value = handlers.get_var(self)
|
||||
if value is Empty:
|
||||
raise KeyError(f"No handler for op/var {self}")
|
||||
return value
|
||||
|
||||
|
||||
class ExpBinOp(ExpOp):
|
||||
__slots__ = ()
|
||||
|
||||
|
||||
class ExpSym(str, ExpBase):
|
||||
__slots__ = ()
|
||||
|
||||
def __repr__(self):
|
||||
return f"'{self}"
|
||||
|
||||
|
||||
class ExpTuple(tuple, ExpBase):
|
||||
__slots__ = ()
|
||||
|
||||
def clone(self):
|
||||
return self.__class__(v.clone() if isinstance(ExpBase) else v for v in self)
|
||||
|
||||
def get_eval(self, k, handlers, *args, default=None, **kwargs):
|
||||
val = super().__getitem__(k)
|
||||
if isinstance(val, ExpBase):
|
||||
return val.eval(handlers, *args, **kwargs)
|
||||
return val
|
||||
|
||||
def pretty_string(self, depth=0):
|
||||
vals = (
|
||||
repr(v) if not isinstance(v, ExpBase) else v.pretty_string(depth=depth + 1)
|
||||
for v in self
|
||||
)
|
||||
pad = " " * (depth + 1) * 2
|
||||
nlpad = f",\n{pad}"
|
||||
return f"(\n{pad}{nlpad.join(vals)}\n{pad[:-2]})"
|
||||
|
||||
def eval(self, handlers, *args, **kwargs):
|
||||
return tuple(
|
||||
v.eval(handlers, *args, **kwargs) if isinstance(v, ExpBase) else v
|
||||
for v in self
|
||||
)
|
||||
|
||||
|
||||
class ExpKV(ExpBase):
|
||||
__slots__ = ("k", "v")
|
||||
|
||||
def __init__(self, k, v):
|
||||
self.k = k
|
||||
self.v = v
|
||||
|
||||
|
||||
class ExpDict(dict, ExpBase):
|
||||
__slots__ = ()
|
||||
|
||||
def clone(self):
|
||||
return self.__class__(v.clone() if isinstance(ExpBase) else v for v in self)
|
||||
|
||||
def pop(self, *args, **kwargs):
|
||||
raise NotImplementedError
|
||||
|
||||
def get_eval(self, k, handlers, *args, default=Empty, **kwargs):
|
||||
val = super().get(k, default)
|
||||
if isinstance(val, ExpBase):
|
||||
return val.eval(handlers, *args, **kwargs)
|
||||
return val
|
||||
|
||||
def pretty_string(self, depth=0):
|
||||
vals = (
|
||||
f"{k}: {v!r}"
|
||||
if not isinstance(v, ExpBase)
|
||||
else f"{k}: {v.pretty_string(depth=depth + 1)}"
|
||||
for k, v in self.items()
|
||||
)
|
||||
pad = " " * (depth + 1) * 2
|
||||
nlpad = f",\n{pad}"
|
||||
return f"{{\n{pad}{nlpad.join(vals)}\n{pad[:-2]}}}"
|
||||
|
||||
def eval(self, handlers, *args, **kwargs):
|
||||
return {
|
||||
k: v.eval(handlers, *args, **kwargs) if isinstance(v, ExpBase) else v
|
||||
for k, v in self.items()
|
||||
}
|
||||
|
||||
popitem = pop
|
||||
update = pop
|
||||
clear = pop
|
||||
__delitem__ = pop
|
||||
__setitem__ = pop
|
||||
__ior__ = pop
|
||||
|
||||
|
||||
class ExpStatements(ExpBase):
|
||||
def __init__(self, statements):
|
||||
if not isinstance(statements, ExpTuple) or not len(statements):
|
||||
raise ValueError("Must have at least one statement")
|
||||
self.statements = statements
|
||||
|
||||
def eval(self, handlers, *args, **kwargs):
|
||||
result = Empty
|
||||
for stmt in self.statements:
|
||||
result = (
|
||||
stmt.eval(handlers, *args, **kwargs)
|
||||
if isinstance(stmt, ExpBase)
|
||||
else stmt
|
||||
)
|
||||
return result
|
||||
|
||||
def __repr__(self):
|
||||
return f"@{self.statements}"
|
||||
|
||||
|
||||
class ExprGetter:
|
||||
def __init__(self, obj, ctx, *args, **kwargs):
|
||||
self.obj = obj
|
||||
self.ctx = ctx
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
|
||||
def __call__(self, k, *, default=Empty):
|
||||
obj = self.obj
|
||||
result = (
|
||||
obj.kwargs.get_eval(k, self.ctx, *self.args, default=default, **self.kwargs)
|
||||
if isinstance(k, str)
|
||||
else obj.args.get_eval(k, self.ctx, *self.args, **self.kwargs)
|
||||
)
|
||||
if result is Empty:
|
||||
raise KeyError(f"Unknown key {k!r}")
|
||||
return result
|
||||
|
||||
|
||||
class ExpFunAp(ExpBase):
|
||||
__slots__ = ("name", "args", "kwargs")
|
||||
|
||||
def __init__(self, name, args=None, kwargs=None):
|
||||
self.name = name
|
||||
self.args = args if args is not None else ExpTuple()
|
||||
self.kwargs = kwargs if kwargs is not None else ExpDict()
|
||||
|
||||
def eval(self, handlers, *args, **kwargs):
|
||||
handler = handlers.get_handler(self.name)
|
||||
if handler is Empty:
|
||||
raise KeyError(f"No handler for op: {self.name!r}")
|
||||
return handler(
|
||||
self, getter=ExprGetter(self, handlers, *args, **kwargs), **kwargs
|
||||
)
|
||||
|
||||
def clone(self):
|
||||
return self.__class__(self.name, self.args.clone(), self.kwargs.clone())
|
||||
|
||||
def pretty_string(self, depth=0):
|
||||
pad = " " * (depth + 1) * 2
|
||||
kwargs_str = f", {self.kwargs.pretty_string(depth + 1)}" if self.kwargs else ""
|
||||
return f"<FUNAP {self.name}\n{pad}{self.args.pretty_string(depth + 1)}{kwargs_str}\n{pad[:-2]}>"
|
||||
|
||||
def __repr__(self):
|
||||
kwargs_str = f", {self.kwargs}" if self.kwargs else ""
|
||||
return f"<FUNAP:{self.name}{self.args}{kwargs_str}>"
|
||||
|
||||
|
||||
class ExpBoundFunAp(ExpFunAp):
|
||||
__slots__ = ("fun",)
|
||||
|
||||
def __init__(self, name, fun, args, kwargs):
|
||||
super().__init__(name, args, kwargs)
|
||||
self.fun = fun
|
||||
|
||||
def eval(self, handlers, *args, **kwargs):
|
||||
def get_evaled(k, default=None):
|
||||
return (
|
||||
self.kwargs.get_eval(k, handlers, *args, default=default, **kwargs)
|
||||
if isinstance(k, str)
|
||||
else self.args.get_eval(k, handlers, *args, **kwargs)
|
||||
)
|
||||
|
||||
return self.fun(self.name, self.args, *args, getter=get_evaled, **kwargs)
|
||||
|
||||
|
||||
__all__ = (
|
||||
"ExpBase",
|
||||
"ExpOp",
|
||||
"ExpBinOp",
|
||||
"ExpSym",
|
||||
"ExpTuple",
|
||||
"ExpKV",
|
||||
"ExpDict",
|
||||
"ExpFunAp",
|
||||
"ExpBoundFunAp",
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
import itertools
|
||||
|
||||
try:
|
||||
import torch
|
||||
except ImportError:
|
||||
# To facilitate testing.
|
||||
class torch:
|
||||
class Tensor:
|
||||
pass
|
||||
|
||||
|
||||
class WrapGenerator:
|
||||
def __init__(self, g):
|
||||
self.g = g
|
||||
self._value = None
|
||||
self.ready = False
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
if not self.ready:
|
||||
raise ValueError("Value not ready")
|
||||
return self._value
|
||||
|
||||
def __iter__(self):
|
||||
self._value = yield from self.g
|
||||
self.ready = True
|
||||
return self._value
|
||||
|
||||
|
||||
def split_iterable(seq, pred):
|
||||
it = iter(seq)
|
||||
while True:
|
||||
toks = tuple(itertools.takewhile(pred, it))
|
||||
if toks == ():
|
||||
break
|
||||
yield toks
|
||||
@@ -0,0 +1,253 @@
|
||||
import contextlib
|
||||
import functools
|
||||
|
||||
from ..latent import ImageBatch
|
||||
from .util import torch
|
||||
from .types import Empty
|
||||
|
||||
|
||||
class Arg:
|
||||
__slots__ = ("name", "default", "validator")
|
||||
|
||||
def __init__(self, name, default=Empty, *, validator=None):
|
||||
self.name = name
|
||||
self.default = default
|
||||
self.validator = validator
|
||||
|
||||
def __call__(self, _key, value, *args, **kwargs):
|
||||
return self.validate(value, *args, **kwargs)
|
||||
|
||||
def validate(self, value):
|
||||
if value is Empty:
|
||||
if self.default is Empty:
|
||||
raise ValueError(f"Missing value for argument {self.name}")
|
||||
return self.default
|
||||
try:
|
||||
return self.validator(self.name, value) if self.validator else value
|
||||
except ValidateError as exc:
|
||||
raise ValidateError(f"Failed to validate argument {self.name}: {exc}")
|
||||
|
||||
@classmethod
|
||||
def tensor(cls, name):
|
||||
return cls(name, validator=ValidateArg.validate_tensor)
|
||||
|
||||
@classmethod
|
||||
def image(cls, name):
|
||||
return cls(name, validator=ValidateArg.validate_image)
|
||||
|
||||
@classmethod
|
||||
def numeric(cls, name, default=Empty):
|
||||
return cls(name, default=default, validator=ValidateArg.validate_numeric)
|
||||
|
||||
@classmethod
|
||||
def numeric_scalar(cls, name, default=Empty):
|
||||
return cls(name, default=default, validator=ValidateArg.validate_numeric_scalar)
|
||||
|
||||
@classmethod
|
||||
def integer(cls, name, default=Empty):
|
||||
return cls(name, default=default, validator=ValidateArg.validate_integer)
|
||||
|
||||
@classmethod
|
||||
def numscalar_sequence(cls, name, default=Empty):
|
||||
return cls(
|
||||
name, default=default, validator=ValidateArg.validate_numscalar_sequence
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def tensor_slice(cls, name, default=Empty):
|
||||
return cls(name, default=default, validator=ValidateArg.validate_tensor_slice)
|
||||
|
||||
@classmethod
|
||||
def sequence(cls, name, default=Empty, *, item_validator=None):
|
||||
return cls(
|
||||
name,
|
||||
default=default,
|
||||
validator=functools.partial(
|
||||
ValidateArg.validate_sequence, item_validator=item_validator
|
||||
),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def nested_sequence(cls, name, default=Empty, *, item_validator=None):
|
||||
return cls(
|
||||
name,
|
||||
default=default,
|
||||
validator=functools.partial(
|
||||
ValidateArg.validate_nested_sequence, item_validator=item_validator
|
||||
),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def string(cls, name, default=Empty):
|
||||
return cls(name, default=default, validator=ValidateArg.validate_string)
|
||||
|
||||
@classmethod
|
||||
def boolean(cls, name, default=Empty):
|
||||
return cls(name, default=default, validator=ValidateArg.validate_boolean)
|
||||
|
||||
@classmethod
|
||||
def present(cls, name):
|
||||
return cls(name, validator=ValidateArg.validate_passthrough)
|
||||
|
||||
@classmethod
|
||||
def one_of(cls, name, validators, *, default=Empty):
|
||||
def validate(idx, val):
|
||||
for validator in validators:
|
||||
try:
|
||||
return validator(idx, val)
|
||||
except ValidateError:
|
||||
continue
|
||||
raise ValidateError(
|
||||
f"Failed to validate argument at {idx} of type {type(val)}"
|
||||
)
|
||||
|
||||
return cls(name, default=default, validator=validate)
|
||||
|
||||
|
||||
class ValidateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class ValidateArg:
|
||||
__slots__ = ("valfuns", "groupfun", "kwargs", "kwargslist")
|
||||
|
||||
def __init__(self, name, *args, kwargslist=(), group=all, **kwargs):
|
||||
if not isinstance(name, (list, tuple)):
|
||||
name = (name,)
|
||||
args = ((args,),)
|
||||
kwargslist = kwargs
|
||||
kwargs = {}
|
||||
self.valfuns = (getattr(self, f"validate_{n}", None) for n in name)
|
||||
if not all(self.valfuns):
|
||||
raise ValueError("Unknown validator")
|
||||
self.groupfun = group
|
||||
self.kwargs = kwargs
|
||||
self.kwargslist = kwargslist if kwargslist is not None else {}
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
kalen = len(self.kwargslist)
|
||||
return self.groupfun(
|
||||
vf(
|
||||
*args,
|
||||
**(self.kwargslist if idx < kalen else {}),
|
||||
**self.kwargs,
|
||||
)
|
||||
for idx, vf in enumerate(self.valfuns)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def validate_numeric(idx, val):
|
||||
if not isinstance(val, (int, float, torch.Tensor)):
|
||||
raise ValidateError(
|
||||
f"Expected numeric or tensor argument at {idx}, got {type(val)}"
|
||||
)
|
||||
return val
|
||||
|
||||
@classmethod
|
||||
def validate_numeric_scalar(cls, idx, val):
|
||||
if not isinstance(val, (int, float)):
|
||||
raise ValidateError(f"Expected numeric argument at {idx}, got {type(val)}")
|
||||
return val
|
||||
|
||||
@classmethod
|
||||
def validate_tensor_slice_item(cls, idx, val):
|
||||
with contextlib.suppress(ValidateError):
|
||||
ok = (
|
||||
val in {Ellipsis, None}
|
||||
or isinstance(val, (int, slice))
|
||||
or cls.validate_sequence(
|
||||
idx, val, item_validator=ValidateArg.validate_integer
|
||||
)
|
||||
)
|
||||
if ok:
|
||||
return val
|
||||
raise ValidateError(
|
||||
f"Expected none, int, slice, tuple of int or ellipsis argument at {idx}, got {type(val)}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate_integer(cls, idx, val):
|
||||
if not isinstance(val, int):
|
||||
raise ValidateError(f"Expected integer argument at {idx}, got {type(val)}")
|
||||
return val
|
||||
|
||||
@staticmethod
|
||||
def validate_tensor(idx, val):
|
||||
if not isinstance(val, torch.Tensor):
|
||||
raise ValidateError(f"Expected tensor argument at {idx}, got {type(val)}")
|
||||
return val
|
||||
|
||||
@staticmethod
|
||||
def validate_image(idx, val):
|
||||
if not isinstance(val, ImageBatch):
|
||||
raise ValidateError(
|
||||
f"Expected PIL Image argument at {idx}, got {type(val)}"
|
||||
)
|
||||
return val
|
||||
|
||||
@staticmethod
|
||||
def validate_sequence(idx, val, *, item_validator=None):
|
||||
if not isinstance(val, (list, tuple)):
|
||||
raise ValidateError(f"Expected sequence argument at {idx}, got {type(val)}")
|
||||
if item_validator is None:
|
||||
return val
|
||||
try:
|
||||
return tuple(item_validator(iidx, v) for iidx, v in enumerate(val))
|
||||
except ValidateError as exc:
|
||||
raise ValidateError(
|
||||
f"Item validation failed for sequence argument at {idx}: {exc}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate_nested_sequence(cls, idx, val, *, item_validator=None, depth=0):
|
||||
if not isinstance(val, (list, tuple)):
|
||||
raise ValidateError(
|
||||
f"Expected nested sequence argument at {idx}, depth {depth} but got {type(val)}"
|
||||
)
|
||||
try:
|
||||
return tuple(
|
||||
cls.validate_nested_sequence(
|
||||
idx, v, item_validator=item_validator, depth=depth + 1
|
||||
)
|
||||
if isinstance(v, (list, tuple))
|
||||
else (item_validator(iidx, v) if item_validator is not None else v)
|
||||
for iidx, v in enumerate(val)
|
||||
)
|
||||
except ValidateError as exc:
|
||||
raise ValidateError(
|
||||
f"Item validation failed for nested sequence argument at {idx}, depth {depth}: {exc}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate_numscalar_sequence(cls, idx, val):
|
||||
return cls.validate_sequence(
|
||||
idx, val, item_validator=cls.validate_numeric_scalar
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate_tensor_slice(cls, idx, val):
|
||||
return cls.validate_sequence(
|
||||
idx, val, item_validator=cls.validate_tensor_slice_item
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate_string(cls, idx, val):
|
||||
if not isinstance(val, str):
|
||||
raise ValidateError(f"Expected string argument at {idx}, got {type(val)}")
|
||||
return val
|
||||
|
||||
@classmethod
|
||||
def validate_boolean(cls, idx, val):
|
||||
if val is not True and val is not False:
|
||||
raise ValidateError(f"Expected boolean argument at {idx}, got {type(val)}")
|
||||
return val
|
||||
|
||||
@classmethod
|
||||
def validate_none(cls, idx, val):
|
||||
if val is not None:
|
||||
raise ValidateError(f"Expected none argument at {idx}, got {type(val)}")
|
||||
return val
|
||||
|
||||
@classmethod
|
||||
def validate_passthrough(cls, idx, val):
|
||||
return val
|
||||
@@ -0,0 +1,667 @@
|
||||
import os
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
import PIL.Image as PILImage
|
||||
from functools import partial
|
||||
|
||||
from . import expression as expr
|
||||
from . import latent
|
||||
from . import unsafe_expression_whitelists
|
||||
|
||||
from .external import MODULES as EXT
|
||||
from .utils import scale_noise, resolve_value, quantile_normalize
|
||||
from .latent import OCSTAESD, ImageBatch, normalize_to_scale
|
||||
|
||||
|
||||
ALLOW_UNSAFE = os.environ.get("COMFYUI_OCS_ALLOW_UNSAFE_EXPRESSIONS") is not None
|
||||
ALLOW_ALL_UNSAFE = os.environ.get("COMFYUI_OCS_ALLOW_ALL_UNSAFE") is not None
|
||||
|
||||
EXT_BLEH = EXT_SONAR = None
|
||||
|
||||
BLENDING_MODES = {
|
||||
"lerp": torch.lerp,
|
||||
}
|
||||
|
||||
HANDLERS = {}
|
||||
|
||||
|
||||
def init_integrations(integrations):
|
||||
global EXT_BLEH, EXT_SONAR, BLENDING_MODES, HANDLERS
|
||||
EXT_BLEH = integrations.bleh
|
||||
EXT_SONAR = integrations.sonar
|
||||
if EXT_BLEH is not None:
|
||||
BLENDING_MODES = EXT_BLEH.latent_utils.BLENDING_MODES
|
||||
HANDLERS["t_bleh_enhance"] = BlehEnhanceHandler()
|
||||
if EXT_SONAR is not None:
|
||||
HANDLERS["t_sonar_power_filter"] = SonarPowerFilterHandler()
|
||||
if integrations.nnlatentupscale is not None:
|
||||
HANDLERS["t_scale_nnlatentupscale"] = ScaleNNLatentUpscaleHandler()
|
||||
|
||||
|
||||
EXT.register_init_handler(init_integrations)
|
||||
|
||||
|
||||
class NormHandler(expr.BaseHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numeric("factor", 1.0),
|
||||
expr.Arg.numscalar_sequence("dim", (-3, -2, -1)),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, factor, dim = self.safe_get_all(obj, getter)
|
||||
return scale_noise(tensor, factor, normalize_dims=dim)
|
||||
|
||||
validate_output = expr.Arg.tensor("output")
|
||||
|
||||
|
||||
class QuantileNormHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numeric("quantile", 0.75),
|
||||
expr.Arg.integer("dim", 1),
|
||||
expr.Arg.boolean("flatten", True),
|
||||
expr.Arg.numeric("norm_factor", 1.0),
|
||||
expr.Arg.numeric("norm_power", 0.5),
|
||||
expr.Arg.string("mode", "clamp"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, quantile, dim, flatten, norm_factor, norm_power, mode = (
|
||||
self.safe_get_all(obj, getter)
|
||||
)
|
||||
return quantile_normalize(
|
||||
tensor,
|
||||
quantile=quantile,
|
||||
dim=dim,
|
||||
flatten=flatten,
|
||||
nq_fac=norm_factor,
|
||||
pow_fac=norm_power,
|
||||
strategy=mode,
|
||||
)
|
||||
|
||||
|
||||
class NormToScaleHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numeric("target_min", 0.0),
|
||||
expr.Arg.numeric("target_max", 1.0),
|
||||
expr.Arg.numscalar_sequence("dim", (-3, -2, -1)),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, tmin, tmax, dim = self.safe_get_all(obj, getter)
|
||||
return normalize_to_scale(tensor, tmin, tmax, dim=dim)
|
||||
|
||||
|
||||
class ClampHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numeric("min", 0.0),
|
||||
expr.Arg.numeric("max", 1.0),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, tmin, tmax = self.safe_get_all(obj, getter)
|
||||
return torch.clamp(tensor, min=tmin, max=tmax)
|
||||
|
||||
|
||||
class StackHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.sequence("tensors", item_validator=expr.ValidateArg.validate_tensor),
|
||||
expr.Arg.integer("dim", 1),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensors, dim = self.safe_get_all(obj, getter)
|
||||
return torch.stack(tensors, dim)
|
||||
|
||||
|
||||
class CatHandler(StackHandler):
|
||||
def handle(self, obj, getter):
|
||||
tensors, dim = self.safe_get_all(obj, getter)
|
||||
return torch.cat(tensors, dim)
|
||||
|
||||
|
||||
class ReshapeHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numscalar_sequence("shape"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, shape = self.safe_get_all(obj, getter)
|
||||
return torch.reshape(tensor.clone(), shape)
|
||||
|
||||
|
||||
class IndexedCopyHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor_dest"),
|
||||
expr.Arg.tensor("tensor_src"),
|
||||
expr.Arg.tensor_slice("slice"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor1, tensor2, tensor_slice = self.safe_get_all(obj, getter)
|
||||
result = tensor1.clone()
|
||||
result[tensor_slice] = tensor2[tensor_slice]
|
||||
return result
|
||||
|
||||
|
||||
class NewLikeHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.nested_sequence(
|
||||
"values",
|
||||
default=(),
|
||||
item_validator=expr.ValidateArg.validate_numeric_scalar,
|
||||
),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, values = self.safe_get_all(obj, getter)
|
||||
return torch.tensor(values, dtype=tensor.dtype, device=tensor.device)
|
||||
|
||||
|
||||
class MeanHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numscalar_sequence("dim", (-3, -2, -1)),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, dim = self.safe_get_all(obj, getter)
|
||||
return tensor.mean(keepdim=True, dim=dim)
|
||||
|
||||
|
||||
class StdHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numscalar_sequence("dim", (-3, -2, -1)),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, dim = self.safe_get_all(obj, getter)
|
||||
return tensor.std(keepdim=True, dim=dim)
|
||||
|
||||
|
||||
class RollHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numeric_scalar("amount", 0.5),
|
||||
expr.Arg.one_of(
|
||||
"dim",
|
||||
(
|
||||
expr.ValidateArg.validate_integer,
|
||||
partial(
|
||||
expr.ValidateArg.validate_sequence,
|
||||
item_validator=expr.ValidateArg.validate_integer,
|
||||
),
|
||||
),
|
||||
default=-2,
|
||||
),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, amount, dim = self.safe_get_all(obj, getter)
|
||||
if not isinstance(dim, tuple):
|
||||
dim = (dim,)
|
||||
if isinstance(amount, float) and amount < 1.0 and amount > -1.0:
|
||||
if len(dim) > 1:
|
||||
raise ValueError(
|
||||
"Cannot use percentage based amount with multiple roll dimensions",
|
||||
)
|
||||
amount = int(tensor.shape[dim[0]] * amount)
|
||||
amount = (amount,) * len(dim)
|
||||
return tensor.roll(amount, dims=dim)
|
||||
|
||||
|
||||
class FlipHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.integer("dim"),
|
||||
expr.Arg.boolean("mirror", False),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, dim, mirror = self.safe_get_all(obj, getter)
|
||||
if dim < 0:
|
||||
dim += tensor.ndim
|
||||
if dim < 0 or dim >= tensor.ndim:
|
||||
raise ValueError(
|
||||
f"Dimension out of range, wanted {dim}, tensor has {tensor.ndim} dimension(s)"
|
||||
)
|
||||
if not mirror:
|
||||
return torch.flip(tensor, (dim,))
|
||||
result = tensor.detach().clone()
|
||||
pivot = tensor.shape[dim] // 2
|
||||
out_slice = tuple(
|
||||
np.s_[:] if d != dim else np.s_[pivot:] for d in range(tensor.ndim)
|
||||
)
|
||||
in_slice = tuple(
|
||||
np.s_[:] if d != dim else np.s_[:pivot] for d in range(tensor.ndim)
|
||||
)
|
||||
result[out_slice] = torch.flip(tensor[in_slice], dims=(dim,))
|
||||
return result
|
||||
|
||||
|
||||
class CopySignHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.tensor("other"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
return torch.copysign(*self.safe_get_all(obj, getter))
|
||||
|
||||
|
||||
class CloneHandler(NormHandler):
|
||||
input_validators = (expr.Arg.tensor("tensor"),)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
return self.safe_get("tensor", obj, getter).clone()
|
||||
|
||||
|
||||
class NewFullHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numscalar_sequence("shape"),
|
||||
expr.Arg.numeric("value", 0.0),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, shape, value = self.safe_get_all(obj, getter)
|
||||
return tensor.new_full(shape, value)
|
||||
|
||||
|
||||
class BlendHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor1"),
|
||||
expr.Arg.tensor("tensor2"),
|
||||
expr.Arg.numeric("scale", 0.5),
|
||||
expr.Arg.string("mode", "lerp"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
t1, t2, scale, mode = self.safe_get_all(obj, getter)
|
||||
blend_handler = BLENDING_MODES.get(mode)
|
||||
if not blend_handler:
|
||||
raise KeyError(f"Unknown blend mode {mode!r}")
|
||||
return blend_handler(t1, t2, scale)
|
||||
|
||||
|
||||
class ContrastAdaptiveSharpeningHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.numeric("scale", 0.5),
|
||||
expr.Arg.boolean("normalize", True),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
t, scale, normalize = self.safe_get_all(obj, getter)
|
||||
return latent.contrast_adaptive_sharpening(t, scale, normalize=normalize)
|
||||
|
||||
|
||||
class ScaleHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.one_of(
|
||||
"scale",
|
||||
(
|
||||
expr.ValidateArg.validate_numeric_scalar,
|
||||
expr.ValidateArg.validate_numscalar_sequence,
|
||||
),
|
||||
),
|
||||
expr.Arg.string("mode", "bicubic"),
|
||||
expr.Arg.boolean("absolute_scale", False),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
t, scale, mode, abs_scale = self.safe_get_all(obj, getter)
|
||||
if isinstance(scale, (list, tuple)):
|
||||
if len(scale) != 2:
|
||||
raise ValueError(
|
||||
"When passing scale as a tuple, it must be in the form (h, w)"
|
||||
)
|
||||
else:
|
||||
scale = (scale, scale)
|
||||
if abs_scale:
|
||||
scale = tuple(int(v) for v in scale)
|
||||
else:
|
||||
scale = (int(t.shape[-2] * scale[0]), int(t.shape[-1] * scale[1]))
|
||||
if not all(v > 0 for v in scale):
|
||||
raise ValueError(f"Invalid scale: scale values must be > 0, got: {scale!r}")
|
||||
return latent.scale_samples(t, scale[1], scale[0], mode=mode)
|
||||
|
||||
|
||||
class NoiseHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.string("type", "gaussian"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
t, typ = self.safe_get_all(obj, getter)
|
||||
ctx = getter.ctx
|
||||
smin, smax, s, sn = (
|
||||
ctx.get_var(k, default=0.0)
|
||||
for k in ("sigma_min", "sigma_max", "sigma", "sigma_next")
|
||||
)
|
||||
ns = latent.get_noise_sampler(typ, t, smin, smax, normalized=False)
|
||||
return ns(s, sn)
|
||||
|
||||
|
||||
class ShapeHandler(expr.BaseHandler):
|
||||
input_validators = (expr.Arg.tensor("tensor"),)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
t = self.safe_get("tensor", obj, getter)
|
||||
return expr.types.ExpTuple((*t.shape,))
|
||||
|
||||
|
||||
class GaussianBlur2DHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.integer("kernel_size"),
|
||||
expr.Arg.numeric_scalar("sigma"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
return latent.gaussian_blur_2d(*self.safe_get_all(obj, getter))
|
||||
|
||||
|
||||
class SNFGuidanceHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("t_tensor"),
|
||||
expr.Arg.tensor("s_tensor"),
|
||||
expr.Arg.integer("t_kernel_size", 3),
|
||||
expr.Arg.numeric_scalar("t_sigma", 1),
|
||||
expr.Arg.integer("s_kernel_size", 3),
|
||||
expr.Arg.numeric_scalar("s_sigma", 1),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
return latent.snf_guidance(*self.safe_get_all(obj, getter))
|
||||
|
||||
|
||||
class RGBLatentHandler(expr.BaseHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("reference"),
|
||||
expr.Arg.numscalar_sequence("rgb"),
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
ctx = getter.ctx.constants.ctx
|
||||
model = ctx.get("model")
|
||||
if model is None:
|
||||
raise ValueError("Ohno")
|
||||
reference, rgb = self.safe_get_all(obj, getter)
|
||||
if len(rgb) != 3 or not all(0 <= v <= 1.0 for v in rgb):
|
||||
raise ValueError("Bad RGB parameter")
|
||||
img = torch.tensor(
|
||||
tuple(v * 2 - 1.0 for v in rgb),
|
||||
device=reference.device,
|
||||
dtype=reference.dtype,
|
||||
).view(1, 3)
|
||||
latent = torch.zeros_like(reference).movedim(1, -1)
|
||||
latent += model.latent_format.rgb_to_latent(img)
|
||||
return latent.movedim(-1, 1)
|
||||
|
||||
|
||||
class TAESDDecodeHandler(expr.BaseHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.string("mode", "sd15"),
|
||||
)
|
||||
validate_output = expr.Arg.image("output")
|
||||
|
||||
def handle(self, obj, getter):
|
||||
t, mode = self.safe_get_all(obj, getter)
|
||||
return OCSTAESD.decode(mode, t)
|
||||
|
||||
|
||||
class TAESDEncodeHandler(expr.BaseHandler):
|
||||
input_validators = (
|
||||
expr.Arg.image("image"),
|
||||
expr.Arg.tensor("reference_latent"),
|
||||
expr.Arg.string("mode", "sd15"),
|
||||
)
|
||||
validate_output = expr.Arg.tensor("output")
|
||||
|
||||
def handle(self, obj, getter):
|
||||
imgbatch, ref, mode = self.safe_get_all(obj, getter)
|
||||
return OCSTAESD.encode(mode, imgbatch, ref)
|
||||
|
||||
|
||||
class ImgShapeHandler(expr.BaseHandler):
|
||||
input_validators = (expr.Arg.tensor("image"),)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
imgbatch = self.safe_get("image", obj, getter)
|
||||
if len(imgbatch) == 0:
|
||||
raise ValueError("Can't get shape of empty image batch")
|
||||
isz = imgbatch[0].size
|
||||
return expr.types.ExpTuple((isz[1], isz[0]))
|
||||
|
||||
|
||||
class ImgPILResizeHandler(expr.BaseHandler):
|
||||
input_validators = (
|
||||
expr.Arg.image("image"),
|
||||
expr.Arg.one_of(
|
||||
"size",
|
||||
(
|
||||
expr.ValidateArg.validate_numeric_scalar,
|
||||
expr.ValidateArg.validate_numscalar_sequence,
|
||||
),
|
||||
),
|
||||
expr.Arg.string("resample_mode", "bicubic"),
|
||||
expr.Arg.boolean("absolute_scale", False),
|
||||
)
|
||||
validate_output = expr.Arg.image("output")
|
||||
|
||||
def handle(self, obj, getter):
|
||||
imgbatch, size, resample_mode, abs_scale = self.safe_get_all(obj, getter)
|
||||
if not isinstance(size, tuple):
|
||||
size = (size, size)
|
||||
if len(size) != 2 or not all(n > 0 for n in size):
|
||||
raise ValueError(
|
||||
"Image resize size parameter must be a positive non-zero number or tuple of positive non-zero height, width"
|
||||
)
|
||||
try:
|
||||
resample_mode = PILImage.Resampling[resample_mode.upper()]
|
||||
except KeyError:
|
||||
raise ValueError("Bad resample mode")
|
||||
if len(imgbatch) == 0:
|
||||
return imgbatch
|
||||
if abs_scale:
|
||||
size = tuple(int(v) for v in size)
|
||||
else:
|
||||
imgsize = imgbatch[0].size
|
||||
size = (int(imgsize[1] * size[0]), int(imgsize[0] * size[1]))
|
||||
new_size = (size[1], size[0])
|
||||
return ImageBatch(img.resize(new_size, resample_mode) for img in imgbatch)
|
||||
|
||||
|
||||
class UnsafeTorchTensorMethodHandler(NormHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("__tensor"),
|
||||
expr.Arg.string("__method"),
|
||||
)
|
||||
|
||||
if ALLOW_ALL_UNSAFE:
|
||||
|
||||
class AlwaysContains:
|
||||
def __contains__(self, k):
|
||||
return True
|
||||
|
||||
whitelist = AlwaysContains()
|
||||
elif ALLOW_UNSAFE:
|
||||
whitelist = unsafe_expression_whitelists.TORCH_FUNCTION_WHITELIST
|
||||
else:
|
||||
whitelist = frozenset()
|
||||
|
||||
def handle(self, obj, getter):
|
||||
if "__method" in obj.kwargs or "__tensor" in obj.kwargs:
|
||||
raise ValueError(
|
||||
"Tensor method call doesn't support passing method or tensor with keyword args"
|
||||
)
|
||||
tensor = self.safe_get("__tensor", obj, getter=getter)
|
||||
method = self.safe_get("__method", obj, getter=getter)
|
||||
args = (
|
||||
self.safe_get(idx, obj, getter=getter) for idx in range(2, len(obj.args))
|
||||
)
|
||||
kwargs = {k: self.safe_get(k, obj, getter=getter) for k in obj.kwargs.keys()}
|
||||
if method not in self.whitelist:
|
||||
raise ValueError(f"Method {method} not whitelisted: cannot call")
|
||||
methodfun = getattr(tensor, method, None)
|
||||
if methodfun is None:
|
||||
raise KeyError(f"Unknown method {method} for Torch tensor")
|
||||
return methodfun(*args, **kwargs)
|
||||
|
||||
|
||||
class UnsafeTorchHandler(expr.BaseHandler):
|
||||
input_validators = (expr.Arg.string("path"),)
|
||||
|
||||
if not ALLOW_ALL_UNSAFE:
|
||||
|
||||
def handle(self, obj, getter):
|
||||
raise ValueError("Unsafe Torch access not allowed")
|
||||
|
||||
else:
|
||||
|
||||
def handle(self, obj, getter):
|
||||
path = self.safe_get("path", obj, getter)
|
||||
keys = path.split(".")
|
||||
if not keys or not all(k for k in keys):
|
||||
raise ValueError(f"Bad path {path}")
|
||||
return resolve_value(keys, torch)
|
||||
|
||||
|
||||
class BlehEnhanceHandler(expr.BaseHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.string("mode"),
|
||||
expr.Arg.numeric_scalar("scale", 1.0),
|
||||
)
|
||||
output_validator = expr.Arg.tensor("output")
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, mode, scale = self.safe_get_all(obj, getter)
|
||||
return EXT_BLEH.latent_utils.enhance_tensor(
|
||||
tensor, mode, scale=scale, adjust_scale=False
|
||||
)
|
||||
|
||||
|
||||
class SonarPowerFilterHandler(expr.BaseHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.present("filter"),
|
||||
)
|
||||
output_validator = expr.Arg.tensor("output")
|
||||
|
||||
default_power_filter = {
|
||||
"mix": 1.0,
|
||||
"normalization_factor": 1.0,
|
||||
"common_mode": 0.0,
|
||||
"channel_correlation": "1,1,1,1,1,1",
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def make_power_filter(cls, fdict, *, toplevel=True):
|
||||
fdict = fdict.copy()
|
||||
compose_with = fdict.pop("compose_with", None)
|
||||
if compose_with:
|
||||
if not isinstance(compose_with, dict):
|
||||
raise TypeError("compose_with must be a dictionary")
|
||||
fdict["compose_with"] = cls.make_power_filter(compose_with, toplevel=False)
|
||||
topargs = {k: fdict.pop(k, dv) for k, dv in cls.default_power_filter.items()}
|
||||
power_filter = EXT_SONAR.powernoise.PowerFilter(**fdict)
|
||||
if not toplevel:
|
||||
return power_filter
|
||||
cc = topargs.get("channel_correlation")
|
||||
if cc is not None:
|
||||
if not isinstance(cc, (list, tuple)) or not all(
|
||||
isinstance(v, (int, float)) for v in cc
|
||||
):
|
||||
raise TypeError(
|
||||
"Bad channel correlation type: must be comma separated string or numeric sequence"
|
||||
)
|
||||
topargs["channel_correlation"] = ",".join(repr(v) for v in cc)
|
||||
return EXT_SONAR.powernoise.PowerNoiseItem(
|
||||
1, power_filter=power_filter, time_brownian=True, **topargs
|
||||
)
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, filter_def = self.safe_get_all(obj, getter)
|
||||
if not isinstance(filter_def, dict):
|
||||
raise TypeError("filter argument must be a dictionary")
|
||||
power_filter = self.make_power_filter(filter_def)
|
||||
filter_rfft = power_filter.make_filter(tensor.shape).to(
|
||||
tensor.device, non_blocking=True
|
||||
)
|
||||
ns = power_filter.make_noise_sampler_internal(
|
||||
tensor,
|
||||
lambda *_unused, latent=tensor: latent,
|
||||
filter_rfft,
|
||||
normalized=False,
|
||||
)
|
||||
return ns(None, None)
|
||||
|
||||
|
||||
class ScaleNNLatentUpscaleHandler(expr.BaseHandler):
|
||||
input_validators = (
|
||||
expr.Arg.tensor("tensor"),
|
||||
expr.Arg.string("mode", "sd1"),
|
||||
expr.Arg.numeric_scalar("scale", 2.0),
|
||||
)
|
||||
output_validator = expr.Arg.tensor("output")
|
||||
|
||||
def handle(self, obj, getter):
|
||||
tensor, mode, scale = self.safe_get_all(obj, getter)
|
||||
if mode not in {"sd1", "sdxl"}:
|
||||
raise ValueError(
|
||||
"Bad mode for t_scale_nnlatentupscale: must be either sd15 or sdxl"
|
||||
)
|
||||
return latent.scale_nnlatentupscale(mode, tensor, scale)
|
||||
|
||||
|
||||
TENSOR_OP_HANDLERS = {
|
||||
"t_norm": NormHandler(),
|
||||
"t_quantilenorm": QuantileNormHandler(),
|
||||
"t_normtoscale": NormToScaleHandler(),
|
||||
"t_normalize_to_scale": NormToScaleHandler(),
|
||||
"t_reshape": ReshapeHandler(),
|
||||
"t_clamp": ClampHandler(),
|
||||
"t_cat": CatHandler(),
|
||||
"t_stack": StackHandler(),
|
||||
"t_indexed_copy": IndexedCopyHandler(),
|
||||
"t_new_like": NewLikeHandler(),
|
||||
"t_mean": MeanHandler(),
|
||||
"t_std": StdHandler(),
|
||||
"t_blend": BlendHandler(),
|
||||
"t_roll": RollHandler(),
|
||||
"t_flip": FlipHandler(),
|
||||
"t_clone": CloneHandler(),
|
||||
"t_newfull": NewFullHandler(),
|
||||
"t_copysign": CopySignHandler(),
|
||||
"t_contrast_adaptive_sharpening": ContrastAdaptiveSharpeningHandler(),
|
||||
"t_scale": ScaleHandler(),
|
||||
"t_noise": NoiseHandler(),
|
||||
"t_shape": ShapeHandler(),
|
||||
"t_gaussianblur2d": GaussianBlur2DHandler(),
|
||||
"t_rgb_latent": RGBLatentHandler(),
|
||||
"t_snf_guidance": SNFGuidanceHandler(),
|
||||
"t_taesd_decode": TAESDDecodeHandler(),
|
||||
"unsafe_tensor_method": UnsafeTorchTensorMethodHandler(),
|
||||
"unsafe_torch": UnsafeTorchHandler(),
|
||||
}
|
||||
|
||||
IMAGE_OP_HANDLERS = {
|
||||
"img_taesd_encode": TAESDEncodeHandler(),
|
||||
"img_shape": ImgShapeHandler(),
|
||||
"img_pil_resize": ImgPILResizeHandler(),
|
||||
}
|
||||
|
||||
HANDLERS |= TENSOR_OP_HANDLERS
|
||||
HANDLERS |= IMAGE_OP_HANDLERS
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
import contextlib
|
||||
import importlib
|
||||
import sys
|
||||
from functools import partial
|
||||
from types import ModuleType
|
||||
from typing import Callable, NamedTuple
|
||||
|
||||
|
||||
class Integrations:
|
||||
class Integration(NamedTuple):
|
||||
key: str
|
||||
module_name: str
|
||||
handler: Callable | None = None
|
||||
|
||||
def __init__(self):
|
||||
self.initialized = False
|
||||
self.modules = {}
|
||||
self.init_handlers = []
|
||||
self.handlers = []
|
||||
|
||||
def __getitem__(self, key):
|
||||
return self.modules[key]
|
||||
|
||||
def __contains__(self, key):
|
||||
return key in self.modules
|
||||
|
||||
def __getattr__(self, key):
|
||||
return self.modules.get(key)
|
||||
|
||||
def get(self, key, default=None):
|
||||
return self.modules.get(key, default)
|
||||
|
||||
@staticmethod
|
||||
def get_custom_node(module_name: str, key: str) -> ModuleType | None:
|
||||
bi_module = sys.modules.get("_blepping_integrations", {}).get(key)
|
||||
if bi_module is not None:
|
||||
return bi_module
|
||||
module_key = f"custom_nodes.{module_name}"
|
||||
with contextlib.suppress(StopIteration):
|
||||
spec = importlib.util.find_spec(module_key)
|
||||
if spec is None:
|
||||
return None
|
||||
return next(
|
||||
v
|
||||
for v in sys.modules.copy().values()
|
||||
if hasattr(v, "__spec__")
|
||||
and v.__spec__ is not None
|
||||
and v.__spec__.origin == spec.origin
|
||||
)
|
||||
return None
|
||||
|
||||
def register_init_handler(self, handler):
|
||||
self.init_handlers.append(handler)
|
||||
|
||||
def register_integration(self, key: str, module_name: str, handler=None) -> None:
|
||||
if self.initialized:
|
||||
raise ValueError(
|
||||
"Internal error: Cannot register integration after initialization",
|
||||
)
|
||||
if any(item[0] == key or item[1] == module_name for item in self.handlers):
|
||||
errstr = (
|
||||
f"Module {module_name} ({key}) already in integration handlers list!"
|
||||
)
|
||||
raise ValueError(errstr)
|
||||
self.handlers.append(self.Integration(key, module_name, handler))
|
||||
|
||||
def initialize(self) -> None:
|
||||
if self.initialized:
|
||||
return
|
||||
self.initialized = True
|
||||
for ih in self.handlers:
|
||||
module = self.get_custom_node(ih.module_name, ih.key)
|
||||
if module is None:
|
||||
continue
|
||||
if ih.handler is not None:
|
||||
module = ih.handler(module)
|
||||
if module is not None:
|
||||
self.modules[ih.key] = module
|
||||
|
||||
for init_handler in self.init_handlers:
|
||||
init_handler(self)
|
||||
|
||||
|
||||
class OCSIntegrations(Integrations):
|
||||
def __init__(self, *args: list, **kwargs: dict):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.register_integration("bleh", "ComfyUI-bleh", self.bleh_integration)
|
||||
self.register_integration("sonar", "ComfyUI-sonar", self.sonar_integration)
|
||||
self.register_integration("nnlatentupscale", "ComfyUi_NNLatentUpscale")
|
||||
self.register_integration("tiled_diffusion", "ComfyUI-TiledDiffusion")
|
||||
|
||||
@classmethod
|
||||
def bleh_integration(cls, module: ModuleType) -> ModuleType | None:
|
||||
bleh_version = getattr(module, "BLEH_VERSION", -1)
|
||||
if bleh_version < 1:
|
||||
return None
|
||||
return module.py
|
||||
|
||||
@classmethod
|
||||
def sonar_integration(cls, module: ModuleType) -> ModuleType | None:
|
||||
return module.py
|
||||
|
||||
|
||||
MODULES = OCSIntegrations()
|
||||
|
||||
|
||||
class IntegratedNode(type):
|
||||
@staticmethod
|
||||
def wrap_INPUT_TYPES(orig_method: Callable, *args: list, **kwargs: dict) -> dict:
|
||||
MODULES.initialize()
|
||||
return orig_method(*args, **kwargs)
|
||||
|
||||
def __new__(cls: type, name: str, bases: tuple, attrs: dict) -> object:
|
||||
obj = type.__new__(cls, name, bases, attrs)
|
||||
if hasattr(obj, "INPUT_TYPES"):
|
||||
obj.INPUT_TYPES = partial(cls.wrap_INPUT_TYPES, obj.INPUT_TYPES)
|
||||
return obj
|
||||
|
||||
|
||||
__all__ = ("MODULES",)
|
||||
+524
@@ -0,0 +1,524 @@
|
||||
import collections
|
||||
|
||||
import torch
|
||||
|
||||
from . import expression as expr
|
||||
from . import expression_handlers
|
||||
|
||||
from .external import MODULES as EXT
|
||||
from .utils import fallback
|
||||
|
||||
OD = collections.OrderedDict
|
||||
|
||||
BLENDING_MODES = {
|
||||
"lerp": torch.lerp,
|
||||
"a_only": lambda a, b, t: a * t,
|
||||
"b_only": lambda a, b, t: b * t,
|
||||
"inject": lambda a, b, t: (b * t).add_(a),
|
||||
}
|
||||
|
||||
FILTER = {}
|
||||
|
||||
EXT_BLEH = None
|
||||
|
||||
|
||||
def init_integrations(integrations):
|
||||
global BLENDING_MODES, FILTER, EXT_BLEH
|
||||
EXT_BLEH = integrations.bleh
|
||||
if EXT_BLEH is not None:
|
||||
BLENDING_MODES = EXT_BLEH.latent_utils.BLENDING_MODES | BLENDING_MODES
|
||||
FILTER |= {
|
||||
"bleh_enhance": BlehEnhanceFilter,
|
||||
"bleh_ops": BlehOpsFilter,
|
||||
}
|
||||
ext_sonar = integrations.sonar
|
||||
if ext_sonar is not None:
|
||||
FILTER["sonar_power_filter"] = SonarPowerFilter
|
||||
|
||||
|
||||
EXT.register_init_handler(init_integrations)
|
||||
|
||||
FILTER_HANDLERS = expr.HandlerContext(
|
||||
expr.BASIC_HANDLERS | expression_handlers.HANDLERS
|
||||
)
|
||||
|
||||
|
||||
class FilterRefs:
|
||||
def __init__(self, kvs=None, *, ctx=None):
|
||||
self.kvs = fallback(kvs, {})
|
||||
self.ctx = fallback(ctx, {})
|
||||
|
||||
def get(self, k, default=None):
|
||||
return self.kvs.get(k, default)
|
||||
|
||||
def __getitem__(self, k):
|
||||
return self.kvs[k]
|
||||
|
||||
def __setitem__(self, k, v):
|
||||
self.kvs[k] = v
|
||||
|
||||
def clone(self):
|
||||
return self.__class__(self.kvs.copy(), ctx=self.ctx)
|
||||
|
||||
def __or__(self, other):
|
||||
return self.__class__(self.kvs | other.kvs, ctx=self.ctx | other.ctx)
|
||||
|
||||
def __ior__(self, other):
|
||||
self.kvs |= other.kvs
|
||||
self.ctx |= other.ctx
|
||||
return self
|
||||
|
||||
def __delitem__(self, k):
|
||||
del self.kvs[k]
|
||||
|
||||
def __contains__(self, k):
|
||||
return k in self.kvs
|
||||
|
||||
def __missing__(self, k):
|
||||
return self.kvs.__missing__(k)
|
||||
|
||||
def __len__(self):
|
||||
return len(self.kvs)
|
||||
|
||||
def __iter__(self):
|
||||
return self.kvs.__iter__()
|
||||
|
||||
def items(self):
|
||||
return self.kvs.items()
|
||||
|
||||
@classmethod
|
||||
def from_ss(cls, ss, *, have_current=False):
|
||||
ms = ss.model.model_sampling
|
||||
fr = cls(
|
||||
{
|
||||
"step": ss.step,
|
||||
"substep": ss.substep,
|
||||
"dt": ss.dt,
|
||||
"sigma_idx": ss.idx,
|
||||
"sigma": ss.sigma,
|
||||
"sigma_next": ss.sigma_next,
|
||||
"sigma_down": ss.sigma_down,
|
||||
"sigma_up": ss.sigma_up,
|
||||
"sigma_prev": ss.sigma_prev,
|
||||
"hist_len": len(ss.hist),
|
||||
"sigma_min": ms.sigma_min.item(),
|
||||
"sigma_max": ms.sigma_max.item(),
|
||||
"step_pct": float(ss.step / ss.total_steps),
|
||||
"total_steps": ss.total_steps,
|
||||
"sampling_pct": (999 - ms.timestep(ss.sigma).item()) / 999,
|
||||
"is_rectified_flow": ss.model.is_rectified_flow,
|
||||
"original_cfg_scale": ss.model.inner_cfg_scale,
|
||||
},
|
||||
ctx={"ss": ss, "model": ss.model},
|
||||
)
|
||||
if have_current and len(ss.hist) > 0:
|
||||
fr |= cls.from_mr(ss.hcur)
|
||||
fr["d"] = ss.d
|
||||
if not have_current and len(ss.hist) > 0:
|
||||
hist_offs = -1
|
||||
elif len(ss.hist) > 1:
|
||||
hist_offs = -2
|
||||
else:
|
||||
hist_offs = None
|
||||
if hist_offs is not None:
|
||||
hprev = ss.hist[hist_offs]
|
||||
fr.kvs |= {f"{k}_prev": v for k, v in cls.from_mr(hprev).kvs.items()}
|
||||
fr["d_prev"] = hprev.d
|
||||
return fr
|
||||
|
||||
@classmethod
|
||||
def from_mr(cls, mr):
|
||||
return cls({
|
||||
k: getattr(mr, ak)
|
||||
for k, ak in (
|
||||
("cond", "denoised_cond"),
|
||||
("denoised", "denoised"),
|
||||
("model_call", "call_idx"),
|
||||
("sigma", "sigma"),
|
||||
("uncond", "denoised_uncond"),
|
||||
("x", "x"),
|
||||
)
|
||||
if getattr(mr, ak, None) is not None
|
||||
})
|
||||
|
||||
@classmethod
|
||||
def from_sr(cls, sr):
|
||||
return cls({
|
||||
k: getattr(sr, ak)
|
||||
for k, ak in (
|
||||
("cond", "denoised_cond"),
|
||||
("denoised", "denoised"),
|
||||
("noise", "noise_pred"),
|
||||
("sigma_down", "sigma_down"),
|
||||
("sigma_next", "sigma_next"),
|
||||
("sigma_up", "sigma_up"),
|
||||
("sigma", "sigma"),
|
||||
("step", "step"),
|
||||
("substep", "substep"),
|
||||
("uncond", "denoised_uncond"),
|
||||
("x", "x"),
|
||||
)
|
||||
if getattr(sr, ak, None) is not None
|
||||
})
|
||||
|
||||
|
||||
class Filter:
|
||||
name = "unknown"
|
||||
uses_ref = False
|
||||
default_options = {
|
||||
"enabled": True,
|
||||
"when": None,
|
||||
"input": "default",
|
||||
"output": "default",
|
||||
"ref": "default",
|
||||
"final": "default",
|
||||
"blend_mode": "lerp",
|
||||
"strength": 1.0,
|
||||
}
|
||||
|
||||
def __init__(self, **options):
|
||||
self.options = options
|
||||
self.set_options(self.default_options)
|
||||
if self.when is not None:
|
||||
self.when = expr.Expression(self.when)
|
||||
for key in ("input", "output", "ref", "final"):
|
||||
if not self.uses_ref and key == "ref":
|
||||
continue
|
||||
val = getattr(self, key)
|
||||
val = make_filter(val) if isinstance(val, dict) else expr.Expression(val)
|
||||
setattr(self, key, val)
|
||||
if self.blend_mode not in BLENDING_MODES:
|
||||
raise ValueError("Bad blend mode")
|
||||
|
||||
def set_options(self, defaults):
|
||||
for k, v in defaults.items():
|
||||
setattr(self, k, self.options.pop(k, v))
|
||||
|
||||
def apply(self, input_latent, default_ref=None, refs=None, **kwargs):
|
||||
if not self.check_applies(refs):
|
||||
return input_latent
|
||||
refs = fallback(refs, FilterRefs()).clone()
|
||||
latent = self.get_ref("input", input_latent, self.input, refs=refs)
|
||||
refs["input"] = latent
|
||||
if not self.uses_ref:
|
||||
ref_latent = None
|
||||
else:
|
||||
ref_latent = (
|
||||
self.get_ref("ref", default_ref, self.ref, refs=refs)
|
||||
if default_ref is not None
|
||||
else None
|
||||
)
|
||||
refs["ref"] = ref_latent
|
||||
output_latent = self.get_ref(
|
||||
"output",
|
||||
self.filter(latent, ref_latent, refs=refs, **kwargs),
|
||||
self.output,
|
||||
refs=refs,
|
||||
)
|
||||
refs["output"] = output_latent
|
||||
return self.get_ref(
|
||||
"final",
|
||||
BLENDING_MODES[self.blend_mode](
|
||||
input_latent[: output_latent.shape[0]], output_latent, self.strength
|
||||
),
|
||||
self.final,
|
||||
refs=refs,
|
||||
)
|
||||
|
||||
def filter(self, latent, ref_latent, *, refs, **kwargs):
|
||||
raise NotImplementedError
|
||||
|
||||
def check_applies(self, refs=None):
|
||||
if not self.enabled:
|
||||
return False
|
||||
if self.when is None:
|
||||
return True
|
||||
refs = fallback(refs, FilterRefs())
|
||||
matched = self.when.eval(FILTER_HANDLERS.clone(constants=refs, variables={}))
|
||||
# if matched:
|
||||
# print("\nMATCH", self.name)
|
||||
return matched
|
||||
|
||||
def get_ref(self, name, default_ref, ops, *, refs=None):
|
||||
if isinstance(ops, Filter):
|
||||
return ops.apply(default_ref, ops, refs=refs)
|
||||
drefs = FilterRefs({"default": default_ref})
|
||||
refs = drefs if refs is None else refs | drefs
|
||||
return ops.eval(FILTER_HANDLERS.clone(constants=refs, variables={}))
|
||||
|
||||
def __str__(self):
|
||||
prettyvals = ", ".join(
|
||||
f"{k}={getattr(self, k, None)!s}" for k in self.default_options.keys()
|
||||
)
|
||||
return f"<Filter({self.name}): {prettyvals}>"
|
||||
|
||||
|
||||
class SimpleFilter(Filter):
|
||||
name = "simple"
|
||||
|
||||
def filter(self, latent, *args, **kwargs):
|
||||
return latent
|
||||
|
||||
|
||||
class BlendFilter(Filter):
|
||||
name = "blend"
|
||||
default_options = Filter.default_options | {"filter1": None, "filter2": None}
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if not (isinstance(self.filter1, dict) and isinstance(self.filter2, dict)):
|
||||
raise ValueError("Must set filter1 and filter2")
|
||||
self.filter1 = make_filter(self.filter1)
|
||||
self.filter2 = make_filter(self.filter2)
|
||||
|
||||
def filter(self, latent, ref_latent, *, refs, **kwargs):
|
||||
if self.blend_mode == "lerp":
|
||||
if self.strength == 0:
|
||||
return self.filter1(latent, ref_latent, refs=refs, **kwargs)
|
||||
if self.strength == 1:
|
||||
return self.filter2(latent, ref_latent, refs=refs, **kwargs)
|
||||
return BLENDING_MODES[self.blend_mode](
|
||||
self.filter1.apply(latent, ref_latent, refs=refs, **kwargs),
|
||||
self.filter2.apply(latent, ref_latent, refs=refs, **kwargs),
|
||||
self.strength,
|
||||
)
|
||||
|
||||
|
||||
class ListFilter(Filter):
|
||||
name = "list"
|
||||
default_options = Filter.default_options | {"filters": ()}
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if not isinstance(self.filters, (list, tuple)):
|
||||
raise ValueError("filters key must be a sequence")
|
||||
self.filters = tuple(make_filter(filt) for filt in self.filters)
|
||||
|
||||
def filter(self, latent, ref_latent, *, refs, **kwargs):
|
||||
if not self.filters:
|
||||
return latent
|
||||
for filt in self.filters:
|
||||
latent = filt.apply(latent, ref_latent, refs=refs, **kwargs)
|
||||
return latent
|
||||
|
||||
|
||||
class NormalizeFilter(Filter):
|
||||
name = "normalize"
|
||||
uses_ref = True
|
||||
default_options = Filter.default_options | {
|
||||
"adjust_target": 0,
|
||||
"balance_scale": 1.0,
|
||||
"adjust_scale": 1.0,
|
||||
"dims": (-2, -1),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
start_step=0,
|
||||
end_step=9999,
|
||||
phase="after",
|
||||
adjust_target=0,
|
||||
balance_scale=1.0,
|
||||
adjust_scale=1.0,
|
||||
dims=(-2, -1),
|
||||
):
|
||||
self.start_step = start_step
|
||||
self.end_step = end_step
|
||||
self.phase = phase.lower().strip() # before, after, all
|
||||
if isinstance(adjust_target, str):
|
||||
adjust_target = adjust_target.lower().strip()
|
||||
if adjust_target not in ("x",):
|
||||
raise ValueError("Bad target mean")
|
||||
# "x", scalar or array matching mean dims
|
||||
self.adjust_target = adjust_target
|
||||
# multiplier on adjustment, scalar or array matching mean dims
|
||||
self.adjust_scale = adjust_scale
|
||||
self.balance_scale = balance_scale
|
||||
self.dims = dims
|
||||
|
||||
def __call__(self, ss, sigma, latent, phase, orig_x=None):
|
||||
if ss.step < self.start_step or ss.step > self.end_step:
|
||||
return latent
|
||||
if self.phase != "all" and phase != self.phase:
|
||||
return latent
|
||||
if self.adjust_target == "x" and orig_x is None:
|
||||
raise ValueError("Can only use source x in after phase")
|
||||
adjust_scale, balance_scale = (
|
||||
torch.tensor(v, dtype=latent.dtype).to(latent)
|
||||
if isinstance(v, (list, tuple))
|
||||
else v
|
||||
for v in (self.adjust_scale, self.balance_scale)
|
||||
)
|
||||
latent_mean = latent.mean(dim=self.dims, keepdim=True)
|
||||
# print("MEAN", latent_mean)
|
||||
latent = latent - latent_mean * balance_scale
|
||||
if self.adjust_target == "x":
|
||||
latent += orig_x.mean(dim=self.dims, keepdim=True) * adjust_scale
|
||||
elif isinstance(self.adjust_target, (list, tuple)):
|
||||
adjust_target = torch.tensor(self.adjust_target, dtype=latent.dtype).to(
|
||||
latent
|
||||
)
|
||||
latent += adjust_target * adjust_scale
|
||||
else:
|
||||
latent += self.adjust_target * adjust_scale
|
||||
return latent
|
||||
|
||||
|
||||
class NormalizeFilter_:
|
||||
def __init__(
|
||||
self,
|
||||
start_step=0,
|
||||
end_step=9999,
|
||||
phase="after",
|
||||
adjust_target=0,
|
||||
balance_scale=1.0,
|
||||
adjust_scale=1.0,
|
||||
dims=(-2, -1),
|
||||
):
|
||||
self.start_step = start_step
|
||||
self.end_step = end_step
|
||||
self.phase = phase.lower().strip() # before, after, all
|
||||
if isinstance(adjust_target, str):
|
||||
adjust_target = adjust_target.lower().strip()
|
||||
if adjust_target not in ("x",):
|
||||
raise ValueError("Bad target mean")
|
||||
# "x", scalar or array matching mean dims
|
||||
self.adjust_target = adjust_target
|
||||
# multiplier on adjustment, scalar or array matching mean dims
|
||||
self.adjust_scale = adjust_scale
|
||||
self.balance_scale = balance_scale
|
||||
self.dims = dims
|
||||
|
||||
def __call__(self, ss, sigma, latent, phase, orig_x=None):
|
||||
if ss.step < self.start_step or ss.step > self.end_step:
|
||||
return latent
|
||||
if self.phase != "all" and phase != self.phase:
|
||||
return latent
|
||||
if self.adjust_target == "x" and orig_x is None:
|
||||
raise ValueError("Can only use source x in after phase")
|
||||
adjust_scale, balance_scale = (
|
||||
torch.tensor(v, dtype=latent.dtype).to(latent)
|
||||
if isinstance(v, (list, tuple))
|
||||
else v
|
||||
for v in (self.adjust_scale, self.balance_scale)
|
||||
)
|
||||
latent_mean = latent.mean(dim=self.dims, keepdim=True)
|
||||
# print("MEAN", latent_mean)
|
||||
latent = latent - latent_mean * balance_scale
|
||||
if self.adjust_target == "x":
|
||||
latent += orig_x.mean(dim=self.dims, keepdim=True) * adjust_scale
|
||||
elif isinstance(self.adjust_target, (list, tuple)):
|
||||
adjust_target = torch.tensor(self.adjust_target, dtype=latent.dtype).to(
|
||||
latent
|
||||
)
|
||||
latent += adjust_target * adjust_scale
|
||||
else:
|
||||
latent += self.adjust_target * adjust_scale
|
||||
return latent
|
||||
|
||||
|
||||
Normalize = NormalizeFilter
|
||||
|
||||
|
||||
class BlehEnhanceFilter(Filter):
|
||||
name = "bleh_enhance"
|
||||
default_options = Filter.default_options | {
|
||||
"enhance_mode": None,
|
||||
"enhance_scale": 1.0,
|
||||
}
|
||||
|
||||
def filter(self, latent, *args, **kwargs):
|
||||
if self.enhance_mode is None or self.enhance_scale == 1:
|
||||
return latent
|
||||
return EXT_BLEH.latent_utils.enhance_tensor(
|
||||
latent, self.enhance_mode, scale=self.enhance_scale, adjust_scale=False
|
||||
)
|
||||
|
||||
|
||||
class BlehOpsFilter(Filter):
|
||||
name = "bleh_ops"
|
||||
default_options = Filter.default_options | {"ops": ()}
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if isinstance(self.ops, (tuple, list)):
|
||||
self.ops = EXT_BLEH.nodes.ops.RuleGroup(
|
||||
tuple(
|
||||
r for rs in self.ops for r in EXT_BLEH.nodes.ops.Rule.from_dict(rs)
|
||||
)
|
||||
)
|
||||
return
|
||||
if not isinstance(self.ops, str):
|
||||
raise ValueError("ops key must be a YAML string or list of object")
|
||||
self.ops = EXT_BLEH.nodes.ops.RuleGroup.from_yaml(self.ops)
|
||||
|
||||
def filter(self, latent, ref_latent, *args, refs=None, **kwargs):
|
||||
if not self.ops:
|
||||
return latent
|
||||
refs = fallback(refs, {})
|
||||
bops = EXT_BLEH.nodes.ops
|
||||
state = {
|
||||
bops.CondType.TYPE: bops.PatchType.LATENT,
|
||||
bops.CondType.PERCENT: 0.0,
|
||||
bops.CondType.BLOCK: -1,
|
||||
bops.CondType.STAGE: -1,
|
||||
bops.CondType.STEP: refs.get("step", 0),
|
||||
bops.CondType.STEP_EXACT: refs.get("step", -1),
|
||||
"h": latent,
|
||||
"hsp": ref_latent,
|
||||
"target": "h",
|
||||
}
|
||||
self.ops.eval(state, toplevel=True)
|
||||
return state["h"]
|
||||
|
||||
|
||||
class SonarPowerFilter(Filter):
|
||||
name = "sonar_power_filter"
|
||||
default_options = Filter.default_options
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
power_filter = self.options.pop("power_filter", None)
|
||||
if power_filter is None:
|
||||
self.power_filter = None
|
||||
return
|
||||
if not isinstance(power_filter, dict):
|
||||
raise ValueError("power_filter key must be dict or null")
|
||||
self.power_filter = (
|
||||
expression_handlers.SonarPowerFilterHandler.make_power_filter(power_filter)
|
||||
)
|
||||
|
||||
def filter(self, latent, ref_latent, *args, refs=None, **kwargs):
|
||||
if not self.power_filter:
|
||||
return latent
|
||||
filter_rfft = self.power_filter.make_filter(latent.shape).to(
|
||||
latent.device, non_blocking=True
|
||||
)
|
||||
ns = self.power_filter.make_noise_sampler_internal(
|
||||
latent,
|
||||
lambda *_unused, latent=latent: latent,
|
||||
filter_rfft,
|
||||
normalized=False,
|
||||
)
|
||||
return ns(None, None)
|
||||
|
||||
|
||||
def make_filter(args):
|
||||
if not isinstance(args, dict):
|
||||
raise TypeError(f"Bad type for filter: {type(args)}")
|
||||
args = args.copy()
|
||||
filter_type = args.pop("filter_type", "simple")
|
||||
if not isinstance(filter_type, str):
|
||||
raise ValueError("Missing or invalid filter_type")
|
||||
filter_fun = FILTER.get(filter_type)
|
||||
if filter_fun is None:
|
||||
raise ValueError(f"Unknown filter_type: {filter_type}")
|
||||
return filter_fun(**args)
|
||||
|
||||
|
||||
FILTER |= {
|
||||
"simple": SimpleFilter,
|
||||
"blend": BlendFilter,
|
||||
"list": ListFilter,
|
||||
"normalize": NormalizeFilter,
|
||||
}
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
import folder_paths
|
||||
import latent_preview
|
||||
|
||||
from comfy.taesd.taesd import TAESD
|
||||
from comfy.utils import bislerp
|
||||
from comfy import latent_formats
|
||||
|
||||
from .external import MODULES as EXT
|
||||
|
||||
EXT_NNLATENTUPSCALE = None
|
||||
|
||||
|
||||
def init_integrations(integrations):
|
||||
global get_noise_sampler, EXT_NNLATENTUPSCALE
|
||||
|
||||
ext_sonar = integrations.sonar
|
||||
if ext_sonar is not None:
|
||||
get_noise_sampler = ext_sonar.noise.get_noise_sampler
|
||||
EXT_NNLATENTUPSCALE = EXT.nnlatentupscale
|
||||
|
||||
|
||||
EXT.register_init_handler(init_integrations)
|
||||
|
||||
|
||||
def normalize_to_scale(latent, target_min, target_max, *, dim=(-3, -2, -1)):
|
||||
min_val, max_val = (
|
||||
latent.amin(dim=dim, keepdim=True),
|
||||
latent.amax(dim=dim, keepdim=True),
|
||||
)
|
||||
normalized = (latent - min_val).div_(max_val - min_val)
|
||||
return (
|
||||
normalized.mul_(target_max - target_min)
|
||||
.add_(target_min)
|
||||
.clamp_(target_min, target_max)
|
||||
)
|
||||
|
||||
|
||||
# Improvements by https://github.com/Clybius
|
||||
# The following is modified to work with latent images of ~0 mean from https://github.com/Jamy-L/Pytorch-Contrast-Adaptive-Sharpening/tree/main.
|
||||
# The algorithm is directly implemented from FidelityFX's source code that can be found here: https://github.com/GPUOpen-Effects/FidelityFX-CAS/blob/master/ffx-cas/ffx_cas.h.
|
||||
def contrast_adaptive_sharpening( # noqa: PLR0914
|
||||
x,
|
||||
amount=0.8,
|
||||
*,
|
||||
normalize=True,
|
||||
epsilon=1e-06,
|
||||
):
|
||||
orig_shape = x.shape
|
||||
if x.ndim == 5:
|
||||
x = x.reshape(orig_shape[0], orig_shape[1] * orig_shape[2], *orig_shape[-2:])
|
||||
elif x.ndim != 4:
|
||||
raise ValueError(
|
||||
"Contrast-adaptive sharpening requires a tensor with 4 or 5 dimensions",
|
||||
)
|
||||
|
||||
def on_abs_stacked(tensor_list, f, *args: list, **kwargs: dict):
|
||||
return f(torch.abs(torch.stack(tensor_list)), *args, **kwargs)[0]
|
||||
|
||||
if normalize:
|
||||
luminance = torch.linalg.vector_norm(x, dim=1, keepdim=True).add_(1e-08)
|
||||
x = x / luminance
|
||||
orig_mean = x.mean(dim=(-3, -2, -1), keepdim=True)
|
||||
x -= orig_mean
|
||||
|
||||
x_padded = F.pad(x, pad=(1, 1, 1, 1))
|
||||
x_padded = torch.complex(x_padded, torch.zeros_like(x_padded))
|
||||
# each side gets padded with 1 pixel
|
||||
# padding = same by default
|
||||
|
||||
# Extracting the 3x3 neighborhood around each pixel
|
||||
# a b c
|
||||
# d e f
|
||||
# g h i
|
||||
|
||||
a = x_padded[..., :-2, :-2]
|
||||
b = x_padded[..., :-2, 1:-1]
|
||||
c = x_padded[..., :-2, 2:]
|
||||
d = x_padded[..., 1:-1, :-2]
|
||||
e = x_padded[..., 1:-1, 1:-1]
|
||||
f = x_padded[..., 1:-1, 2:]
|
||||
g = x_padded[..., 2:, :-2]
|
||||
h = x_padded[..., 2:, 1:-1]
|
||||
i = x_padded[..., 2:, 2:]
|
||||
|
||||
# Computing contrast
|
||||
cross = (b, d, e, f, h)
|
||||
mn = on_abs_stacked(cross, torch.min, axis=0)
|
||||
mx = on_abs_stacked(cross, torch.max, axis=0)
|
||||
|
||||
diag = (a, c, g, i)
|
||||
mn2 = on_abs_stacked(diag, torch.min, axis=0)
|
||||
mx2 = on_abs_stacked(diag, torch.max, axis=0)
|
||||
|
||||
mx = mx + mx2
|
||||
mn = mn + mn2
|
||||
|
||||
# Computing local weight
|
||||
inv_mx = torch.reciprocal(mx + epsilon) # 1/mx
|
||||
|
||||
amp = inv_mx * mn
|
||||
|
||||
# scaling
|
||||
amp = torch.sqrt(amp)
|
||||
|
||||
w = -amp * (amount * (1 / 5 - 1 / 8) + 1 / 8)
|
||||
# w scales from 0 when amp=0 to K for amp=1
|
||||
# K scales from -1/5 when amount=1 to -1/8 for amount=0
|
||||
|
||||
# The local conv filter is
|
||||
# 0 w 0
|
||||
# w 1 w
|
||||
# 0 w 0
|
||||
div = torch.reciprocal(1 + 4 * w)
|
||||
output = ((b + d + f + h) * w + e) * div
|
||||
|
||||
output = output.real
|
||||
for ob, xb in zip(x, output):
|
||||
ob.clamp_(*xb.aminmax())
|
||||
if normalize:
|
||||
output = output.add_(orig_mean).mul_(luminance)
|
||||
return output.reshape(*orig_shape)
|
||||
|
||||
|
||||
class ImageBatch(tuple):
|
||||
__slots__ = ()
|
||||
|
||||
|
||||
class OCSTAESD:
|
||||
latent_formats = {
|
||||
"sd15": latent_formats.SD15(),
|
||||
"sdxl": latent_formats.SDXL(),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def get_decoder_name(cls, fmt):
|
||||
return cls.latent_formats[fmt].taesd_decoder_name
|
||||
|
||||
@classmethod
|
||||
def get_encoder_name(cls, fmt):
|
||||
result = cls.get_decoder_name(fmt)
|
||||
if not result.endswith("_decoder"):
|
||||
raise RuntimeError(
|
||||
f"Could not determine TAESD encoder name from {result!r}"
|
||||
)
|
||||
return f"{result[:-7]}encoder"
|
||||
|
||||
@classmethod
|
||||
def get_taesd_path(cls, name):
|
||||
taesd_path = next(
|
||||
(
|
||||
fn
|
||||
for fn in folder_paths.get_filename_list("vae_approx")
|
||||
if fn.startswith(name)
|
||||
),
|
||||
"",
|
||||
)
|
||||
if taesd_path == "":
|
||||
raise RuntimeError(f"Could not get TAESD path for {name!r}")
|
||||
return folder_paths.get_full_path("vae_approx", taesd_path)
|
||||
|
||||
@classmethod
|
||||
def decode(cls, fmt, latent):
|
||||
latent_format = cls.latent_formats[fmt]
|
||||
filename = cls.get_taesd_path(cls.get_decoder_name(fmt))
|
||||
model = TAESD(
|
||||
decoder_path=filename, latent_channels=latent_format.latent_channels
|
||||
).to(latent.device)
|
||||
result = model.decode(latent).movedim(1, 3)
|
||||
return ImageBatch(
|
||||
latent_preview.preview_to_image(result[batch_idx])
|
||||
for batch_idx in range(result.shape[0])
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def img_to_encoder_input(imgbatch):
|
||||
return torch.stack(
|
||||
tuple(
|
||||
torch.tensor(np.array(img), dtype=torch.float32)
|
||||
.div_(127)
|
||||
.sub_(1.0)
|
||||
.clamp_(-1, 1)
|
||||
for img in imgbatch
|
||||
),
|
||||
dim=0,
|
||||
).movedim(-1, 1)
|
||||
|
||||
@classmethod
|
||||
def encode(cls, fmt, imgbatch, latent, *, normalize_output=False):
|
||||
latent_format = cls.latent_formats[fmt]
|
||||
rv = latent_format.process_out(1.0)
|
||||
filename = cls.get_taesd_path(cls.get_encoder_name(fmt))
|
||||
model = TAESD(
|
||||
encoder_path=filename, latent_channels=latent_format.latent_channels
|
||||
).to(device=latent.device)
|
||||
result = model.encode(cls.img_to_encoder_input(imgbatch).to(latent.device))
|
||||
return result.to(latent.dtype).clamp(-rv, rv)
|
||||
|
||||
|
||||
bleh_scale_samples = None
|
||||
UPSCALE_METHODS = ("bicubic", "bislerp", "bilinear", "nearest-exact", "area")
|
||||
|
||||
|
||||
def scale_samples(
|
||||
samples,
|
||||
width,
|
||||
height,
|
||||
mode="bicubic",
|
||||
sigma=None, # noqa: ARG001
|
||||
):
|
||||
global bleh_scale_samples, UPSCALE_METHODS
|
||||
if bleh_scale_samples is None:
|
||||
bleh = EXT.get("bleh")
|
||||
if bleh is not None:
|
||||
bleh_scale_samples = bleh.latent_utils.scale_samples
|
||||
UPSCALE_METHODS = bleh.latent_utils.UPSCALE_METHODS
|
||||
else:
|
||||
bleh_scale_samples = False
|
||||
if bleh_scale_samples:
|
||||
return bleh_scale_samples(samples, width, height, mode=mode, sigma=sigma)
|
||||
if mode == "bislerp":
|
||||
return bislerp(samples, width, height)
|
||||
return F.interpolate(samples, size=(height, width), mode=mode)
|
||||
|
||||
|
||||
def get_noise_sampler(noise_type, x, *_args: list, **_kwargs: dict): # noqa: F811
|
||||
if noise_type != "gaussian":
|
||||
raise ValueError("Only gaussian noise supported")
|
||||
return lambda _s, _sn: torch.randn_like(x)
|
||||
|
||||
|
||||
def scale_nnlatentupscale(mode, latent, scale=2.0, *, scale_factor=0.13025):
|
||||
if EXT_NNLATENTUPSCALE is None:
|
||||
raise RuntimeError("nnlatentupscale integration not available")
|
||||
mode = {"sdxl": "SDXL", "sd1": "SD 1.x"}.get(mode)
|
||||
if mode is None:
|
||||
raise ValueError("Bad mode")
|
||||
node = EXT_NNLATENTUPSCALE.NNLatentUpscale()
|
||||
model = EXT_NNLATENTUPSCALE.latent_resizer.LatentResizer.load_model(
|
||||
node.weight_path[mode], latent.device, latent.dtype
|
||||
).to(device=latent.device)
|
||||
result = (
|
||||
model(scale_factor * latent, scale=scale).to(
|
||||
dtype=latent.dtype, device=latent.device
|
||||
)
|
||||
/ scale_factor
|
||||
)
|
||||
del model
|
||||
return result
|
||||
|
||||
|
||||
# Gaussian blur
|
||||
def gaussian_blur_2d(img, kernel_size, sigma):
|
||||
height = img.shape[-1]
|
||||
kernel_size = min(kernel_size, height - (height % 2 - 1))
|
||||
ksize_half = (kernel_size - 1) * 0.5
|
||||
|
||||
x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size)
|
||||
|
||||
pdf = torch.exp(-0.5 * (x / sigma).pow(2))
|
||||
|
||||
x_kernel = pdf / pdf.sum()
|
||||
x_kernel = x_kernel.to(device=img.device, dtype=img.dtype)
|
||||
|
||||
kernel2d = torch.mm(x_kernel[:, None], x_kernel[None, :])
|
||||
kernel2d = kernel2d.expand(img.shape[-3], 1, kernel2d.shape[0], kernel2d.shape[1])
|
||||
|
||||
padding = [kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2]
|
||||
|
||||
img = torch.nn.functional.pad(img, padding, mode="reflect")
|
||||
img = torch.nn.functional.conv2d(img, kernel2d, groups=img.shape[-3])
|
||||
|
||||
return img
|
||||
|
||||
|
||||
# Saliency-adaptive Noise Fusion based on High-fidelity Person-centric Subject-to-Image Synthesis (Wang et al.)
|
||||
# https://github.com/CodeGoat24/Face-diffuser/blob/edff1a5178ac9984879d9f5e542c1d0f0059ca5f/facediffuser/pipeline.py#L535-L562
|
||||
def snf_guidance(
|
||||
t_guidance: torch.Tensor,
|
||||
s_guidance: torch.Tensor,
|
||||
t_kernel_size=3,
|
||||
t_sigma=1,
|
||||
s_kernel_size=3,
|
||||
s_sigma=1,
|
||||
):
|
||||
b, c, h, w = shape = t_guidance.shape
|
||||
|
||||
t_softmax, s_softmax = (
|
||||
torch.softmax(
|
||||
gaussian_blur_2d(torch.abs(t), ks, sig).reshape(b * c, h * w),
|
||||
dim=1,
|
||||
).reshape(*shape)
|
||||
for t, ks, sig in (
|
||||
(t_guidance, t_kernel_size, t_sigma),
|
||||
(s_guidance, s_kernel_size, s_sigma),
|
||||
)
|
||||
)
|
||||
guidance_stacked = torch.stack((t_guidance, s_guidance), dim=0)
|
||||
argeps = torch.argmax(
|
||||
torch.stack((t_softmax, s_softmax), dim=0), dim=0, keepdim=True
|
||||
)
|
||||
return torch.gather(guidance_stacked, dim=0, index=argeps).squeeze(0)
|
||||
|
||||
|
||||
class OCSLatentFormat:
|
||||
def __init__(self, device, latent_format):
|
||||
if latent_format.latent_rgb_factors is None:
|
||||
self.rgb_factors = None
|
||||
return
|
||||
self.rgb_factors = torch.tensor(
|
||||
latent_format.latent_rgb_factors, device=device, dtype=torch.float
|
||||
).t()
|
||||
# Thanks for Joviax for the help implementing this!
|
||||
self.rgb_factors_inv = torch.linalg.pinv(self.rgb_factors)
|
||||
bias = getattr(latent_format, "latent_rgb_factors_bias", None)
|
||||
self.rgb_factors_bias = (
|
||||
None
|
||||
if bias is None
|
||||
else torch.tensor(bias, device=device, dtype=torch.float)
|
||||
)
|
||||
|
||||
def latent_to_rgb(self, latent: torch.Tensor) -> torch.Tensor:
|
||||
# NCHW -> NHWC
|
||||
if self.latent_factors is None:
|
||||
raise ValueError("No RGB factors for latent type!")
|
||||
return torch.nn.functional.linear(
|
||||
latent.movedim(1, -1), self.rgb_factors, bias=self.rgb_factors_bias
|
||||
)
|
||||
|
||||
def rgb_to_latent(self, img: torch.Tensor) -> torch.Tensor:
|
||||
# NHWC
|
||||
if self.latent_factors is None:
|
||||
raise ValueError("No RGB factors for latent type!")
|
||||
if self.rgb_factors_bias is not None:
|
||||
img = img - self.rgb_factors_bias
|
||||
return torch.nn.functional.linear(img, self.rgb_factors_inv)
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
import torch
|
||||
|
||||
import comfy
|
||||
from comfy.k_diffusion.sampling import to_d
|
||||
|
||||
from . import filtering
|
||||
|
||||
from .utils import fallback
|
||||
from .latent import OCSLatentFormat
|
||||
|
||||
|
||||
class History:
|
||||
def __init__(self, size):
|
||||
self.history = []
|
||||
self.size = size
|
||||
|
||||
def __len__(self):
|
||||
return len(self.history)
|
||||
|
||||
def __getitem__(self, k):
|
||||
return self.history[k]
|
||||
|
||||
def push(self, val):
|
||||
if len(self.history) >= self.size:
|
||||
self.history = self.history[-(self.size - 1) :]
|
||||
self.history.append(val)
|
||||
|
||||
def reset(self):
|
||||
self.history = []
|
||||
|
||||
def clone(self):
|
||||
obj = self.__new__(self.__class__)
|
||||
obj.__init__(self.size)
|
||||
obj.history = self.history.copy()
|
||||
return obj
|
||||
|
||||
|
||||
class ModelResult:
|
||||
def __init__(
|
||||
self,
|
||||
call_idx,
|
||||
sigma,
|
||||
x,
|
||||
denoised,
|
||||
have_uncond=True,
|
||||
**kwargs,
|
||||
):
|
||||
self.call_idx = call_idx
|
||||
self.sigma = sigma
|
||||
self.x = x
|
||||
self.denoised = denoised
|
||||
self.have_uncond = have_uncond
|
||||
for k in ("denoised_uncond", "denoised_cond", "tangents", "jdenoised"):
|
||||
setattr(self, k, kwargs.pop(k, None))
|
||||
if len(kwargs) != 0:
|
||||
raise ValueError(f"Unexpected keyword arguments: {tuple(kwargs.keys())}")
|
||||
|
||||
def to_d(
|
||||
self,
|
||||
/,
|
||||
x=None,
|
||||
sigma=None,
|
||||
denoised=None,
|
||||
denoised_uncond=None,
|
||||
alt_cfgpp_scale=0,
|
||||
cfgpp=False,
|
||||
):
|
||||
x = fallback(x, self.x)
|
||||
sigma = fallback(sigma, self.sigma)
|
||||
denoised = fallback(denoised, self.denoised)
|
||||
denoised_uncond = fallback(denoised_uncond, self.denoised_uncond)
|
||||
if alt_cfgpp_scale != 0:
|
||||
x = x - denoised * alt_cfgpp_scale + denoised_uncond * alt_cfgpp_scale
|
||||
return to_d(x, sigma, denoised if not cfgpp else denoised_uncond)
|
||||
|
||||
def get_split_prediction(
|
||||
self,
|
||||
*,
|
||||
x=None,
|
||||
d=None,
|
||||
sigma=None,
|
||||
denoised=None,
|
||||
denoised_uncond=None,
|
||||
alt_cfgpp_scale=0,
|
||||
cfgpp=False,
|
||||
):
|
||||
denoised = fallback(denoised, self.denoised)
|
||||
denoised_uncond = fallback(denoised_uncond, self.denoised_uncond)
|
||||
x = fallback(x, self.x)
|
||||
sigma = fallback(sigma, self.sigma)
|
||||
if d is None:
|
||||
d = self.to_d(
|
||||
x=x,
|
||||
sigma=sigma,
|
||||
denoised=denoised,
|
||||
denoised_uncond=denoised_uncond,
|
||||
alt_cfgpp_scale=alt_cfgpp_scale,
|
||||
cfgpp=cfgpp,
|
||||
)
|
||||
denoised_pred = denoised if alt_cfgpp_scale == 0 else x - d * sigma
|
||||
return (denoised_pred, d)
|
||||
|
||||
@property
|
||||
def d(self):
|
||||
return self.to_d()
|
||||
|
||||
def clone(self, deep=False):
|
||||
obj = self.__new__(self.__class__)
|
||||
for k in (
|
||||
"denoised",
|
||||
"call_idx",
|
||||
"sigma",
|
||||
"x",
|
||||
"denoised_uncond",
|
||||
"denoised_cond",
|
||||
"tangents",
|
||||
"jdenoised",
|
||||
):
|
||||
val = getattr(self, k)
|
||||
if deep and isinstance(val, torch.Tensor):
|
||||
val = val.copy()
|
||||
setattr(obj, k, val)
|
||||
return obj
|
||||
|
||||
def get_error(self, other, *, override=None, alt_cfgpp_scale=0, cfgpp=False):
|
||||
slf = fallback(override, self)
|
||||
first, second = (other, slf) if other.sigma > slf.sigma else (slf, other)
|
||||
if first.sigma == second.sigma:
|
||||
return 0.0
|
||||
d = first.to_d(alt_cfgpp_scale=alt_cfgpp_scale, cfgpp=cfgpp)
|
||||
d_pred = second.to_d(
|
||||
x=first.x + d * (second.sigma - first.sigma),
|
||||
alt_cfgpp_scale=alt_cfgpp_scale,
|
||||
cfgpp=cfgpp,
|
||||
)
|
||||
return torch.linalg.norm(d_pred.sub_(d)).div_(torch.linalg.norm(d)).item()
|
||||
|
||||
|
||||
class OCSModel:
|
||||
def __init__(
|
||||
self,
|
||||
model,
|
||||
x: torch.Tensor,
|
||||
s_in: torch.Tensor,
|
||||
extra_args: dict,
|
||||
*,
|
||||
cache: dict | None = None,
|
||||
filter: dict | None = None,
|
||||
cfg1_uncond_optimization: bool = False,
|
||||
cfg_scale_override: int | float | None = None,
|
||||
) -> None:
|
||||
filtargs = fallback(filter, {}).copy()
|
||||
self.filters = {}
|
||||
for key in (
|
||||
"input",
|
||||
"denoised",
|
||||
"jdenoised",
|
||||
"cond",
|
||||
"uncond",
|
||||
"postcfg",
|
||||
"precfg",
|
||||
):
|
||||
filt = filtargs.pop(key, None)
|
||||
if filt is None:
|
||||
continue
|
||||
self.filters[key] = filtering.make_filter(filt)
|
||||
self.model = model
|
||||
self.s_in = s_in
|
||||
self.extra_args = extra_args
|
||||
self.cfg1_uncond_optimization = cfg1_uncond_optimization
|
||||
self.cfg_scale_override = cfg_scale_override
|
||||
self.is_rectified_flow = isinstance(
|
||||
model.inner_model.inner_model.model_sampling, comfy.model_sampling.CONST
|
||||
)
|
||||
self.latent_format = OCSLatentFormat(
|
||||
x.device, model.inner_model.inner_model.latent_format
|
||||
)
|
||||
|
||||
def maybe_filter(
|
||||
self, name: str, latent: torch.Tensor, *args: list, **kwargs: dict
|
||||
) -> torch.Tensor:
|
||||
filt = self.filters.get(name)
|
||||
if filt is None:
|
||||
return latent
|
||||
return filt.apply(latent, *args, **kwargs)
|
||||
|
||||
def filter_result(
|
||||
self, result: ModelResult, *args: list, **kwargs: dict
|
||||
) -> ModelResult:
|
||||
if not self.filters:
|
||||
return result
|
||||
result = result.clone()
|
||||
for key in ("denoised", "cond", "uncond", "jdenoised"):
|
||||
filt = self.filters.get(key)
|
||||
if filt is None:
|
||||
continue
|
||||
attk = f"denoised_{key}" if key in {"cond", "uncond"} else key
|
||||
inpval = getattr(result, attk, None)
|
||||
if inpval is None:
|
||||
continue
|
||||
setattr(result, attk, filt.apply(inpval, *args, **kwargs))
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _fr_add_mr(fr: filtering.FilterRefs, mr: ModelResult) -> filtering.FilterRefs:
|
||||
frmr = filtering.FilterRefs.from_mr(mr)
|
||||
fr.kvs |= {f"{k}_curr": v for k, v in frmr.kvs.items()}
|
||||
return fr
|
||||
|
||||
def call_model(
|
||||
self, x: torch.Tensor, sigma: torch.Tensor, **kwargs: dict
|
||||
) -> torch.Tensor:
|
||||
return self.model(x, sigma * self.s_in, **self.extra_args | kwargs)
|
||||
|
||||
@property
|
||||
def model_sampling(self):
|
||||
return self.model.inner_model.inner_model.model_sampling
|
||||
|
||||
@property
|
||||
def inner_cfg_scale(self) -> None | int | float:
|
||||
maybe_cfg_scale = getattr(self.model.inner_model, "cfg", None)
|
||||
return maybe_cfg_scale if isinstance(maybe_cfg_scale, (int, float)) else None
|
||||
|
||||
def set_inner_cfg_scale(self, scale: None | int | float) -> None | int | float:
|
||||
eff_scale = self.cfg_scale_override
|
||||
if scale is not None:
|
||||
eff_scale = None if scale < 0 else scale
|
||||
if eff_scale is None or eff_scale < 0:
|
||||
return None
|
||||
curr_cfg_scale = self.inner_cfg_scale
|
||||
if curr_cfg_scale is None:
|
||||
return None
|
||||
self.model.inner_model.cfg = eff_scale
|
||||
return curr_cfg_scale
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
x: torch.Tensor,
|
||||
sigma: torch.Tensor,
|
||||
*,
|
||||
call_index: int = 0,
|
||||
ss,
|
||||
s_in=None,
|
||||
tangents=None,
|
||||
require_uncond: bool = False,
|
||||
cfg_scale_override: None | int = None,
|
||||
**kwargs,
|
||||
) -> ModelResult:
|
||||
filter_refs = ss.refs | filtering.FilterRefs({
|
||||
"model_call": call_index,
|
||||
"orig_x": x,
|
||||
})
|
||||
|
||||
comfy.model_management.throw_exception_if_processing_interrupted()
|
||||
|
||||
model_options = self.extra_args.get("model_options", {}).copy()
|
||||
denoised_cond = denoised_uncond = None
|
||||
have_uncond = True
|
||||
|
||||
def postcfg(args):
|
||||
nonlocal denoised_cond, denoised_uncond, have_uncond
|
||||
denoised_uncond = args["uncond_denoised"]
|
||||
denoised_cond = args["cond_denoised"]
|
||||
result = args["denoised"]
|
||||
if "postcfg" in self.filters:
|
||||
result = self.maybe_filter(
|
||||
"postcfg",
|
||||
result,
|
||||
refs=filter_refs
|
||||
| filtering.FilterRefs({
|
||||
"postcfg_input": args["input"],
|
||||
"postcfg_sigma": args["sigma"],
|
||||
"postcfg_denoised_cond": denoised_cond,
|
||||
"postcfg_denoised_uncond": denoised_uncond,
|
||||
}),
|
||||
)
|
||||
if denoised_uncond is None:
|
||||
have_uncond = False
|
||||
denoised_uncond = denoised_cond
|
||||
return result
|
||||
|
||||
def precfg(args):
|
||||
conds_out = args["conds_out"]
|
||||
precfg_refs = (
|
||||
filter_refs
|
||||
| filtering.FilterRefs({
|
||||
"precfg_input": args["input"],
|
||||
"precfg_sigma": args["sigma"],
|
||||
"precfg_cond_scale": args["cond_scale"],
|
||||
})
|
||||
| filtering.FilterRefs({
|
||||
f"precfg_cond_{idx}": cond for idx, cond in enumerate(conds_out)
|
||||
})
|
||||
)
|
||||
return [
|
||||
self.maybe_filter(
|
||||
"precfg",
|
||||
curr_cond,
|
||||
refs=precfg_refs | filtering.FilterRefs({"cond_idx": cond_idx}),
|
||||
)
|
||||
for cond_idx, curr_cond in enumerate(conds_out)
|
||||
]
|
||||
|
||||
orig_cfg_scale = self.set_inner_cfg_scale(cfg_scale_override)
|
||||
|
||||
model_options = comfy.model_patcher.set_model_options_post_cfg_function(
|
||||
model_options,
|
||||
postcfg,
|
||||
disable_cfg1_optimization=require_uncond
|
||||
or not self.cfg1_uncond_optimization,
|
||||
)
|
||||
if "precfg" in self.filters:
|
||||
model_options = comfy.model_patcher.set_model_options_pre_cfg_function(
|
||||
model_options,
|
||||
precfg,
|
||||
)
|
||||
|
||||
extra_args = self.extra_args | {"model_options": model_options}
|
||||
s_in = fallback(s_in, self.s_in)
|
||||
if s_in.shape[0] != x.shape[0]:
|
||||
s_in = self.s_in = x.new_ones((x.shape[0],))
|
||||
x = self.maybe_filter("input", x, refs=filter_refs)
|
||||
|
||||
def call_model(x, sigma, **kwargs):
|
||||
return self.model(x, sigma * s_in, **extra_args | kwargs)
|
||||
|
||||
if tangents is None:
|
||||
denoised = call_model(x, sigma, **kwargs)
|
||||
self.set_inner_cfg_scale(orig_cfg_scale)
|
||||
mr = ModelResult(
|
||||
call_index,
|
||||
sigma,
|
||||
x,
|
||||
denoised,
|
||||
have_uncond=have_uncond,
|
||||
denoised_uncond=denoised_uncond,
|
||||
denoised_cond=denoised_cond,
|
||||
)
|
||||
self._fr_add_mr(filter_refs, mr)
|
||||
mr = self.filter_result(mr, default_ref=x, refs=filter_refs)
|
||||
return mr
|
||||
denoised, denoised_prime = torch.func.jvp(call_model, (x, sigma), tangents)
|
||||
self.set_inner_cfg_scale(orig_cfg_scale)
|
||||
mr = ModelResult(
|
||||
call_index,
|
||||
sigma,
|
||||
x,
|
||||
denoised,
|
||||
have_uncond=have_uncond,
|
||||
jdenoised=denoised_prime,
|
||||
denoised_uncond=denoised_uncond,
|
||||
denoised_cond=denoised_cond,
|
||||
)
|
||||
self._fr_add_mr(filter_refs, mr)
|
||||
mr = self.filter_result(mr, default_ref=x, refs=filter_refs)
|
||||
return mr
|
||||
+722
-78
@@ -1,14 +1,81 @@
|
||||
from .sampling import composable_sampler, STEP_SAMPLERS
|
||||
from .substep_sampling import StepSamplerChain
|
||||
from .substep_merging import MERGE_SUBSTEPS_CLASSES
|
||||
|
||||
import comfy
|
||||
import yaml
|
||||
|
||||
import torch
|
||||
|
||||
class ComposableSampler:
|
||||
from tqdm import tqdm
|
||||
|
||||
from .external import MODULES, IntegratedNode
|
||||
from .restart import Restart
|
||||
from .sampling import composable_sampler
|
||||
from .step_samplers import STEP_SAMPLERS
|
||||
from .substep_merging import MERGE_SUBSTEPS_CLASSES
|
||||
from .substep_sampling import ParamGroup, StepSamplerChain, StepSamplerGroups
|
||||
from .filtering import make_filter
|
||||
|
||||
try:
|
||||
from comfy_execution import validation as comfy_validation
|
||||
|
||||
if not hasattr(comfy_validation, "validate_node_input"):
|
||||
raise NotImplementedError
|
||||
HAVE_COMFY_UNION_TYPE = comfy_validation.validate_node_input("B", "A,B")
|
||||
except (ImportError, NotImplementedError):
|
||||
HAVE_COMFY_UNION_TYPE = False
|
||||
except Exception as exc:
|
||||
HAVE_COMFY_UNION_TYPE = False
|
||||
tqdm.write(
|
||||
f"** OCS: Warning, caught unexpected exception trying to detect ComfyUI union type support. Disabling. Exception: {exc}"
|
||||
)
|
||||
|
||||
PARAM_INPUT_TYPES = frozenset((
|
||||
"IMAGE",
|
||||
"OCS_NOISE",
|
||||
"SAMPLER",
|
||||
"SIGMAS",
|
||||
"SONAR_CUSTOM_NOISE",
|
||||
"UPSCALE_MODEL",
|
||||
"VAE",
|
||||
))
|
||||
|
||||
NOISE_INPUT_TYPES = frozenset(("SONAR_CUSTOM_NOISE", "OCS_NOISE"))
|
||||
|
||||
if not HAVE_COMFY_UNION_TYPE:
|
||||
|
||||
class Wildcard(str):
|
||||
__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)
|
||||
WILDCARD_PARAM = Wildcard("*", whitelist=PARAM_INPUT_TYPES)
|
||||
else:
|
||||
WILDCARD_NOISE = ",".join(NOISE_INPUT_TYPES)
|
||||
WILDCARD_PARAM = ",".join(PARAM_INPUT_TYPES)
|
||||
|
||||
PARAM_INPUT_TYPES_HINT = (
|
||||
f"The following input types are supported: {', '.join(PARAM_INPUT_TYPES)}"
|
||||
)
|
||||
NOISE_INPUT_TYPES_HINT = (
|
||||
f"The following input types are supported: {', '.join(NOISE_INPUT_TYPES)}"
|
||||
)
|
||||
|
||||
DEFAULT_YAML_PARAMS = "# YAML/JSON parameters\n"
|
||||
|
||||
|
||||
class SamplerNode(metaclass=IntegratedNode):
|
||||
RETURN_TYPES = ("SAMPLER",)
|
||||
CATEGORY = "sampling/custom_sampling/samplers"
|
||||
CATEGORY = "sampling/custom_sampling/OCS"
|
||||
DESCRIPTION = "Overly Complicated Sampling main sampler node. Can be connected to a SamplerCustom or other sampler node that supports a SAMPLER input."
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"SAMPLER that can be connected to a SamplerCustom or other sampler node that supports a SAMPLER input.",
|
||||
)
|
||||
|
||||
FUNCTION = "go"
|
||||
|
||||
@@ -16,34 +83,31 @@ class ComposableSampler:
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"s_noise": (
|
||||
"FLOAT",
|
||||
"groups": (
|
||||
"OCS_GROUPS",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": -100.0,
|
||||
"max": 100.0,
|
||||
"step": 0.01,
|
||||
"round": False,
|
||||
"tooltip": "Connect OCS substep groups here which are output from the OCS Group node.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"eta": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": -100.0,
|
||||
"max": 100.0,
|
||||
"step": 0.01,
|
||||
"round": False,
|
||||
},
|
||||
),
|
||||
"merge_method": (tuple(MERGE_SUBSTEPS_CLASSES.keys()),),
|
||||
"step_sampler_chain": ("STEP_SAMPLER_CHAIN",),
|
||||
},
|
||||
"optional": {
|
||||
"merge_sampler_opt": ("STEP_SAMPLER_CHAIN",),
|
||||
"params_opt": (
|
||||
"OCS_PARAMS",
|
||||
{
|
||||
"tooltip": "Optionally connect parameters like custom noise here. Output from the OCS Param or OCS MultiParam nodes.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"parameters": (
|
||||
"STRING",
|
||||
{"default": "", "multiline": True, "dynamicPrompts": False},
|
||||
{
|
||||
"default": "",
|
||||
"placeholder": DEFAULT_YAML_PARAMS,
|
||||
"multiline": True,
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "The text parameter block allows setting custom parameters using YAML (recommended) or JSON. Optional, may be left blank.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
@@ -51,41 +115,36 @@ class ComposableSampler:
|
||||
def go(
|
||||
self,
|
||||
*,
|
||||
s_noise,
|
||||
eta,
|
||||
merge_method,
|
||||
step_sampler_chain,
|
||||
merge_sampler_opt=None,
|
||||
groups,
|
||||
params_opt=None,
|
||||
parameters="",
|
||||
):
|
||||
if merge_sampler_opt is not None:
|
||||
merge_sampler = merge_sampler_opt.items[0]
|
||||
else:
|
||||
merge_sampler = ComposableStepSampler().go(step_method="euler")[0].items[0]
|
||||
options = {
|
||||
"s_noise": s_noise,
|
||||
"eta": eta,
|
||||
"merge_method": merge_method,
|
||||
"merge_sampler": merge_sampler,
|
||||
}
|
||||
MODULES.initialize()
|
||||
options = {}
|
||||
parameters = parameters.strip()
|
||||
if parameters:
|
||||
extra_params = yaml.safe_load(parameters)
|
||||
if not isinstance(extra_params, dict):
|
||||
raise ValueError("Parameters must be a JSON or YAML object")
|
||||
options |= extra_params
|
||||
options["chain"] = step_sampler_chain.clone()
|
||||
if extra_params is not None:
|
||||
if not isinstance(extra_params, dict):
|
||||
raise ValueError("Parameters must be a JSON or YAML object")
|
||||
options |= extra_params
|
||||
if params_opt is not None:
|
||||
options |= params_opt.items
|
||||
options["_groups"] = groups.clone()
|
||||
return (
|
||||
comfy.samplers.KSAMPLER(
|
||||
composable_sampler,
|
||||
{"composable_sampler_options": options},
|
||||
composable_sampler, {"overly_complicated_options": options}
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
class ComposableStepSampler:
|
||||
RETURN_TYPES = ("STEP_SAMPLER_CHAIN",)
|
||||
CATEGORY = "sampling/custom_sampling/samplers"
|
||||
class GroupNode(metaclass=IntegratedNode):
|
||||
RETURN_TYPES = ("OCS_GROUPS",)
|
||||
CATEGORY = "sampling/custom_sampling/OCS"
|
||||
DESCRIPTION = "Over Complicated Sampling group definition node."
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"This output can be connect to another OCS Group node or an OCS Sampler node.",
|
||||
)
|
||||
|
||||
FUNCTION = "go"
|
||||
|
||||
@@ -93,52 +152,637 @@ class ComposableStepSampler:
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"s_noise": (
|
||||
"FLOAT",
|
||||
"merge_method": (
|
||||
tuple(MERGE_SUBSTEPS_CLASSES.keys()),
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": -100.0,
|
||||
"max": 100.0,
|
||||
"step": 0.01,
|
||||
"round": False,
|
||||
"tooltip": "The merge method determines how multiple substeps are combined together during sampling.",
|
||||
},
|
||||
),
|
||||
"eta": (
|
||||
"FLOAT",
|
||||
"time_mode": (
|
||||
("step", "step_pct", "sigma"),
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": -100.0,
|
||||
"max": 100.0,
|
||||
"step": 0.01,
|
||||
"round": False,
|
||||
"tooltip": "The time mode controls how the time_start and time_end parameters are interpreted. The default of step is generally easiest to use.",
|
||||
},
|
||||
),
|
||||
"time_start": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0.0,
|
||||
"step": 0.1,
|
||||
"round'": False,
|
||||
"tooltip": "The start time this group will be active (inclusive).",
|
||||
},
|
||||
),
|
||||
"time_end": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 999,
|
||||
"min": 0.0,
|
||||
"step": 0.1,
|
||||
"round'": False,
|
||||
"tooltip": "The group will become inactive when the current time is GREATER than the specified end time.",
|
||||
},
|
||||
),
|
||||
"substeps": (
|
||||
"OCS_SUBSTEPS",
|
||||
{
|
||||
"tooltip": "Connect output from an OCS Substeps node here.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"substeps": ("INT", {"default": 1, "min": 1, "max": 1000}),
|
||||
"step_method": (tuple(STEP_SAMPLERS.keys()),),
|
||||
},
|
||||
"optional": {
|
||||
"step_sampler_opt": ("STEP_SAMPLER_CHAIN",),
|
||||
"custom_noise_opt": ("SONAR_CUSTOM_NOISE",),
|
||||
"groups_opt": (
|
||||
"OCS_GROUPS",
|
||||
{
|
||||
"tooltip": "You may optionally connect the output from another OCS Group node here. Only one group per step is used, matching (based on time or other constraints) starts with the OCS Group node furthest from the OCS Sampler.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"params_opt": (
|
||||
"OCS_PARAMS",
|
||||
{
|
||||
"tooltip": "Optionally connect parameters like custom noise here. Output from the OCS Param or OCS MultiParam nodes.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"parameters": (
|
||||
"STRING",
|
||||
{"default": "", "multiline": True, "dynamicPrompts": False},
|
||||
{
|
||||
"default": "",
|
||||
"placeholder": DEFAULT_YAML_PARAMS,
|
||||
"multiline": True,
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "The text parameter block allows setting custom parameters using YAML (recommended) or JSON. Optional, may be left blank.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
def go(self, *, parameters="", step_sampler_opt=None, **kwargs):
|
||||
if step_sampler_opt is not None:
|
||||
chain = step_sampler_opt.clone()
|
||||
def go(
|
||||
self,
|
||||
*,
|
||||
merge_method,
|
||||
time_mode,
|
||||
time_start,
|
||||
time_end,
|
||||
substeps,
|
||||
groups_opt=None,
|
||||
params_opt=None,
|
||||
parameters="",
|
||||
):
|
||||
MODULES.initialize()
|
||||
group = StepSamplerGroups() if groups_opt is None else groups_opt.clone()
|
||||
chain = substeps.clone()
|
||||
chain.merge_method = merge_method
|
||||
chain.time_mode = time_mode
|
||||
chain.time_start, chain.time_end = time_start, time_end
|
||||
options = {}
|
||||
parameters = parameters.strip()
|
||||
if parameters:
|
||||
extra_params = yaml.safe_load(parameters)
|
||||
if extra_params is not None:
|
||||
if not isinstance(extra_params, dict):
|
||||
raise ValueError("Parameters must be a JSON or YAML object")
|
||||
options |= extra_params
|
||||
if params_opt is not None:
|
||||
options |= params_opt.items
|
||||
chain.options |= options
|
||||
group.append(chain)
|
||||
return (group,)
|
||||
|
||||
|
||||
class SubstepsNode(metaclass=IntegratedNode):
|
||||
RETURN_TYPES = ("OCS_SUBSTEPS",)
|
||||
CATEGORY = "sampling/custom_sampling/OCS"
|
||||
DESCRIPTION = "Overly Complicated Sampling substeps definition node. Used to define a sampler type and other sampler-specific parameters."
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"This output can be connected to another OCS Substeps node or an OCS Group node.",
|
||||
)
|
||||
|
||||
FUNCTION = "go"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"substeps": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1,
|
||||
"min": 1,
|
||||
"max": 1000,
|
||||
"tooltip": "Number of substeps to use for each step, in other words (depending on the OCS Group merge strategy) it may split a step into multiple smaller steps.",
|
||||
},
|
||||
),
|
||||
"step_method": (
|
||||
tuple(STEP_SAMPLERS.keys()),
|
||||
{
|
||||
"tooltip": "In other words, the sampler.",
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"substeps_opt": (
|
||||
"OCS_SUBSTEPS",
|
||||
{
|
||||
"tooltip": "Optionally connect another OCS Substeps node here. Substeps will run in order, starting from the OCS Substeps node FURTHEST from the OCS Group node.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"params_opt": (
|
||||
"OCS_PARAMS",
|
||||
{
|
||||
"tooltip": "Optionally connect parameters like custom noise here. Output from the OCS Param or OCS MultiParam nodes.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"parameters": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "",
|
||||
"placeholder": f"{DEFAULT_YAML_PARAMS}s_noise: 1.0\neta: 1.0\n",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "The text parameter block allows setting custom parameters using YAML (recommended) or JSON. Optional, may be left blank.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
def go(
|
||||
self,
|
||||
*,
|
||||
parameters="",
|
||||
substeps_opt=None,
|
||||
params_opt=None,
|
||||
**kwargs,
|
||||
):
|
||||
MODULES.initialize()
|
||||
if substeps_opt is not None:
|
||||
chain = substeps_opt.clone()
|
||||
else:
|
||||
chain = StepSamplerChain()
|
||||
parameters = parameters.strip()
|
||||
if parameters:
|
||||
extra_params = yaml.safe_load(parameters)
|
||||
if not isinstance(extra_params, dict):
|
||||
raise ValueError("Parameters must be a JSON or YAML object")
|
||||
kwargs |= extra_params
|
||||
chain.items.append(kwargs)
|
||||
if extra_params is not None:
|
||||
if not isinstance(extra_params, dict):
|
||||
raise ValueError("Parameters must be a JSON or YAML object")
|
||||
kwargs |= extra_params
|
||||
if params_opt is not None:
|
||||
kwargs |= params_opt.items
|
||||
chain.append(kwargs)
|
||||
return (chain,)
|
||||
|
||||
|
||||
__all__ = ("ComposableStepSampler", "ComposableSampler")
|
||||
class ParamNode(metaclass=IntegratedNode):
|
||||
RETURN_TYPES = ("OCS_PARAMS",)
|
||||
CATEGORY = "sampling/custom_sampling/OCS"
|
||||
DESCRIPTION = "Overly Complicated Sampling parameter definition node. Used to set parameters like custom noise types that require an input."
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"Can be connected to another OCS Param or OCS MultiParam node or any other OCS node that takes OCS_PARAMS as an input.",
|
||||
)
|
||||
|
||||
FUNCTION = "go"
|
||||
|
||||
OCS_PARAM_INPUT_TYPES = {
|
||||
"custom_noise": lambda v: hasattr(v, "make_noise_sampler"),
|
||||
"merge_sampler": lambda v: isinstance(v, StepSamplerChain),
|
||||
"restart_custom_noise": lambda v: hasattr(v, "make_noise_sampler"),
|
||||
"sampler": lambda _v: True,
|
||||
"vae": lambda _v: True,
|
||||
"upscale_model": lambda _v: True,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"key": (
|
||||
tuple(cls.OCS_PARAM_INPUT_TYPES.keys()),
|
||||
{
|
||||
"tooltip": "Used to set the type of custom parameter.",
|
||||
},
|
||||
),
|
||||
"value": (
|
||||
WILDCARD_PARAM,
|
||||
{
|
||||
"tooltip": f"Connect the type of value expected by the key. Allows connecting output from any type of node HOWEVER if it is the wrong type expected by the key you will get an error when you run the workflow.\n{PARAM_INPUT_TYPES_HINT}",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"params_opt": (
|
||||
"OCS_PARAMS",
|
||||
{
|
||||
"tooltip": "You may optionally connect the output from other OCS Param or OCS MultiParam nodes here to set multiple parameters.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"parameters": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "",
|
||||
"placeholder": "# Additional YAML or JSON parameters",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": False,
|
||||
"defaultInput": True,
|
||||
"tooltip": "The text parameter block allows setting custom parameters using YAML (recommended) or JSON. Optional, may be left blank.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def get_renamed_key(cls, key, params):
|
||||
rename = params.get("rename")
|
||||
if rename is None:
|
||||
return key
|
||||
if not isinstance(rename, str):
|
||||
raise ValueError("Param rename key must be a string if set")
|
||||
rename = rename.strip()
|
||||
if not rename or not all(c == "_" or c.isalnum() for c in rename):
|
||||
raise ValueError(
|
||||
"Param rename keys must consist of one or more alphanumeric or underscore characters"
|
||||
)
|
||||
return f"{key}_{rename}"
|
||||
|
||||
def go(self, *, key, value, params_opt=None, parameters=""):
|
||||
MODULES.initialize()
|
||||
if not self.OCS_PARAM_INPUT_TYPES[key](value):
|
||||
raise ValueError(f"CSamplerParam: Bad value type for key {key}")
|
||||
if parameters:
|
||||
extra_params = yaml.safe_load(parameters)
|
||||
if extra_params is not None:
|
||||
if not isinstance(extra_params, dict):
|
||||
raise ValueError("Parameters must be a JSON or YAML object")
|
||||
key = self.get_renamed_key(key, extra_params)
|
||||
else:
|
||||
extra_params = None
|
||||
params = ParamGroup(items={}) if params_opt is None else params_opt.clone()
|
||||
params[key] = value
|
||||
if extra_params is not None:
|
||||
params[f"{key}.params"] = extra_params
|
||||
return (params,)
|
||||
|
||||
|
||||
class MultiParamNode(ParamNode, metaclass=IntegratedNode):
|
||||
RETURN_TYPES = ("OCS_PARAMS",)
|
||||
CATEGORY = "sampling/custom_sampling/OCS"
|
||||
DESCRIPTION = "Overly Complicated Sampling parameter definition node. Used to set parameters like custom noise types that require an input. Like the OCS Param node but allows setting multiple parameters at the same time."
|
||||
OUTPUT_TYPES = (
|
||||
"Can be connected to another OCS Param or OCS MultiParam node or any other OCS node that takes OCS_PARAMS as an input.",
|
||||
)
|
||||
|
||||
FUNCTION = "go"
|
||||
|
||||
PARAM_COUNT = 5
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
param_keys = (
|
||||
("", *ParamNode.OCS_PARAM_INPUT_TYPES.keys()),
|
||||
{
|
||||
"tooltip": "Used to set the type of custom parameter.",
|
||||
},
|
||||
)
|
||||
return {
|
||||
"required": {
|
||||
f"key_{idx}": param_keys for idx in range(1, cls.PARAM_COUNT + 1)
|
||||
},
|
||||
"optional": {
|
||||
"params_opt": (
|
||||
"OCS_PARAMS",
|
||||
{
|
||||
"tooltip": "You may optionally connect the output from other OCS MultiParam or OCS Param nodes here to set multiple parameters.",
|
||||
"forceInput": True,
|
||||
},
|
||||
),
|
||||
"parameters": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "",
|
||||
"placeholder": """\
|
||||
# Additional YAML or JSON parameters
|
||||
# Should be an object with key corresponding to the index of the input
|
||||
""",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": False,
|
||||
"defaultInput": True,
|
||||
"tooltip": "The text parameter block allows setting custom parameters using YAML (recommended) or JSON. Optional, may be left blank.",
|
||||
},
|
||||
),
|
||||
}
|
||||
| {
|
||||
f"value_opt_{idx}": (
|
||||
WILDCARD_PARAM,
|
||||
{
|
||||
"tooltip": f"Connect the type of value expected by the corresponding key. Allows connecting output from any type of node HOWEVER if it is the wrong type expected by the corresponding key you will get an error when you run the workflow.\n{PARAM_INPUT_TYPES_HINT}",
|
||||
"forceInput": True,
|
||||
},
|
||||
)
|
||||
for idx in range(1, cls.PARAM_COUNT + 1)
|
||||
},
|
||||
}
|
||||
|
||||
def go(self, *, params_opt=None, parameters="", **kwargs):
|
||||
MODULES.initialize()
|
||||
params = ParamGroup(items={}) if params_opt is None else params_opt.clone()
|
||||
if parameters:
|
||||
extra_params = yaml.safe_load(parameters)
|
||||
if extra_params is not None:
|
||||
if not isinstance(extra_params, dict):
|
||||
raise ValueError("Parameters must be a JSON or YAML object")
|
||||
else:
|
||||
extra_params = {}
|
||||
else:
|
||||
extra_params = {}
|
||||
for idx in range(1, self.PARAM_COUNT + 1):
|
||||
key, value = kwargs.get(f"key_{idx}"), kwargs.get(f"value_opt_{idx}")
|
||||
if not key or value is None:
|
||||
continue
|
||||
if not self.OCS_PARAM_INPUT_TYPES[key](value):
|
||||
raise ValueError(f"CSamplerParamGroup: Bad value type for key {key}")
|
||||
extra = extra_params.get(str(idx))
|
||||
key = self.get_renamed_key(key, extra)
|
||||
params[key] = value
|
||||
if extra is not None:
|
||||
params[f"{key}.params"] = extra
|
||||
|
||||
return (params,)
|
||||
|
||||
|
||||
class SimpleRestartSchedule(metaclass=IntegratedNode):
|
||||
RETURN_TYPES = ("SIGMAS",)
|
||||
CATEGORY = "sampling/custom_sampling/OCS"
|
||||
DESCRIPTION = "Overly Complicated Sampling simple Restart schedule node. Allows generating a Restart sampling schedule based on a text definition."
|
||||
OUTPUT_TYPES = (
|
||||
"Can be connected to an OCS Sampler or RestartSampler node. Do not connect directly to a sampler that doesn't have built-in support for Restart schedules.",
|
||||
)
|
||||
|
||||
FUNCTION = "go"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"sigmas": (
|
||||
"SIGMAS",
|
||||
{
|
||||
"tooltip": "Connect the output from another scheduler node (i.e. BasicScheduler) here.",
|
||||
},
|
||||
),
|
||||
"start_step": (
|
||||
"INT",
|
||||
{
|
||||
"min": 0,
|
||||
"default": 0,
|
||||
"tooltip": "Step the restart schedule definition starts applying. Zero-based.",
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"schedule": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "",
|
||||
"placeholder": """\
|
||||
# YAML or JSON restart schedule. Example:
|
||||
# Every 5 steps, jump back 3 steps
|
||||
- [5, -3]
|
||||
# Jump to schedule item 0
|
||||
- 0
|
||||
""",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Define a schedule here using YAML (recommended) or JSON.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
def go(self, *, sigmas, start_step=0, schedule=""):
|
||||
MODULES.initialize()
|
||||
if schedule:
|
||||
parsed_schedule = yaml.safe_load(schedule)
|
||||
if parsed_schedule is not None:
|
||||
if not isinstance(parsed_schedule, (list, tuple)):
|
||||
raise ValueError("Schedule must be a JSON or YAML list")
|
||||
else:
|
||||
parsed_schedule = []
|
||||
else:
|
||||
parsed_schedule = []
|
||||
return (Restart.simple_schedule(sigmas, start_step, parsed_schedule),)
|
||||
|
||||
|
||||
class ModelSetMaxSigmaNode(metaclass=IntegratedNode):
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
CATEGORY = "hacks"
|
||||
DESCRIPTION = "Allows forcing a model's maximum and minumum sigmas to a specified value. You generally do NOT want to connect this to a sampler node. Connect it to a scheduler node (i.e. BasicScheduler) instead."
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"Patched model. Can be connected to a scheduler node (i.e. BasicScheduler). Generally NOT recommended to connect to an actual sampler, the main use case is only for generating sigmas.",
|
||||
)
|
||||
|
||||
FUNCTION = "go"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"model": (
|
||||
"MODEL",
|
||||
{
|
||||
"tooltip": "Model to patch with the min/max sigmas.",
|
||||
},
|
||||
),
|
||||
"mode": (
|
||||
("recalculate", "simple_multiply"),
|
||||
{
|
||||
"tooltip": "Mode to use when setting sigmas in the patched model. Recalculate should generally be more accurate.",
|
||||
},
|
||||
),
|
||||
"sigma_max": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": -1.0,
|
||||
"min": -10000.0,
|
||||
"max": 10000.0,
|
||||
"step": 0.01,
|
||||
"round": False,
|
||||
"tooltip": "You can set the maximum sigma here. If you use a positive value, it will be interpreted as the absolute value for the max sigma. If you use a negative value it will be interpreted as a percentage of the current value (where 1.0 signifies 100%). Schedules generated with the patched model should start from sigma_max (or close to it).",
|
||||
},
|
||||
),
|
||||
"fake_sigma_min": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.0,
|
||||
"min": 0.0,
|
||||
"max": 1000.0,
|
||||
"step": 0.01,
|
||||
"round": False,
|
||||
"tooltip": "You can set the minimum sigma here. Disabled if set to 0. If you use a positive value, it will be interpreted as the absolute value for the max sigma. If you use a negative value it will be interpreted as a percentage of the current value (where 1.0 signifies 100%). Schedules generated with the patched model should end with [sigma_min, 0]. NOTE: May not work with some schedulers. I recommend leaving this at 0 unless you know you need it (and even then it may not work).",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
def go(self, model, mode="recalculate", sigma_max=-1.0, fake_sigma_min=0.0):
|
||||
MODULES.initialize()
|
||||
if sigma_max == 0:
|
||||
raise ValueError("ModelSetMaxSigma: Invalid sigma_max value")
|
||||
if mode not in ("recalculate", "simple_multiply"):
|
||||
raise ValueError("ModelSetMaxSigma: Invalid mode value")
|
||||
orig_ms = model.get_model_object("model_sampling")
|
||||
model = model.clone()
|
||||
orig_max_sigma, orig_min_sigma = (
|
||||
orig_ms.sigma_max.item(),
|
||||
orig_ms.sigma_min.item(),
|
||||
)
|
||||
max_multiplier = abs(sigma_max) if sigma_max < 0 else sigma_max / orig_max_sigma
|
||||
if max_multiplier == 1:
|
||||
return (model,)
|
||||
mcfg = model.get_model_object("model_config")
|
||||
orig_sigmas = orig_ms.sigmas
|
||||
fake_sigma_min = orig_sigmas.new_full((1,), fake_sigma_min)
|
||||
|
||||
class NewModelSampling(orig_ms.__class__):
|
||||
if fake_sigma_min != 0:
|
||||
|
||||
@property
|
||||
def sigma_min(self):
|
||||
return fake_sigma_min
|
||||
|
||||
ms = NewModelSampling(mcfg)
|
||||
if mode == "simple_multiply":
|
||||
ms.set_sigmas(orig_sigmas * max_multiplier)
|
||||
else:
|
||||
ss = getattr(mcfg, "sampling_setting", None) or {}
|
||||
if ss.get("beta_schedule", "linear") != "linear":
|
||||
raise NotImplementedError(
|
||||
"ModelSetMaxSigma: Can only handle linear beta schedules in reschedule mode"
|
||||
)
|
||||
ms.set_sigmas((orig_sigmas**2 * max_multiplier**2) ** 0.5)
|
||||
new_max_sigma, new_min_sigma = ms.sigma_max.item(), ms.sigma_min.item()
|
||||
if new_min_sigma >= new_max_sigma:
|
||||
raise ValueError(
|
||||
"ModelSetMaxSigma: Invalid fake_min_sigma value, result max <= min"
|
||||
)
|
||||
model.add_object_patch("model_sampling", ms)
|
||||
tqdm.write(
|
||||
f"OCS: ModelSetMaxSigma: Set model sigmas({mode}): old_max={orig_max_sigma:.04}, old_min={orig_min_sigma:.03}, new_max={new_max_sigma:.04}, new_min={new_min_sigma:.03}"
|
||||
)
|
||||
return (model,)
|
||||
|
||||
|
||||
class ApplyFilterLatent(metaclass=IntegratedNode):
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
CATEGORY = "sampling/custom_sampling/OCS"
|
||||
DESCRIPTION = "Allows applying an OCS filter to any latent. Define a filter block in yaml_config."
|
||||
|
||||
FUNCTION = "go"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"latent": (
|
||||
"LATENT",
|
||||
{
|
||||
"tooltip": "Latent input. Note: This node does not care about masks.",
|
||||
},
|
||||
),
|
||||
"seed": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 0xFFFFFFFFFFFFFFFF,
|
||||
"tooltip": "Seed to use for generated noise.",
|
||||
},
|
||||
),
|
||||
"yaml_config": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "",
|
||||
"placeholder": """\
|
||||
# YAML or JSON filter definition
|
||||
""",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Enter your filter definition here. There is essentially no error handling.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def get_latent_samples(cls, latent: dict) -> torch.Tensor:
|
||||
samples = latent["samples"]
|
||||
batch_indexes = latent.get("batch_index")
|
||||
if batch_indexes is None:
|
||||
return samples.clone()
|
||||
return samples[tuple(batch_indexes), ...].clone()
|
||||
|
||||
def go(self, *, latent: dict, seed: int, yaml_config: str) -> tuple:
|
||||
MODULES.initialize()
|
||||
torch.manual_seed(seed)
|
||||
samples = self.get_latent_samples(latent)
|
||||
config = yaml.safe_load(yaml_config)
|
||||
if not config:
|
||||
return ({"samples": samples},)
|
||||
if not isinstance(config, dict) or "filter" not in config:
|
||||
raise ValueError(
|
||||
"Bad YAML config type (must be object) or missing filter key in config"
|
||||
)
|
||||
filter_def = config.get("filter")
|
||||
if not isinstance(filter_def, dict):
|
||||
raise ValueError("Bad type for filter definition, must be object")
|
||||
ocs_filter = make_filter(filter_def)
|
||||
new_samples = ocs_filter.apply(samples.to(dtype=torch.float32)).to(samples)
|
||||
return ({"samples": new_samples},)
|
||||
|
||||
|
||||
class ApplyFilterImage(ApplyFilterLatent):
|
||||
DESCRIPTION = "Allows applying an OCS filter to any image. Define a filter block in yaml_config."
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
result = super().INPUT_TYPES()
|
||||
del result["required"]["latent"]
|
||||
result["required"] = {
|
||||
"image": (
|
||||
"IMAGE",
|
||||
{"tooltip": "Image input."},
|
||||
),
|
||||
} | result["required"]
|
||||
return result
|
||||
|
||||
def go(self, *, image: torch.Tensor, seed: int, yaml_config: str) -> tuple:
|
||||
image = image.clone()
|
||||
if image.ndim == 3:
|
||||
image = image.unsqueeze(0)
|
||||
result = (
|
||||
super()
|
||||
.go(
|
||||
latent={"samples": image.movedim(-1, 1)},
|
||||
seed=seed,
|
||||
yaml_config=yaml_config,
|
||||
)[0]["samples"]
|
||||
.movedim(1, -1)
|
||||
.to(image)
|
||||
)
|
||||
return (result,)
|
||||
|
||||
|
||||
__all__ = (
|
||||
"SamplerNode",
|
||||
"GroupNode",
|
||||
"SubstepsNode",
|
||||
"ParamNode",
|
||||
"MultiParamNode",
|
||||
"ModelSetMaxSigmaNode",
|
||||
)
|
||||
|
||||
+309
@@ -0,0 +1,309 @@
|
||||
import gc
|
||||
import math
|
||||
import random
|
||||
|
||||
import scipy
|
||||
import torch
|
||||
from tqdm import tqdm
|
||||
|
||||
from .filtering import Filter, make_filter
|
||||
from .utils import scale_noise, fallback
|
||||
|
||||
|
||||
class ImmiscibleNoise(Filter):
|
||||
name = "immiscible"
|
||||
uses_ref = True
|
||||
default_options = Filter.default_options | {
|
||||
"size": 0,
|
||||
"batching": "channel",
|
||||
"maximize": False,
|
||||
"distance_scale": 0.0,
|
||||
"distance_scale_ref": None,
|
||||
}
|
||||
|
||||
def __call__(self, noise_sampler, x_ref, *, refs=None):
|
||||
if self.size == 0 or self.strength == 0 or not self.check_applies(refs):
|
||||
return noise_sampler()
|
||||
size = self.size if self.strength == 1.0 else self.size + 1
|
||||
return self.apply(
|
||||
torch.cat(tuple(noise_sampler() for _ in range(size))),
|
||||
default_ref=x_ref,
|
||||
refs=refs,
|
||||
output_shape=x_ref.shape,
|
||||
)
|
||||
|
||||
def filter(self, latent, ref_latent, *, refs, output_shape):
|
||||
if self.size == 0:
|
||||
return latent
|
||||
offset = 0 if self.strength == 1.0 else output_shape[0]
|
||||
return self.unbatch(
|
||||
self.immiscible(self.batch(latent[offset:]), self.batch(ref_latent)),
|
||||
output_shape,
|
||||
)
|
||||
|
||||
def batch(self, latent):
|
||||
if self.batching == "batch":
|
||||
return latent
|
||||
sz = latent.shape
|
||||
if self.batching == "channel":
|
||||
return latent.reshape(sz[0] * sz[1], *sz[2:])
|
||||
if self.batching == "frame":
|
||||
if latent.ndim != 5:
|
||||
raise ValueError(
|
||||
"Both latent and reference must be five-dimensional for frame mode"
|
||||
)
|
||||
return latent.permute(0, 2, 1, 3, 4).reshape(sz[0] * sz[2], sz[1], *sz[3:])
|
||||
if self.batching == "row":
|
||||
return latent.reshape(math.prod(sz[:-1]), sz[-1])
|
||||
if self.batching == "column":
|
||||
if latent.ndim != 4:
|
||||
raise ValueError(
|
||||
"Both latent and reference must be four-dimensional for column mode"
|
||||
)
|
||||
return latent.permute(0, 1, 3, 2).reshape(sz[0] * sz[1] * sz[3], sz[2])
|
||||
raise ValueError("Bad Immmiscible noise batching type")
|
||||
|
||||
def unbatch(self, latent, sz):
|
||||
if self.batching == "column":
|
||||
return latent.reshape(*sz[:2], sz[3], sz[2]).permute(0, 1, 3, 2)
|
||||
if self.batching == "frame":
|
||||
return latent.reshape(sz[0], sz[2], sz[1], *sz[3:]).permute(0, 2, 1, 3, 4)
|
||||
return latent.reshape(*sz)
|
||||
|
||||
# Originally based on implementation from https://github.com/kohya-ss/sd-scripts/pull/1395
|
||||
# Idea for use with inference as well as implementation help from https://github.com/Clybius
|
||||
def immiscible(
|
||||
self,
|
||||
latent: torch.Tensor,
|
||||
ref_latent: torch.Tensor,
|
||||
*,
|
||||
out_latent: torch.Tensor | None = None,
|
||||
return_idxs=False,
|
||||
):
|
||||
# "Immiscible Diffusion: Accelerating Diffusion Training with Noise Assignment" (2024) Li et al. arxiv.org/abs/2406.12303
|
||||
# Minimize latent-noise pairs over a batch
|
||||
batch = latent.shape[0]
|
||||
ref_latent = ref_latent.detach().clone()
|
||||
if self.distance_scale == 0:
|
||||
ref_latent_expanded = ref_latent.unsqueeze(1).expand(
|
||||
-1, batch, *ref_latent.shape[1:]
|
||||
)
|
||||
latent_expanded = latent.unsqueeze(0).expand(
|
||||
ref_latent.shape[0], *latent.shape
|
||||
)
|
||||
dist = (ref_latent_expanded - latent_expanded) ** 2
|
||||
del ref_latent_expanded, latent_expanded
|
||||
dist = dist.mean(tuple(range(2, dist.dim())))
|
||||
else:
|
||||
dist = torch.linalg.vector_norm(
|
||||
fallback(self.distance_scale_ref, self.distance_scale)
|
||||
* ref_latent.flatten(start_dim=1).unsqueeze(1)
|
||||
- self.distance_scale * latent.flatten(start_dim=1).unsqueeze(0),
|
||||
dim=2,
|
||||
)
|
||||
dist = dist.half()
|
||||
try:
|
||||
assign_mat = scipy.optimize.linear_sum_assignment(
|
||||
dist.cpu(), maximize=self.maximize
|
||||
)
|
||||
except ValueError as exc:
|
||||
tqdm.write(f"OCS: Immiscible: Failed due to exception: {exc}")
|
||||
return (
|
||||
None
|
||||
if return_idxs
|
||||
else fallback(out_latent, latent)[: ref_latent.shape[0]]
|
||||
)
|
||||
return (
|
||||
assign_mat if return_idxs else fallback(out_latent, latent)[assign_mat[1]]
|
||||
)
|
||||
|
||||
def immiscible_simple(
|
||||
self,
|
||||
latent: torch.Tensor,
|
||||
ref_latent: torch.Tensor,
|
||||
*,
|
||||
out_latent: torch.Tensor | None = None,
|
||||
) -> torch.Tensor:
|
||||
return self.unbatch(
|
||||
self.immiscible(
|
||||
self.batch(latent),
|
||||
self.batch(ref_latent),
|
||||
out_latent=self.batch(out_latent) if out_latent is not None else None,
|
||||
),
|
||||
ref_latent.shape,
|
||||
)
|
||||
|
||||
|
||||
class NoiseSamplerCache:
|
||||
def __init__(
|
||||
self,
|
||||
x,
|
||||
seed,
|
||||
min_sigma,
|
||||
max_sigma,
|
||||
*,
|
||||
normalize_noise=True,
|
||||
cpu_noise=True,
|
||||
batch_size=1,
|
||||
caching=True,
|
||||
cache_reset_interval=9999,
|
||||
set_seed=True,
|
||||
seed_offset=1,
|
||||
scale=1.0,
|
||||
normalize_dims=(-3, -2, -1),
|
||||
immiscible=None,
|
||||
filter=None,
|
||||
**_unused,
|
||||
):
|
||||
self.x = x
|
||||
self.mega_x = None
|
||||
self.seed = seed
|
||||
self.seed_offset = seed_offset
|
||||
self.min_sigma = min_sigma
|
||||
self.max_sigma = max_sigma
|
||||
self.cache = {}
|
||||
self.batch_size = max(1, batch_size)
|
||||
self.normalize_noise = normalize_noise
|
||||
self.cpu_noise = cpu_noise
|
||||
self.caching = caching
|
||||
self.cache_reset_interval = max(1, cache_reset_interval)
|
||||
self.scale = float(scale)
|
||||
self.normalize_dims = tuple(int(v) for v in normalize_dims)
|
||||
self.immiscible = ImmiscibleNoise(**fallback(immiscible, {}))
|
||||
if filter is None:
|
||||
self.filter = None
|
||||
else:
|
||||
self.filter = make_filter(filter)
|
||||
self.update_x(x)
|
||||
if set_seed:
|
||||
random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
if self.seed_offset > 0:
|
||||
for _ in range(self.seed_offset):
|
||||
_ = torch.randn_like(x)
|
||||
else:
|
||||
self.seed_offset = 0
|
||||
|
||||
def reset_cache(self):
|
||||
self.cache = {}
|
||||
gc.collect()
|
||||
|
||||
def scale_noise(self, noise, factor=1.0, normalized=None, normalize_dims=None):
|
||||
normalized = self.normalize_noise if normalized is None else normalized
|
||||
normalize_dims = (
|
||||
self.normalize_dims if normalize_dims is None else normalize_dims
|
||||
)
|
||||
return scale_noise(
|
||||
noise, factor, normalized=normalized, normalize_dims=normalize_dims
|
||||
)
|
||||
|
||||
def update_x(self, x):
|
||||
if self.x.shape == x.shape and self.mega_x is not None:
|
||||
self.x = x
|
||||
return
|
||||
self.x = x
|
||||
self.mega_x = None
|
||||
self.reset_cache()
|
||||
if self.batch_size == 1:
|
||||
self.mega_x = x
|
||||
return
|
||||
self.mega_x = x.repeat(x.shape[0] * self.batch_size, *((1,) * (x.dim() - 1)))
|
||||
|
||||
def set_cache(self, key, noise_sampler):
|
||||
if not self.caching:
|
||||
return
|
||||
self.cache[key] = noise_sampler
|
||||
|
||||
def make_caching_noise_sampler(
|
||||
self,
|
||||
nsobj,
|
||||
size,
|
||||
sigma,
|
||||
sigma_next,
|
||||
*,
|
||||
immiscible=None,
|
||||
sigmas=None,
|
||||
):
|
||||
size = min(size, self.batch_size)
|
||||
if immiscible is None:
|
||||
immiscible = self.immiscible
|
||||
cache_key = (nsobj, size, hash(immiscible))
|
||||
if self.caching:
|
||||
noise_sampler = self.cache.get(cache_key)
|
||||
if noise_sampler:
|
||||
return noise_sampler
|
||||
curr_seed = self.seed + self.seed_offset
|
||||
self.seed_offset += 1
|
||||
curr_x = self.mega_x[: self.x.shape[0] * size, ...]
|
||||
if nsobj is None:
|
||||
|
||||
def ns(*_unused, **_unusedkwargs):
|
||||
noise = torch.randn(
|
||||
curr_x.shape,
|
||||
dtype=curr_x.dtype,
|
||||
layout=curr_x.layout,
|
||||
device="cpu" if self.cpu_noise else curr_x.device,
|
||||
)
|
||||
if noise.device != curr_x.device:
|
||||
return noise.to(curr_x.device)
|
||||
return noise
|
||||
|
||||
else:
|
||||
if sigmas is not None:
|
||||
sigma_min, sigma_max = sigmas[sigmas > 0].min(), sigmas.max()
|
||||
else:
|
||||
sigma_min, sigma_max = self.min_sigma, self.max_sigma
|
||||
ns = nsobj.make_noise_sampler(
|
||||
curr_x,
|
||||
sigma_min,
|
||||
sigma_max,
|
||||
seed=curr_seed,
|
||||
normalized=False,
|
||||
cpu=self.cpu_noise,
|
||||
)
|
||||
|
||||
orig_h, orig_w = self.x.shape[-2:]
|
||||
remain = 0
|
||||
noise = None
|
||||
|
||||
def noise_sampler_(
|
||||
curr_sigma,
|
||||
curr_sigma_next,
|
||||
*_unused,
|
||||
out_hw=(orig_h, orig_w),
|
||||
**_unusedkwargs,
|
||||
):
|
||||
nonlocal remain, noise
|
||||
if out_hw != (orig_h, orig_w):
|
||||
raise NotImplementedError(
|
||||
f"Noise size mismatch: {out_hw} vs {(orig_h, orig_w)}"
|
||||
)
|
||||
if remain < 1:
|
||||
curr_sigma = fallback(curr_sigma, sigma)
|
||||
curr_sigma_next = fallback(curr_sigma_next, sigma_next)
|
||||
noise = self.scale_noise(ns(curr_sigma, curr_sigma_next)).view(
|
||||
size,
|
||||
*self.x.shape,
|
||||
)
|
||||
remain = size
|
||||
result = noise[-remain]
|
||||
remain -= 1
|
||||
return result
|
||||
|
||||
def noise_sampler(*args, x_ref=None, refs=None, **kwargs):
|
||||
if immiscible is False:
|
||||
noise = noise_sampler_(*args, **kwargs)
|
||||
else:
|
||||
noise = immiscible(
|
||||
lambda args=args, kwargs=kwargs: noise_sampler_(*args, **kwargs),
|
||||
fallback(x_ref, self.x),
|
||||
refs=refs,
|
||||
)
|
||||
return (
|
||||
self.filter.apply(noise, refs=refs)
|
||||
if self.filter is not None
|
||||
else noise
|
||||
)
|
||||
|
||||
self.set_cache(cache_key, noise_sampler)
|
||||
return noise_sampler
|
||||
@@ -0,0 +1,94 @@
|
||||
import torch
|
||||
|
||||
|
||||
class Restart:
|
||||
def __init__(self, *, s_noise=1.0, custom_noise=None, immiscible=False):
|
||||
from .noise import ImmiscibleNoise
|
||||
|
||||
self.s_noise = s_noise
|
||||
if immiscible is not False:
|
||||
immiscible = ImmiscibleNoise(**immiscible)
|
||||
self.immiscible = immiscible
|
||||
self.custom_noise = custom_noise
|
||||
|
||||
def get_noise_sampler(self, nsc):
|
||||
return nsc.make_caching_noise_sampler(
|
||||
self.custom_noise,
|
||||
1,
|
||||
nsc.max_sigma,
|
||||
nsc.min_sigma,
|
||||
immiscible=self.immiscible,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_segment(sigmas: torch.Tensor) -> torch.Tensor:
|
||||
last_sigma = sigmas[0]
|
||||
for idx in range(1, len(sigmas)):
|
||||
sigma = sigmas[idx]
|
||||
if sigma > last_sigma:
|
||||
return sigmas[:idx]
|
||||
last_sigma = sigma
|
||||
return sigmas
|
||||
|
||||
def split_sigmas(self, sigmas):
|
||||
prev_seg = None
|
||||
while len(sigmas) > 1:
|
||||
seg = self.get_segment(sigmas)
|
||||
sigmas = sigmas[len(seg) :]
|
||||
if prev_seg is not None and seg[0] > prev_seg[-1]:
|
||||
noise_scale = self.get_noise_scale(prev_seg[-1], seg[0])
|
||||
else:
|
||||
noise_scale = 0.0
|
||||
prev_seg = seg
|
||||
yield (noise_scale, seg)
|
||||
|
||||
def get_noise_scale(self, s_min, s_max):
|
||||
result = (s_max**2 - s_min**2) ** 0.5
|
||||
if isinstance(result, torch.Tensor):
|
||||
result = result.item()
|
||||
return result * self.s_noise
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Restart: s_noise={self.s_noise:.04}, immiscible={self.immiscible}>"
|
||||
|
||||
@classmethod
|
||||
def simple_schedule(cls, sigmas, start_step, schedule=(), max_iter=1000):
|
||||
if sigmas.ndim != 1:
|
||||
raise ValueError("Bad number of dimensions for sigmas")
|
||||
siglen = len(sigmas) - 1
|
||||
if siglen <= start_step or not len(schedule):
|
||||
return sigmas
|
||||
siglist = sigmas.cpu().tolist()
|
||||
out = siglist[:start_step]
|
||||
sched_len = len(schedule)
|
||||
sched_idx = 0
|
||||
sig_idx = start_step
|
||||
iter_count = 0
|
||||
while 0 <= sched_idx < sched_len:
|
||||
# print(f"LOOP: sched_idx={sched_idx}, sig_idx={sig_idx}: {out}")
|
||||
iter_count += 1
|
||||
if iter_count > max_iter:
|
||||
raise RuntimeError("Hit max iteration count. Loop in schedule?")
|
||||
item = schedule[sched_idx]
|
||||
if not isinstance(item, (list, tuple)):
|
||||
if item < 0:
|
||||
item = sched_len + item
|
||||
if item < 0 or item >= sched_len:
|
||||
raise ValueError("Schedule jump index out of range")
|
||||
sched_idx = item
|
||||
continue
|
||||
if sig_idx >= siglen or sig_idx < 0:
|
||||
break
|
||||
interval, jump = item
|
||||
chunk = siglist[sig_idx : sig_idx + interval + 1]
|
||||
# print(f"{out} + {chunk}")
|
||||
out += chunk
|
||||
sig_idx += interval + jump
|
||||
if jump >= 0:
|
||||
sig_idx += 1
|
||||
sched_idx += 1
|
||||
if sig_idx < siglen and sig_idx >= 0:
|
||||
out += siglist[sig_idx:]
|
||||
if out[-1] > siglist[-1]:
|
||||
out.append(siglist[-1])
|
||||
return torch.tensor(out).to(sigmas)
|
||||
+90
-50
@@ -2,9 +2,23 @@ import torch
|
||||
from tqdm.auto import trange
|
||||
|
||||
|
||||
from .substep_samplers import STEP_SAMPLERS
|
||||
from .substep_sampling import SamplerState, History, ModelCallCache
|
||||
from .filtering import FILTER_HANDLERS, FilterRefs
|
||||
from .model import OCSModel
|
||||
from .noise import NoiseSamplerCache
|
||||
from .substep_sampling import SamplerState
|
||||
from .substep_merging import MERGE_SUBSTEPS_CLASSES
|
||||
from .restart import Restart
|
||||
|
||||
|
||||
def find_merge_sampler(merge_samplers, ss) -> object | None:
|
||||
handlers = None
|
||||
for merge_sampler in merge_samplers:
|
||||
if merge_sampler.when is not None and handlers is None:
|
||||
handlers = FILTER_HANDLERS.clone(constants=ss.refs)
|
||||
# handlers = FILTER_HANDLERS.clone_with_refs(ss.refs)
|
||||
if merge_sampler.check_match(handlers, ss=ss):
|
||||
return merge_sampler
|
||||
return None
|
||||
|
||||
|
||||
def composable_sampler(
|
||||
@@ -14,14 +28,14 @@ def composable_sampler(
|
||||
*,
|
||||
s_noise=1.0,
|
||||
eta=1.0,
|
||||
composable_sampler_options,
|
||||
overly_complicated_options,
|
||||
extra_args=None,
|
||||
callback=None,
|
||||
disable=None,
|
||||
noise_sampler=None,
|
||||
**kwargs,
|
||||
):
|
||||
copts = composable_sampler_options.copy()
|
||||
copts = overly_complicated_options.copy()
|
||||
if extra_args is None:
|
||||
extra_args = {}
|
||||
if noise_sampler is None:
|
||||
@@ -29,64 +43,90 @@ def composable_sampler(
|
||||
def noise_sampler(_s, _sn):
|
||||
return torch.randn_like(x)
|
||||
|
||||
samplers = []
|
||||
substeps = 0
|
||||
for sitem in copts["chain"].items:
|
||||
custom_noise = sitem.get("custom_noise_opt")
|
||||
if custom_noise is None:
|
||||
curr_ns = noise_sampler
|
||||
else:
|
||||
curr_ns = custom_noise.make_noise_sampler(
|
||||
x, sigmas[-1], sigmas[0], normalized=True
|
||||
)
|
||||
ssampler = STEP_SAMPLERS[sitem["step_method"]](noise_sampler=curr_ns, **sitem)
|
||||
samplers.append(ssampler)
|
||||
# samplers += (ssampler,) * sitem["substeps"]
|
||||
substeps += ssampler.substeps
|
||||
msitem = copts["merge_sampler"]
|
||||
if copts["merge_method"] in ("sample", "sample_uncached"):
|
||||
custom_noise = msitem.get("custom_noise_opt")
|
||||
if custom_noise is None:
|
||||
curr_ns = noise_sampler
|
||||
else:
|
||||
curr_ns = custom_noise.make_noise_sampler(
|
||||
x, sigmas[-1], sigmas[0], normalized=True
|
||||
)
|
||||
merge_sampler = STEP_SAMPLERS[msitem["step_method"]](
|
||||
noise_sampler=curr_ns, **msitem
|
||||
)
|
||||
pass
|
||||
else:
|
||||
merge_sampler = None
|
||||
restart_params = copts.get("restart", {})
|
||||
restart_enabled = restart_params.get("enabled", True)
|
||||
restart_custom_noise = copts.get("restart_custom_noise")
|
||||
if isinstance(restart_custom_noise, str):
|
||||
restart_custom_noise = copts.get(f"restart_custom_noise_{restart_custom_noise}")
|
||||
restart = Restart(
|
||||
s_noise=restart_params.get("s_noise", 1.0),
|
||||
custom_noise=restart_custom_noise,
|
||||
immiscible=restart_params.get("immiscible", False),
|
||||
)
|
||||
|
||||
ss = SamplerState(
|
||||
ModelCallCache(
|
||||
OCSModel(
|
||||
model,
|
||||
x,
|
||||
x.new_ones((x.shape[0],)),
|
||||
extra_args,
|
||||
size=copts.get("model_call_cache", 0),
|
||||
max_use=copts.get("model_call_cache_max_use", 1000000),
|
||||
threshold=copts.get("model_call_cache_threshold", 0),
|
||||
**copts.get("model", {}),
|
||||
),
|
||||
sigmas,
|
||||
0,
|
||||
History(x, 3),
|
||||
History(x, 2),
|
||||
extra_args,
|
||||
noise_sampler=noise_sampler,
|
||||
callback=callback,
|
||||
eta=eta if eta != 1.0 else copts["eta"],
|
||||
s_noise=s_noise if s_noise != 1.0 else copts["s_noise"],
|
||||
eta=eta if eta != 1.0 else copts.get("eta", 1.0),
|
||||
s_noise=s_noise if s_noise != 1.0 else copts.get("s_noise", 1.0),
|
||||
reta=copts.get("reta", 1.0),
|
||||
disable_status=disable,
|
||||
)
|
||||
merge_sampler = MERGE_SUBSTEPS_CLASSES[copts["merge_method"]](
|
||||
ss,
|
||||
samplers,
|
||||
**(copts | {"merge_sampler": merge_sampler}),
|
||||
groups = copts["_groups"]
|
||||
merge_samplers = tuple(
|
||||
MERGE_SUBSTEPS_CLASSES[g.merge_method](ss, g) for g in groups.items
|
||||
)
|
||||
for idx in trange(len(sigmas) - 1, disable=disable):
|
||||
print(f"STEP {idx+1}")
|
||||
ss.update(idx)
|
||||
ss.model.reset_cache()
|
||||
x = merge_sampler.step(x)
|
||||
nsc = NoiseSamplerCache(
|
||||
x,
|
||||
extra_args.get("seed", 42),
|
||||
sigmas[sigmas > 0].min(),
|
||||
sigmas.max(),
|
||||
**copts.get("noise", {}),
|
||||
)
|
||||
ss.noise = nsc
|
||||
sigma_chunks = (
|
||||
tuple(restart.split_sigmas(sigmas)) if restart_enabled else ((0.0, sigmas),)
|
||||
)
|
||||
step_count = sum(len(chunk) - 1 for _noise, chunk in sigma_chunks)
|
||||
ss.total_steps = step_count
|
||||
step = 0
|
||||
with trange(step_count, disable=ss.disable_status) as pbar:
|
||||
for noise_scale, chunk_sigmas in sigma_chunks:
|
||||
if step != 0 and noise_scale != 0:
|
||||
prev_refs = FilterRefs({
|
||||
f"pre_restart_{k}": v for k, v in ss.refs.items()
|
||||
})
|
||||
ss.sigmas = chunk_sigmas
|
||||
ss.update(0, step=step, substep=0)
|
||||
if step != 0:
|
||||
nsc.reset_cache()
|
||||
nsc.update_x(x)
|
||||
ss.hist.reset()
|
||||
for ms in merge_samplers:
|
||||
ms.reset()
|
||||
nsc.min_sigma, nsc.max_sigma = chunk_sigmas[-1], chunk_sigmas[0]
|
||||
if step != 0 and noise_scale != 0:
|
||||
restart_ns = restart.get_noise_sampler(nsc)
|
||||
x += nsc.scale_noise(
|
||||
restart_ns(nsc.min_sigma, nsc.max_sigma, refs=prev_refs | ss.refs),
|
||||
noise_scale,
|
||||
)
|
||||
del restart_ns
|
||||
del prev_refs
|
||||
for idx in range(len(chunk_sigmas) - 1):
|
||||
if idx > 0:
|
||||
ss.update(idx, step=step, substep=0)
|
||||
nsc.update_x(x)
|
||||
nsc.update_x(x)
|
||||
merge_sampler = find_merge_sampler(merge_samplers, ss)
|
||||
if merge_sampler is None:
|
||||
raise RuntimeError(f"No matching sampler group for step {step + 1}")
|
||||
pbar.set_description(
|
||||
f"{merge_sampler.name}: {ss.sigma.item():.03} -> {ss.sigma_next.item():.03}"
|
||||
)
|
||||
x = merge_sampler(x)
|
||||
if (idx + 1) % nsc.cache_reset_interval == 0:
|
||||
nsc.reset_cache()
|
||||
step += 1
|
||||
pbar.update(1)
|
||||
return x
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
from . import ( # noqa: F401
|
||||
builtins,
|
||||
blep,
|
||||
clybius,
|
||||
extraltodeus,
|
||||
misc,
|
||||
solver_tde,
|
||||
solver_tode,
|
||||
solver_tsde,
|
||||
solver_diffrax,
|
||||
)
|
||||
|
||||
from . import registry
|
||||
|
||||
registry.init()
|
||||
|
||||
STEP_SAMPLERS = registry.STEP_SAMPLERS
|
||||
STEP_SAMPLER_SIMPLE_NAMES = registry.STEP_SAMPLER_SIMPLE_NAMES
|
||||
|
||||
__all__ = ("STEP_SAMPLERS", "STEP_SAMPLER_SIMPLE_NAMES")
|
||||
@@ -0,0 +1,536 @@
|
||||
import contextlib
|
||||
import typing
|
||||
|
||||
import torch
|
||||
|
||||
from . import registry # noqa: F401
|
||||
|
||||
from .. import filtering, noise, utils
|
||||
from ..utils import fallback
|
||||
|
||||
|
||||
class SamplerResult:
|
||||
CLONE_KEYS = (
|
||||
"denoised_cond",
|
||||
"denoised_uncond",
|
||||
"denoised",
|
||||
"final",
|
||||
"is_rectified_flow",
|
||||
"noise_pred",
|
||||
"noise_sampler",
|
||||
"s_noise",
|
||||
"sampler",
|
||||
"sigma_down",
|
||||
"sigma_next",
|
||||
"sigma_up",
|
||||
"sigma",
|
||||
"step",
|
||||
"substep",
|
||||
"x_",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ss,
|
||||
sampler,
|
||||
x,
|
||||
sigma_up=None,
|
||||
*,
|
||||
split_result=None,
|
||||
sigma=None,
|
||||
sigma_next=None,
|
||||
sigma_down=None,
|
||||
s_noise=None,
|
||||
noise_sampler=None,
|
||||
final=True,
|
||||
):
|
||||
self.is_rectified_flow = ss.model.is_rectified_flow
|
||||
self.sampler = sampler
|
||||
self.sigma_up = fallback(sigma_up, ss.sigma.new_zeros(1))
|
||||
self.s_noise = fallback(s_noise, sampler.s_noise)
|
||||
self.sigma = fallback(sigma, ss.sigma)
|
||||
self.sigma_next = fallback(sigma_next, ss.sigma_next)
|
||||
self.sigma_down = fallback(sigma_down, self.sigma_next)
|
||||
self.noise_sampler = fallback(noise_sampler, sampler.noise_sampler)
|
||||
self.final = final
|
||||
self.step = ss.step
|
||||
self.substep = ss.substep
|
||||
self.x_ = x
|
||||
if split_result is not None:
|
||||
self.denoised, self.noise_pred = split_result
|
||||
elif x is None:
|
||||
raise ValueError("SamplerResult requires at least one of x, split_result")
|
||||
else:
|
||||
self.denoised = self.noise_pred = None
|
||||
_ = self.extract_pred(ss)
|
||||
self.denoised_uncond = ss.hcur.denoised_uncond
|
||||
self.denoised_cond = ss.hcur.denoised_cond
|
||||
|
||||
def get_noise(self, *, scaled=True, ss=None):
|
||||
if self.sigma_next == 0 or self.noise_scale == 0:
|
||||
return torch.zeros_like(self.x_)
|
||||
return self.noise_sampler(
|
||||
self.sigma,
|
||||
self.sigma_next,
|
||||
out_hw=self.x.shape[-2:],
|
||||
x_ref=self.x,
|
||||
refs=filtering.FilterRefs.from_sr(self) if ss is None else ss.refs,
|
||||
).mul_(self.noise_scale if scaled else 1.0)
|
||||
|
||||
def extract_pred(self, ss):
|
||||
if self.denoised is None or self.noise_pred is None:
|
||||
self.denoised, self.noise_pred = utils.extract_pred(
|
||||
ss.hcur.x, self.x_, ss.sigma, self.sigma_down
|
||||
)
|
||||
return self.denoised, self.noise_pred
|
||||
|
||||
@property
|
||||
def x(self):
|
||||
if self.x_ is None:
|
||||
self.x_ = self.denoised + self.sigma_down * self.noise_pred
|
||||
return self.x_
|
||||
|
||||
@property
|
||||
def noise_scale(self):
|
||||
return self.sigma_up * self.s_noise
|
||||
|
||||
def noise_x(self, x=None, scale=1.0, *, ss=None):
|
||||
x = fallback(x, self.x)
|
||||
if self.sigma_next == 0 or self.noise_scale == 0:
|
||||
return x
|
||||
noise = self.get_noise(ss=ss).mul_(scale)
|
||||
if not self.is_rectified_flow:
|
||||
return noise.add_(x)
|
||||
x_coeff = (1 - self.sigma_next) / (1 - self.sigma_down)
|
||||
# print(f"\nRF noise: {x_coeff}")
|
||||
return noise.add_(x_coeff * x)
|
||||
|
||||
def clone(self):
|
||||
obj = self.__new__(self.__class__)
|
||||
for k in self.CLONE_KEYS:
|
||||
if hasattr(self, k):
|
||||
setattr(obj, k, getattr(self, k))
|
||||
return obj
|
||||
|
||||
|
||||
class StepSamplerContext:
|
||||
def __init__(self, sampler, *args, **kwargs):
|
||||
self.sampler = sampler
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
|
||||
def __enter__(self):
|
||||
if self.sampler.ss is not None:
|
||||
raise RuntimeError("Cannot reenter prepared sampler in context manager!")
|
||||
self.sampler.prepare(*self.args, **self.kwargs)
|
||||
return self.sampler
|
||||
|
||||
def __exit__(self, *_unused):
|
||||
self.sampler.reset()
|
||||
|
||||
|
||||
class SingleStepSampler:
|
||||
name = None
|
||||
self_noise = 0
|
||||
model_calls = 0
|
||||
ancestralize = False
|
||||
sample_sigma_zero = False
|
||||
immiscible = None
|
||||
allow_cfgpp = False
|
||||
allow_alt_cfgpp = False
|
||||
afs_end_step = -1
|
||||
uses_alt_noise = False
|
||||
|
||||
default_eta = 1.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
noise_sampler=None,
|
||||
substeps=1,
|
||||
s_noise=1.0,
|
||||
eta=None,
|
||||
eta_retry_increment=0,
|
||||
dyn_eta_start=None,
|
||||
dyn_eta_end=None,
|
||||
weight=1.0,
|
||||
pre_filter=None,
|
||||
post_filter=None,
|
||||
immiscible=None,
|
||||
**kwargs,
|
||||
):
|
||||
self.ss = None
|
||||
self.options = kwargs
|
||||
self.cfgpp = self.allow_cfgpp and self.options.pop("cfgpp", False) is True
|
||||
alt_cfgpp_scale = self.options.pop("alt_cfgpp_scale", 0.0)
|
||||
self.alt_cfgpp_scale = 0.0 if not self.allow_alt_cfgpp else alt_cfgpp_scale
|
||||
self.s_noise = s_noise
|
||||
self.eta = fallback(eta, self.default_eta)
|
||||
self.eta_retry_increment = eta_retry_increment
|
||||
self.dyn_eta_start = dyn_eta_start
|
||||
self.dyn_eta_end = dyn_eta_end
|
||||
self.noise_sampler = noise_sampler
|
||||
self.immiscible = (
|
||||
noise.ImmiscibleNoise(**immiscible)
|
||||
if immiscible not in (False, None)
|
||||
else immiscible
|
||||
)
|
||||
self.weight = weight
|
||||
self.afs_end_step = self.options.pop("afs_end_step", -1)
|
||||
self.substeps = substeps
|
||||
self.pre_filter = (
|
||||
None if pre_filter is None else filtering.make_filter(pre_filter)
|
||||
)
|
||||
self.post_filter = (
|
||||
None if post_filter is None else filtering.make_filter(post_filter)
|
||||
)
|
||||
self.custom_noise = self.options.get("custom_noise")
|
||||
if isinstance(self.custom_noise, str):
|
||||
self.custom_noise = self.options.get(f"custom_noise_{self.custom_noise}")
|
||||
if not self.uses_alt_noise:
|
||||
return
|
||||
self.alt_custom_noise = self.options.get("custom_noise_alt")
|
||||
alt_immiscible = self.options.get("alt_immiscible")
|
||||
self.alt_immiscible = (
|
||||
noise.ImmiscibleNoise(**alt_immiscible)
|
||||
if isinstance(alt_immiscible, dict)
|
||||
else alt_immiscible
|
||||
)
|
||||
|
||||
def __call__(self, x):
|
||||
ss = self.ss
|
||||
orig_x = x
|
||||
if not self.sample_sigma_zero and ss.sigma_next == 0:
|
||||
return (yield from self.denoised_result())
|
||||
if ss.step <= self.afs_end_step:
|
||||
return (yield from self.afs_step(x))
|
||||
if self.pre_filter or self.post_filter:
|
||||
filter_refs = ss.refs | filtering.FilterRefs({"orig_x": orig_x})
|
||||
if self.pre_filter:
|
||||
x = self.pre_filter.apply(x, refs=filter_refs)
|
||||
next_x = None
|
||||
sg = self.step(x)
|
||||
with contextlib.suppress(StopIteration):
|
||||
while True:
|
||||
sr = sg.send(next_x)
|
||||
if sr.final:
|
||||
if self.ancestralize:
|
||||
sr = self.ancestralize_result(sr)
|
||||
curr_x = sr.x
|
||||
if self.post_filter:
|
||||
curr_x = self.post_filter.apply(curr_x, refs=filter_refs)
|
||||
sr.x_ = curr_x
|
||||
return (yield sr)
|
||||
next_x = sr.noise_x(ss=ss)
|
||||
|
||||
def step(self, x):
|
||||
raise NotImplementedError
|
||||
|
||||
def prepare(self, ss):
|
||||
self.ss = ss
|
||||
self.noise_sampler = ss.noise.make_caching_noise_sampler(
|
||||
self.custom_noise,
|
||||
self.max_noise_samples,
|
||||
ss.sigma,
|
||||
ss.sigma_next,
|
||||
immiscible=fallback(self.immiscible, ss.noise.immiscible),
|
||||
)
|
||||
if not self.uses_alt_noise:
|
||||
return
|
||||
if self.alt_custom_noise is None and self.alt_immiscible is None:
|
||||
self.alt_noise_sampler = self.noise_sampler
|
||||
return
|
||||
self.alt_noise_sampler = ss.noise.make_caching_noise_sampler(
|
||||
fallback(self.alt_custom_noise, self.custom_noise),
|
||||
1,
|
||||
ss.sigma,
|
||||
ss.sigma_next,
|
||||
immiscible=fallback(
|
||||
fallback(self.alt_immiscible, self.immiscible),
|
||||
ss.noise.immiscible,
|
||||
),
|
||||
)
|
||||
|
||||
def reset(self):
|
||||
self.ss = None
|
||||
self.noise_sampler = None
|
||||
if self.uses_alt_noise:
|
||||
self.alt_noise_sampler = None
|
||||
|
||||
# From https://arxiv.org/abs/2210.05475
|
||||
def afs_step(self, x):
|
||||
sigma, sigma_next = self.ss.sigma, self.ss.sigma_next
|
||||
afs_d = x / ((1 + sigma**2).sqrt())
|
||||
dt = sigma_next - sigma
|
||||
return (yield from self.result(x + afs_d * dt))
|
||||
|
||||
# Euler - based on original ComfyUI implementation
|
||||
def euler_step(
|
||||
self,
|
||||
x,
|
||||
*,
|
||||
sigma_down=None,
|
||||
sigma_up=None,
|
||||
eta=None,
|
||||
sigma=None,
|
||||
sigma_next=None,
|
||||
):
|
||||
eta = fallback(eta, self.get_dyn_eta())
|
||||
if sigma_down is None or sigma_up is None:
|
||||
if not (sigma_down is None and sigma_up is None):
|
||||
raise ValueError("Must pass both sigma_down and sigma_up or neither")
|
||||
sigma_down, sigma_up = self.get_ancestral_step(
|
||||
eta=eta, sigma=sigma, sigma_next=sigma_next
|
||||
)
|
||||
return (
|
||||
yield from self.split_result(
|
||||
*self.get_split_prediction(), sigma_down=sigma_down, sigma_up=sigma_up
|
||||
)
|
||||
)
|
||||
|
||||
def denoised_result(self, **kwargs):
|
||||
ss = self.ss
|
||||
return (
|
||||
yield SamplerResult(ss, self, ss.denoised, ss.sigma.new_zeros(1), **kwargs)
|
||||
)
|
||||
|
||||
def result(self, x, noise_scale=None, **kwargs):
|
||||
return (yield SamplerResult(self.ss, self, x, noise_scale, **kwargs))
|
||||
|
||||
def split_result(
|
||||
self, denoised=None, noise_pred=None, sigma_up=None, sigma_down=None, **kwargs
|
||||
):
|
||||
return (
|
||||
yield SamplerResult(
|
||||
ss=self.ss,
|
||||
sampler=self,
|
||||
x=None,
|
||||
sigma_up=sigma_up,
|
||||
sigma_down=sigma_down,
|
||||
split_result=(denoised, noise_pred),
|
||||
**kwargs,
|
||||
)
|
||||
)
|
||||
|
||||
def get_ancestral_step(
|
||||
self, *args, dyn_eta=False, as_dict=False, retry_increment=None, **kwargs
|
||||
):
|
||||
if dyn_eta:
|
||||
args = (self.get_dyn_eta(), *args)
|
||||
retry_increment = fallback(retry_increment, self.eta_retry_increment)
|
||||
sigma_down, sigma_up = self.ss.get_ancestral_step(
|
||||
*args, retry_increment=retry_increment, **kwargs
|
||||
)
|
||||
if not as_dict:
|
||||
return sigma_down, sigma_up
|
||||
return {"sigma_down": sigma_down, "sigma_up": sigma_up}
|
||||
|
||||
def ancestralize_result(self, sr):
|
||||
ss = self.ss
|
||||
new_sr = sr.clone()
|
||||
if new_sr.sigma_down is not None and new_sr.sigma_down != new_sr.sigma_next:
|
||||
return sr
|
||||
eta = self.get_dyn_eta()
|
||||
if sr.sigma_next == 0 or eta == 0:
|
||||
return sr
|
||||
sd, su = self.get_ancestral_step(eta, sigma=sr.sigma, sigma_next=sr.sigma_next)
|
||||
_ = new_sr.extract_pred(ss)
|
||||
new_sr.x_ = None
|
||||
new_sr.sigma_up = su
|
||||
new_sr.sigma_down = sd
|
||||
return new_sr
|
||||
|
||||
def __str__(self):
|
||||
return f"<SS({self.name}): s_noise={self.s_noise}, eta={self.eta}>"
|
||||
|
||||
def get_dyn_value(self, start, end):
|
||||
if None in (start, end):
|
||||
return 1.0
|
||||
if start == end:
|
||||
return start
|
||||
ss = self.ss
|
||||
main_idx = getattr(ss, "main_idx", ss.idx)
|
||||
main_sigmas = getattr(ss, "main_sigmas", ss.sigmas)
|
||||
step_pct = main_idx / (len(main_sigmas) - 1)
|
||||
dd_diff = end - start
|
||||
return start + dd_diff * step_pct
|
||||
|
||||
def get_dyn_eta(self):
|
||||
return self.eta * self.get_dyn_value(self.dyn_eta_start, self.dyn_eta_end)
|
||||
|
||||
@property
|
||||
def max_noise_samples(self):
|
||||
return (1 + self.self_noise) * self.substeps
|
||||
|
||||
@property
|
||||
def require_uncond(self):
|
||||
return self.cfgpp or self.alt_cfgpp_scale != 0
|
||||
|
||||
def to_d(self, mr, *, use_cfgpp=True, **kwargs):
|
||||
if not use_cfgpp:
|
||||
return mr.to_d(**kwargs)
|
||||
return mr.to_d(alt_cfgpp_scale=self.alt_cfgpp_scale, cfgpp=self.cfgpp, **kwargs)
|
||||
|
||||
def get_split_prediction(self, *, mr=None, sigma=None, **kwargs):
|
||||
mr = fallback(mr, self.ss.hcur)
|
||||
sigma = fallback(sigma, mr.sigma)
|
||||
return mr.get_split_prediction(
|
||||
sigma=sigma,
|
||||
alt_cfgpp_scale=self.alt_cfgpp_scale,
|
||||
cfgpp=self.cfgpp,
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def call_model(self, *args, **kwargs):
|
||||
ss = self.ss
|
||||
kwargs["require_uncond"] = self.require_uncond or kwargs.get(
|
||||
"require_uncond", False
|
||||
)
|
||||
kwargs["cfg_scale_override"] = kwargs.get(
|
||||
"cfg_scale_override",
|
||||
self.options.get("cfg_scale_override", ss.cfg_scale_override),
|
||||
)
|
||||
return ss.call_model(*args, ss=ss, **kwargs)
|
||||
|
||||
def step_mix(self, x, denoised, uncond, ratio, *, blend=torch.lerp):
|
||||
if self.cfgpp:
|
||||
return denoised + (x - uncond).mul_(ratio)
|
||||
pp = self.alt_cfgpp_scale
|
||||
if pp == 0:
|
||||
return blend(denoised, x, ratio)
|
||||
return blend(denoised * (1 + pp) - uncond * pp, x, ratio)
|
||||
|
||||
|
||||
class HistorySingleStepSampler(SingleStepSampler):
|
||||
default_history_limit, max_history = 0, 0
|
||||
|
||||
def __init__(self, *args, history_limit=None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.history_limit = min(
|
||||
self.max_history,
|
||||
max(
|
||||
0,
|
||||
self.default_history_limit if history_limit is None else history_limit,
|
||||
),
|
||||
)
|
||||
|
||||
def available_history(self):
|
||||
ss = self.ss
|
||||
available = max(
|
||||
0, min(ss.idx, self.history_limit, self.max_history, len(ss.hist) - 1)
|
||||
)
|
||||
if not available:
|
||||
return available
|
||||
curr_shape = ss.hist[-1].denoised.shape
|
||||
for eff_available in range(available):
|
||||
if ss.hist[-2 - eff_available].denoised.shape != curr_shape:
|
||||
return eff_available
|
||||
return available
|
||||
|
||||
|
||||
class ReversibleConfig(typing.NamedTuple):
|
||||
scale: float
|
||||
eta: float
|
||||
dyn_eta_start: float | None = None
|
||||
dyn_eta_end: float | None = None
|
||||
eta_retry_increment: float = 0.0
|
||||
start_step: int = 0
|
||||
end_step: int = 9999
|
||||
use_cfgpp: bool = False
|
||||
|
||||
@classmethod
|
||||
def build(cls, *, default_eta, default_scale, eta=None, scale=None, **kwargs):
|
||||
return cls.__new__(
|
||||
cls,
|
||||
eta=fallback(eta, default_eta),
|
||||
scale=fallback(scale, default_scale),
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def check(self, step):
|
||||
return self.scale != 0 and self.start_step <= step <= self.end_step
|
||||
|
||||
|
||||
class ReversibleSingleStepSampler(HistorySingleStepSampler):
|
||||
default_reversible_scale = 1.0
|
||||
default_reta = 1.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
reversible_scale=None,
|
||||
reta=None,
|
||||
dyn_reta_start=None,
|
||||
dyn_reta_end=None,
|
||||
reversible_start_step=0,
|
||||
reversible=None,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
if reversible is None:
|
||||
# For backward compatibility.
|
||||
self.reversible = ReversibleConfig.build(
|
||||
default_eta=self.default_reta,
|
||||
default_scale=self.default_reversible_scale,
|
||||
scale=reversible_scale,
|
||||
eta=reta,
|
||||
dyn_eta_start=dyn_reta_start,
|
||||
dyn_eta_end=dyn_reta_end,
|
||||
start_step=reversible_start_step,
|
||||
)
|
||||
return
|
||||
self.reversible = ReversibleConfig.build(
|
||||
default_eta=self.default_reta,
|
||||
default_scale=self.default_reversible_scale,
|
||||
**reversible,
|
||||
)
|
||||
|
||||
def reversible_correction(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def get_dyn_reta(self, *, r=None):
|
||||
r = fallback(r, self.reversible)
|
||||
ss = self.ss
|
||||
if not r.check(ss.step):
|
||||
return 0.0
|
||||
return r.eta * self.get_dyn_value(r.dyn_eta_start, r.dyn_eta_end)
|
||||
|
||||
dyn_reta = property(get_dyn_reta)
|
||||
|
||||
def get_reversible_cfg(self, *, reversible=None):
|
||||
reversible = fallback(reversible, self.reversible)
|
||||
ss = self.ss
|
||||
if not reversible.check(ss.step):
|
||||
return 0.0, 0.0
|
||||
return self.get_dyn_reta(r=reversible), reversible.scale
|
||||
|
||||
|
||||
class DPMPPStepMixin:
|
||||
@staticmethod
|
||||
def sigma_fn(t):
|
||||
return t.neg().exp()
|
||||
|
||||
@staticmethod
|
||||
def t_fn(t):
|
||||
return t.log().neg()
|
||||
|
||||
|
||||
class MinSigmaStepMixin:
|
||||
@staticmethod
|
||||
def adjust_step(sigma, min_sigma, threshold=5e-04):
|
||||
if min_sigma - sigma > threshold:
|
||||
return sigma.clamp(min=min_sigma)
|
||||
return sigma
|
||||
|
||||
def adjusted_step(self, sn, result, mcc, sigma_up):
|
||||
ss = self.ss
|
||||
if sn == ss.sigma_next:
|
||||
return sigma_up, result
|
||||
# FIXME: Make sure we're noising from the right sigma.
|
||||
result = yield from self.result(
|
||||
result, sigma_up, sigma=ss.sigma, sigma_next=sn, final=False
|
||||
)
|
||||
mr = self.call_model(result, sn, call_index=mcc)
|
||||
dt = ss.sigma_next - sn
|
||||
result = result + self.to_d(mr) * dt
|
||||
return sigma_up.new_zeros(1), result
|
||||
@@ -0,0 +1,546 @@
|
||||
import typing
|
||||
|
||||
import inspect
|
||||
import torch
|
||||
|
||||
import comfy
|
||||
|
||||
from .. import filtering
|
||||
from .. import expression as expr
|
||||
from ..utils import fallback
|
||||
from .base import (
|
||||
StepSamplerContext,
|
||||
SingleStepSampler,
|
||||
registry,
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
import pytorch_wavelets as ptwav
|
||||
|
||||
HAVE_WAVELETS = True
|
||||
except ImportError:
|
||||
HAVE_WAVELETS = False
|
||||
|
||||
|
||||
class DynamicStep(SingleStepSampler):
|
||||
name = "dynamic"
|
||||
sample_sigma_zero = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
dynamic = self.options.get("dynamic")
|
||||
if dynamic is None:
|
||||
raise ValueError(
|
||||
"Dynamic sampler type requires specifying dynamic block in text parameters"
|
||||
)
|
||||
if isinstance(dynamic, str):
|
||||
dynamic = ({"expression": dynamic},)
|
||||
elif not isinstance(dynamic, (tuple, list)):
|
||||
raise ValueError(
|
||||
"Bad type for dynamic block: must be string or list of objects"
|
||||
)
|
||||
elif len(dynamic) == 0:
|
||||
raise ValueError("Dynamic block as a list cannot be empty")
|
||||
dynresult = []
|
||||
for idx, item in enumerate(dynamic):
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError(
|
||||
f"Bad item in dynamic block at index {idx}: must be a dict"
|
||||
)
|
||||
dyn_when = item.get("when")
|
||||
if isinstance(dyn_when, str):
|
||||
dyn_when = expr.Expression(dyn_when)
|
||||
elif dyn_when is not None:
|
||||
raise ValueError(
|
||||
f"Unexpected type for when key in dynamic block at index {idx}, must be string or null/unset"
|
||||
)
|
||||
dyn_params = item.get("expression")
|
||||
if not isinstance(dyn_params, str):
|
||||
raise ValueError(
|
||||
f"Missing or incorrectly typed expression key for dynamic block at index {idx}: must be a string"
|
||||
)
|
||||
dynresult.append((dyn_when, expr.Expression(dyn_params)))
|
||||
self.dynamic = tuple(dynresult)
|
||||
|
||||
def step(self, x):
|
||||
sampler_params = None
|
||||
handlers = filtering.FILTER_HANDLERS.clone(constants=self.ss.refs)
|
||||
for idx, (dyn_when, dyn_params) in enumerate(self.dynamic):
|
||||
if dyn_when is not None and not bool(dyn_when.eval(handlers)):
|
||||
continue
|
||||
sampler_params = dyn_params.eval(handlers)
|
||||
if sampler_params is not None:
|
||||
break
|
||||
if sampler_params is None:
|
||||
raise RuntimeError(
|
||||
"Dynamic sampler could not find matching sampler: all expressions failed to return a result"
|
||||
)
|
||||
if not isinstance(sampler_params, dict):
|
||||
raise TypeError(
|
||||
f"Dynamic sampler expression must evaluate to a dict, got type {type(sampler_params)}"
|
||||
)
|
||||
if bool(sampler_params.get("dynamic_inherit")):
|
||||
copy_keys = (
|
||||
"s_noise",
|
||||
"eta",
|
||||
"pre_filter",
|
||||
"post_filter",
|
||||
"immiscible",
|
||||
)
|
||||
opts = {k: getattr(self, k) for k in copy_keys}
|
||||
else:
|
||||
opts = {}
|
||||
opts["custom_noise"] = self.custom_noise
|
||||
opts |= sampler_params
|
||||
opts |= {k: v for k, v in self.options.items() if k.startswith("custom_noise_")}
|
||||
# print("\n\nDYN OPTS", opts)
|
||||
step_method = opts.get("step_method", "default")
|
||||
sampler_class = registry.STEP_SAMPLER_SIMPLE_NAMES.get(step_method)
|
||||
if sampler_class is None:
|
||||
raise ValueError(f"Unknown step method {step_method} in dynamic sampler")
|
||||
sampler = sampler_class(**opts)
|
||||
with StepSamplerContext(sampler, self.ss) as sampler:
|
||||
yield from sampler.step(x)
|
||||
|
||||
|
||||
class AdapterStep(SingleStepSampler):
|
||||
name = "adapter"
|
||||
model_calls = 2
|
||||
immiscible = False
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.external_sampler = self.options.pop(
|
||||
"SAMPLER", comfy.samplers.sampler_object("euler")
|
||||
)
|
||||
sig = inspect.signature(self.external_sampler.sampler_function)
|
||||
self.external_sampler_options = {
|
||||
k: v
|
||||
for k, v in self.options.pop("external_sampler", {}).items()
|
||||
if k in sig.parameters
|
||||
}
|
||||
self.external_sampler_uses_noise = "noise_sampler" in sig.parameters
|
||||
self.ancestralize = self.options.pop("ancestralize", self.ancestralize) is True
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigmas = ss.sigmas[ss.idx : ss.idx + 2]
|
||||
kwargs = {
|
||||
"callback": None,
|
||||
"disable": True,
|
||||
"extra_args": {"seed": ss.noise.seed + ss.noise.seed_offset},
|
||||
} | self.external_sampler_options
|
||||
if self.external_sampler_uses_noise:
|
||||
kwargs["noise_sampler"] = ss.noise.make_caching_noise_sampler(
|
||||
self.options.get("custom_noise"),
|
||||
1,
|
||||
sigmas[-1],
|
||||
sigmas[0],
|
||||
immiscible=fallback(self.immiscible, ss.noise.immiscible),
|
||||
)
|
||||
|
||||
mcc = 1
|
||||
|
||||
def model_wrapper(x_, sigma_, *args, **kwargs):
|
||||
nonlocal mcc
|
||||
if torch.equal(x_, x) and sigma_ == ss.sigma:
|
||||
return ss.hcur.denoised.clone()
|
||||
mr = self.call_model(x_, sigma_, *args, call_index=mcc, **kwargs)
|
||||
mcc += 1
|
||||
return mr.denoised.clone()
|
||||
|
||||
result = self.external_sampler.sampler_function(
|
||||
model_wrapper, x.clone(), sigmas, **kwargs
|
||||
)
|
||||
yield from self.result(result, ss.sigma.new_zeros(1))
|
||||
|
||||
|
||||
class CycleSingleStepSampler(SingleStepSampler):
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(self, *, cycle_pct=0.25, cycle_adjust_scales=True, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
if cycle_pct < 0:
|
||||
raise ValueError("cycle_pct must be positive")
|
||||
self.cycle_pct = cycle_pct
|
||||
self.cycle_adjust_scales = cycle_adjust_scales
|
||||
|
||||
def get_cycle_scales(self, sigma_next):
|
||||
keep_scale = 1 - self.cycle_pct
|
||||
if not self.cycle_adjust_scales:
|
||||
return keep_scale, self.cycle_pct
|
||||
add_scale = ((sigma_next**2.0 - (keep_scale * sigma_next) ** 2.0) ** 0.5) * (
|
||||
0.95 + 0.25 * self.cycle_pct
|
||||
)
|
||||
# print(f">> keep={keep_scale}, add={add_scale}")
|
||||
return keep_scale, add_scale
|
||||
|
||||
|
||||
class EulerCycleStep(CycleSingleStepSampler):
|
||||
name = "blep_euler_cycle"
|
||||
allow_alt_cfgpp = True
|
||||
allow_cfgpp = True
|
||||
|
||||
def step(self, x):
|
||||
sigma_next = self.ss.sigma_next
|
||||
denoised_pred, d = self.get_split_prediction()
|
||||
keep_scale, add_scale = self.get_cycle_scales(sigma_next)
|
||||
return (
|
||||
yield from self.split_result(
|
||||
denoised_pred, d * keep_scale, sigma_up=add_scale, sigma_down=sigma_next
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class TrapezoidalCycleStep(CycleSingleStepSampler):
|
||||
name = "blep_trapezoidal_cycle"
|
||||
model_calls = 1
|
||||
allow_alt_cfgpp = False
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
blend_mode = self.options.get("blend_mode", "lerp").strip()
|
||||
self.blend = (
|
||||
filtering.BLENDING_MODES[blend_mode] if blend_mode != "lerp" else torch.lerp
|
||||
)
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
ratio = sigma_next / sigma
|
||||
dratio = 1 - (sigma / sigma_next) * 0.5
|
||||
|
||||
# Denoised sample at the next sigma
|
||||
mr_next = self.call_model(
|
||||
self.blend(ss.denoised, x, ratio),
|
||||
ss.sigma_next,
|
||||
call_index=1,
|
||||
)
|
||||
|
||||
keep_scale, add_scale = self.get_cycle_scales(ss.sigma_next)
|
||||
|
||||
denoised_prime = self.blend(mr_next.denoised, ss.denoised, dratio)
|
||||
noise_pred = (x - denoised_prime).mul_(ratio * keep_scale)
|
||||
|
||||
yield from self.result(
|
||||
denoised_prime.add_(noise_pred), add_scale, sigma_down=sigma_next
|
||||
)
|
||||
|
||||
|
||||
class BASConfig(typing.NamedTuple):
|
||||
batch_multiplier: int = 2
|
||||
start_step: int = 0
|
||||
end_step: int = 3
|
||||
s_noise: float = 1.0
|
||||
eta: float = 0.0
|
||||
eta_retry_increment: float = 0
|
||||
denoised_factors: list | tuple | None = None
|
||||
denoised_factors_scale: float = 1.0
|
||||
denoised_multiplier: float = 1.0
|
||||
renoise_mode: str = "restart"
|
||||
fromstep_factor: float = 1.0
|
||||
tostep_factor: float = 1.0
|
||||
tostep_source: str = "dt"
|
||||
|
||||
|
||||
# Batch augmented sampler
|
||||
class BASStep(SingleStepSampler):
|
||||
name = "blep_bas"
|
||||
model_calls = -1
|
||||
uses_alt_noise = True
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
bas = self.bas = BASConfig(**self.options.get("bas", {}))
|
||||
if bas.renoise_mode not in {"restart", "restart_noneta", "simple"}:
|
||||
raise ValueError("Bad BAS renoise mode")
|
||||
if bas.tostep_source not in {"dt", "sigma", "sigma_next"}:
|
||||
raise ValueError("Bad BAS tostep_source")
|
||||
blend_mode = self.options.get("blend_mode", "lerp").strip()
|
||||
self.blend = (
|
||||
filtering.BLENDING_MODES[blend_mode] if blend_mode != "lerp" else torch.lerp
|
||||
)
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
bas = self.bas
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
eta = self.get_dyn_eta()
|
||||
sigma_down, sigma_up = self.get_ancestral_step(eta)
|
||||
denoised = ss.denoised
|
||||
ratio = sigma_down / sigma
|
||||
if (
|
||||
ss.step >= bas.end_step
|
||||
or ss.step < bas.start_step
|
||||
or bas.batch_multiplier < 1
|
||||
):
|
||||
return (yield from self.result(self.blend(denoised, x, ratio), sigma_up))
|
||||
bsigma = sigma * bas.fromstep_factor
|
||||
if bas.tostep_source == "sigma":
|
||||
bsigma_next = sigma * bas.tostep_factor
|
||||
elif bas.tostep_source == "sigma_next":
|
||||
bsigma_next = sigma_next * bas.tostep_factor
|
||||
elif bas.tostep_source == "dt":
|
||||
bsigma_next = bsigma + (sigma_next - bsigma) * bas.tostep_factor
|
||||
else:
|
||||
raise RuntimeError("Impossible BAS tostep_source")
|
||||
if bsigma <= bsigma_next:
|
||||
raise ValueError("BAS: Bad configuration, got sigma <= sigma_next")
|
||||
bsigma_down, bsigma_up = self.get_ancestral_step(
|
||||
bas.eta,
|
||||
sigma=bsigma,
|
||||
sigma_next=bsigma_next,
|
||||
retry_increment=bas.eta_retry_increment,
|
||||
)
|
||||
bratio = bsigma_down / bsigma
|
||||
x_new = self.blend(denoised, x, bratio)
|
||||
batch_factor = bas.batch_multiplier
|
||||
if bas.denoised_factors is None:
|
||||
dn_factors = (bas.denoised_factors_scale / (batch_factor + 1),) * (
|
||||
batch_factor + 1
|
||||
)
|
||||
dn_sum = bas.denoised_factors_scale
|
||||
else:
|
||||
dn_factors = tuple(bas.denoised_factors)[: batch_factor + 1]
|
||||
tooshort = (batch_factor + 1) - len(dn_factors)
|
||||
if tooshort > 0:
|
||||
dn_factors = dn_factors + (dn_factors[-1],) * tooshort
|
||||
if len(dn_factors) != batch_factor + 1:
|
||||
raise ValueError("Bad length for bas_denoised_factors")
|
||||
dn_sum = sum(dn_factors)
|
||||
if bas.denoised_factors_scale != 0:
|
||||
dn_factors = tuple(
|
||||
(f / dn_sum) * bas.denoised_factors_scale for f in dn_factors
|
||||
)
|
||||
# print(
|
||||
# f"\nBAS STEP: step {bsigma} -> {bsigma_next} : down={bsigma_down}, up={bsigma_up}, bratio={bratio}, dn_factors={dn_factors}"
|
||||
# )
|
||||
if dn_sum == 0:
|
||||
raise ValueError("bas_denoised_factors must sum to a non-zero quantity")
|
||||
batch_size = x.shape[0]
|
||||
expanded_batch = batch_size * batch_factor
|
||||
x_expanded = x.new_zeros(expanded_batch, *x.shape[1:])
|
||||
renoise_mode = bas.renoise_mode
|
||||
if renoise_mode == "restart":
|
||||
noise_factor = (bsigma**2 - bsigma_down**2) ** 0.5
|
||||
elif renoise_mode == "restart_noneta":
|
||||
noise_factor = bsigma_up + (bsigma**2 - bsigma_next**2) ** 0.5
|
||||
else:
|
||||
noise_factor = bsigma_up + (bsigma - bsigma_next)
|
||||
for bidx in range(batch_factor):
|
||||
# print(
|
||||
# f"NOISE ITER {bidx} -- {bidx * batch_size} -> {bidx * batch_size + batch_size}"
|
||||
# )
|
||||
x_expanded[
|
||||
bidx * batch_size : bidx * batch_size + batch_size
|
||||
] = yield from self.result(
|
||||
x_new,
|
||||
noise_factor,
|
||||
sigma=bsigma,
|
||||
sigma_down=bsigma_down,
|
||||
s_noise=bas.s_noise,
|
||||
noise_sampler=self.alt_noise_sampler,
|
||||
final=False,
|
||||
)
|
||||
s_in = x.new_ones(expanded_batch)
|
||||
del x_new
|
||||
mr_expanded = self.call_model(x_expanded, bsigma, s_in=s_in, call_index=1)
|
||||
denoised_expanded = mr_expanded.denoised
|
||||
denoised_new = torch.zeros_like(denoised)
|
||||
for obidx in range(batch_size):
|
||||
for bidx in range(-1, batch_factor):
|
||||
# print(f"DN ITER {obidx} <{bidx}> = dn_exp[{bidx * batch_size + obidx}]")
|
||||
dn_curr = (
|
||||
denoised[obidx]
|
||||
if bidx == -1
|
||||
else denoised_expanded[bidx * batch_size + obidx]
|
||||
)
|
||||
denoised_new[obidx] += dn_curr * dn_factors[bidx + 1]
|
||||
denoised_new *= bas.denoised_multiplier
|
||||
result = self.blend(denoised_new, x, ratio)
|
||||
yield from self.result(result, sigma_up)
|
||||
|
||||
|
||||
def scale_wavelets(waves, factor_yl, factor_yh=None):
|
||||
factor_yh = fallback(factor_yh, factor_yl)
|
||||
if factor_yl == 1 and factor_yh == 1:
|
||||
return waves
|
||||
return (waves[0] * factor_yl, tuple(t * factor_yh for t in waves[1]))
|
||||
|
||||
|
||||
def blend_wavelets(a, b, *, factor_yl, factor_yh, blend_yl, blend_yh=None):
|
||||
blend_yh = fallback(blend_yh, blend_yl)
|
||||
if not isinstance(factor_yl, torch.Tensor):
|
||||
factor_yl = a[0].new_full((1,), factor_yl)
|
||||
if not isinstance(factor_yh, torch.Tensor):
|
||||
factor_yh = a[0].new_full((1,), factor_yh)
|
||||
return (
|
||||
blend_yl(a[0], b[0], factor_yl),
|
||||
tuple(blend_yh(ta, tb, factor_yh) for ta, tb in zip(a[1], b[1])),
|
||||
)
|
||||
|
||||
|
||||
class WeoonConfig(typing.NamedTuple):
|
||||
start_step: int = 0
|
||||
end_step: int = 9999
|
||||
eta: float = 0.0
|
||||
eta_retry_increment: float = 0.0
|
||||
s_noise: float = 1.0
|
||||
# One of dwt, dwt1d, dtcwt
|
||||
wavelet_mode: str = "dwt"
|
||||
padding: str = "periodization"
|
||||
inv_padding: str | None = None
|
||||
level: int = 3
|
||||
wave: str = "db4"
|
||||
inv_wave: str | None = None
|
||||
dtcwt_qshift: str = "qshift_a"
|
||||
dtcwt_biort: str = "near_sym_a"
|
||||
dtcwt_inv_qshift: str | None = None
|
||||
dtcwt_inv_biort: str | None = None
|
||||
downstep_scale: float = 1.0
|
||||
yl_strength: float = 1.0
|
||||
yh_strength: float = 0.5
|
||||
wavelet_blend_mode: str = "lerp"
|
||||
wavelet_blend_mode_yh: str | None = None
|
||||
denoised_yl_multiplier: float = 1.0
|
||||
denoised_yh_multiplier: float = 1.0
|
||||
denoised_down_yl_multiplier: float = 1.0
|
||||
denoised_down_yh_multiplier: float = 1.0
|
||||
flatten_start_dim: int = 2
|
||||
|
||||
|
||||
class WeoonStep(SingleStepSampler):
|
||||
name = "blep_weoon"
|
||||
model_calls = 1
|
||||
uses_alt_noise = True
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
if not HAVE_WAVELETS:
|
||||
raise RuntimeError(
|
||||
"Wavelet sampling requires the pytorch_wavelets package installed in your environment",
|
||||
)
|
||||
super().__init__(**kwargs)
|
||||
w = self.weoon = WeoonConfig(**self.options.get("weoon", {}))
|
||||
blend_mode = self.options.get("blend_mode", "lerp").strip()
|
||||
self.blend = (
|
||||
filtering.BLENDING_MODES[blend_mode] if blend_mode != "lerp" else torch.lerp
|
||||
)
|
||||
self.wavelet_blend = (
|
||||
filtering.BLENDING_MODES[w.wavelet_blend_mode]
|
||||
if w.wavelet_blend_mode != "lerp"
|
||||
else torch.lerp
|
||||
)
|
||||
if w.wavelet_blend_mode_yh is None:
|
||||
self.wavelet_blend_yh = self.wavelet_blend
|
||||
else:
|
||||
self.wavelet_blend_yh = (
|
||||
filtering.BLENDING_MODES[w.wavelet_blend_mode_yh]
|
||||
if w.wavelet_blend_mode_yh != "lerp"
|
||||
else torch.lerp
|
||||
)
|
||||
if not (0 <= w.flatten_start_dim <= 2):
|
||||
raise ValueError("Bad flatten_start_dim in Weoon sampler")
|
||||
if w.wavelet_mode == "dtcwt":
|
||||
self.wavelet_forward = ptwav.DTCWTForward(
|
||||
J=w.level, mode=w.padding, biort=w.dtcwt_biort, qshift=w.dtcwt_qshift
|
||||
)
|
||||
self.wavelet_inverse = ptwav.DTCWTInverse(
|
||||
mode=fallback(w.inv_padding, w.padding),
|
||||
biort=fallback(w.dtcwt_inv_biort, w.dtcwt_biort),
|
||||
qshift=fallback(w.dtcwt_inv_qshift, w.dtcwt_qshift),
|
||||
)
|
||||
elif w.wavelet_mode == "dwt":
|
||||
self.wavelet_forward = ptwav.DWTForward(
|
||||
J=w.level, wave=w.wave, mode=w.padding
|
||||
)
|
||||
self.wavelet_inverse = ptwav.DWTInverse(
|
||||
wave=fallback(w.inv_wave, w.wave),
|
||||
mode=fallback(w.inv_padding, w.padding),
|
||||
)
|
||||
elif w.wavelet_mode == "dwt1d":
|
||||
self.wavelet_forward = ptwav.DWT1DForward(
|
||||
J=w.level, wave=w.wave, mode=w.padding
|
||||
)
|
||||
self.wavelet_inverse = ptwav.DWT1DInverse(
|
||||
wave=fallback(w.inv_wave, w.wave),
|
||||
mode=fallback(w.inv_padding, w.padding),
|
||||
)
|
||||
|
||||
def maybe_flatten(self, tensor: torch.Tensor) -> torch.Tensor:
|
||||
w = self.weoon
|
||||
need_flatten = w.wavelet_mode == "dwt1d"
|
||||
if not need_flatten:
|
||||
return tensor
|
||||
start_dim = w.flatten_start_dim
|
||||
tensor = tensor.flatten(start_dim=start_dim)
|
||||
if start_dim == 0:
|
||||
return tensor[None, None, ...]
|
||||
if start_dim == 1:
|
||||
return tensor[:, None, ...]
|
||||
return tensor
|
||||
|
||||
def step(self, x):
|
||||
w = self.weoon
|
||||
ss = self.ss
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
ratio = sigma_down / sigma
|
||||
if not w.start_step <= ss.step <= w.end_step:
|
||||
return (yield from self.result(self.blend(ss.denoised, x, ratio), sigma_up))
|
||||
self.wavelet_forward.to(x)
|
||||
self.wavelet_inverse.to(x)
|
||||
dt = sigma_next - sigma
|
||||
wsigma_next = (sigma + dt * w.downstep_scale).clamp_(0)
|
||||
wsigma_down, wsigma_up = self.get_ancestral_step(
|
||||
w.eta,
|
||||
sigma=sigma,
|
||||
sigma_next=wsigma_next,
|
||||
retry_increment=w.eta_retry_increment,
|
||||
)
|
||||
wratio = wsigma_down / sigma
|
||||
x_down = self.blend(ss.denoised, x, wratio)
|
||||
if wsigma_up != 0:
|
||||
x_down = yield from self.result(
|
||||
x_down,
|
||||
wsigma_up,
|
||||
sigma_next=wsigma_next,
|
||||
sigma_down=wsigma_down,
|
||||
s_noise=w.s_noise,
|
||||
noise_sampler=self.alt_noise_sampler,
|
||||
final=False,
|
||||
)
|
||||
mr_down = self.call_model(x_down, wsigma_next, call_index=1)
|
||||
coeffs = scale_wavelets(
|
||||
self.wavelet_forward(self.maybe_flatten(ss.denoised)),
|
||||
factor_yl=w.denoised_yl_multiplier,
|
||||
factor_yh=w.denoised_yh_multiplier,
|
||||
)
|
||||
coeffs_down = scale_wavelets(
|
||||
self.wavelet_forward(self.maybe_flatten(mr_down.denoised)),
|
||||
factor_yl=w.denoised_down_yl_multiplier,
|
||||
factor_yh=w.denoised_down_yh_multiplier,
|
||||
)
|
||||
coeffs_out = blend_wavelets(
|
||||
coeffs,
|
||||
coeffs_down,
|
||||
factor_yl=w.yl_strength,
|
||||
factor_yh=w.yh_strength,
|
||||
blend_yl=self.wavelet_blend,
|
||||
blend_yh=self.wavelet_blend_yh,
|
||||
)
|
||||
denoised_new = self.wavelet_inverse(coeffs_out)
|
||||
if denoised_new.shape != x.shape:
|
||||
denoised_new = denoised_new.reshape(*x.shape)
|
||||
x = self.blend(denoised_new, x, ratio)
|
||||
yield from self.result(x, sigma_up)
|
||||
|
||||
|
||||
registry.add(
|
||||
BASStep,
|
||||
DynamicStep,
|
||||
AdapterStep,
|
||||
EulerCycleStep,
|
||||
TrapezoidalCycleStep,
|
||||
WeoonStep,
|
||||
)
|
||||
@@ -0,0 +1,541 @@
|
||||
import torch
|
||||
|
||||
import comfy
|
||||
from comfy.k_diffusion.sampling import get_ancestral_step
|
||||
|
||||
from .base import (
|
||||
SingleStepSampler,
|
||||
DPMPPStepMixin,
|
||||
HistorySingleStepSampler,
|
||||
ReversibleSingleStepSampler,
|
||||
registry,
|
||||
)
|
||||
|
||||
|
||||
class EulerStep(SingleStepSampler):
|
||||
name = "euler"
|
||||
allow_cfgpp = True
|
||||
allow_alt_cfgpp = True
|
||||
step = SingleStepSampler.euler_step
|
||||
|
||||
|
||||
class DPMPP2MStep(HistorySingleStepSampler, DPMPPStepMixin):
|
||||
name = "dpmpp_2m"
|
||||
default_history_limit, max_history = 1, 1
|
||||
ancestralize = True
|
||||
default_eta = 0.0
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
s, sn = ss.sigma, ss.sigma_next
|
||||
t, t_next = self.t_fn(s), self.t_fn(sn)
|
||||
h = t_next - t
|
||||
st, st_next = self.sigma_fn(t), self.sigma_fn(t_next)
|
||||
if self.available_history() > 0:
|
||||
h_last = t - self.t_fn(ss.sigma_prev)
|
||||
r = h_last / h
|
||||
denoised, old_denoised = ss.denoised, ss.hprev.denoised
|
||||
denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised
|
||||
else:
|
||||
denoised_d = ss.denoised
|
||||
yield from self.result((st_next / st) * x - (-h).expm1() * denoised_d)
|
||||
|
||||
|
||||
class DPMPP2MSDEStep(ReversibleSingleStepSampler):
|
||||
name = "dpmpp_2m_sde"
|
||||
default_history_limit, max_history = 1, 1
|
||||
default_reversible_scale = 0.0
|
||||
|
||||
def __init__(self, *, solver_type="midpoint", **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
solver_type = solver_type.lower().strip()
|
||||
if solver_type not in ("midpoint", "heun"):
|
||||
raise ValueError("Bad solver_type: must be one of midpoint, heun")
|
||||
self.solver_type = solver_type
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
denoised = ss.denoised
|
||||
# DPM-Solver++(2M) SDE
|
||||
t, s = -sigma.log(), -sigma_next.log()
|
||||
h = s - t
|
||||
eta_h = self.get_dyn_eta() * h
|
||||
ratio = sigma_next / sigma
|
||||
x = ((ratio * (-eta_h).exp()) * x).add_((-h - eta_h).expm1().neg() * denoised)
|
||||
noise_strength = sigma_next * (-2 * eta_h).expm1().neg().sqrt()
|
||||
if self.available_history() == 0:
|
||||
return (yield from self.result(x, noise_strength))
|
||||
sigma_prev, old_denoised = ss.hprev.sigma, ss.hprev.denoised
|
||||
h_last = (-sigma.log()) - (-sigma_prev.log())
|
||||
r = h_last / h
|
||||
if self.solver_type == "midpoint":
|
||||
multiplier = 0.5 * (-h - eta_h).expm1().neg()
|
||||
else:
|
||||
multiplier = (-h - eta_h).expm1().neg() / (-h - eta_h) + 1
|
||||
reta, reversible_scale = self.get_reversible_cfg()
|
||||
if reversible_scale != 0:
|
||||
multiplier *= 0.5
|
||||
x += (denoised - old_denoised).mul_((1 / r) * multiplier)
|
||||
if reversible_scale != 0:
|
||||
reta_h = reta * h
|
||||
if self.solver_type == "midpoint":
|
||||
rmultiplier = 0.5 * (-h - reta_h).expm1().neg()
|
||||
else:
|
||||
rmultiplier = (-h - reta_h).expm1().neg() / (-h - reta_h) + 1
|
||||
rmultiplier = ((1 / r) * (rmultiplier**2 / 2)) * reversible_scale
|
||||
x -= (old_denoised - denoised).mul_(rmultiplier)
|
||||
yield from self.result(x, noise_strength)
|
||||
|
||||
|
||||
class DPMPP3MSDEStep(HistorySingleStepSampler):
|
||||
name = "dpmpp_3m_sde"
|
||||
default_history_limit, max_history = 2, 2
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
denoised = ss.denoised
|
||||
t, s = -ss.sigma.log(), -ss.sigma_next.log()
|
||||
h = s - t
|
||||
eta = self.get_dyn_eta()
|
||||
h_eta = h * (eta + 1)
|
||||
x = torch.exp(-h_eta) * x + (-h_eta).expm1().neg() * denoised
|
||||
noise_strength = ss.sigma_next * (-2 * h * eta).expm1().neg().sqrt()
|
||||
ah = self.available_history()
|
||||
if ah == 0:
|
||||
return (yield from self.result(x, noise_strength))
|
||||
hist = ss.hist
|
||||
h_1 = (-ss.sigma.log()) - (-ss.sigma_prev.log())
|
||||
denoised_1 = hist[-2].denoised
|
||||
if ah == 1:
|
||||
r = h_1 / h
|
||||
d = (denoised - denoised_1) / r
|
||||
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
||||
x = x + phi_2 * d
|
||||
else: # 2+ history items available
|
||||
h_2 = (-ss.sigma_prev.log()) - (-ss.sigmas[ss.idx - 2].log())
|
||||
denoised_2 = hist[-3].denoised
|
||||
r0 = h_1 / h
|
||||
r1 = h_2 / h
|
||||
d1_0 = (denoised - denoised_1) / r0
|
||||
d1_1 = (denoised_1 - denoised_2) / r1
|
||||
d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)
|
||||
d2 = (d1_0 - d1_1) / (r0 + r1)
|
||||
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
||||
phi_3 = phi_2 / h_eta - 0.5
|
||||
x = x + phi_2 * d1 - phi_3 * d2
|
||||
yield from self.result(x, noise_strength)
|
||||
|
||||
def step_(self, x):
|
||||
sr = next(super().step(x))
|
||||
if self.available_history() < 2:
|
||||
yield sr
|
||||
return
|
||||
ss = self.ss
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
hprev = ss.hist[-2]
|
||||
hprevprev = ss.hist[-3]
|
||||
t, s = -sigma.log(), -sigma_next.log()
|
||||
h = s - t
|
||||
eta = self.get_dyn_eta()
|
||||
h_eta = h * (eta + 1)
|
||||
h_2 = (-ss.sigma_prev.log()) - (-hprevprev.sigma.log())
|
||||
denoised = ss.denoised
|
||||
denoised_1 = hprev.denoised
|
||||
denoised_2 = hprevprev.denoised
|
||||
h_1 = (-ss.sigma.log()) - (-hprev.sigma.log())
|
||||
r0 = h_1 / h
|
||||
r1 = h_2 / h
|
||||
d1_0 = (denoised - denoised_1).div_(r0)
|
||||
d1_1 = (denoised_1 - denoised_2).div_(r1)
|
||||
d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)
|
||||
d2 = (d1_0 - d1_1).div_(r0 + r1)
|
||||
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
||||
phi_3 = phi_2 / h_eta - 0.5
|
||||
sr.x_ += phi_2 * d1 - phi_3 * d2
|
||||
yield sr
|
||||
# x = x + phi_2 * d1 - phi_3 * d2
|
||||
# yield from self.result(sr.x + phi_2 * d1 - phi_3 * d2, sr.sigma_up)
|
||||
|
||||
|
||||
# Alt CFG++ approach referenced from https://github.com/comfyanonymous/ComfyUI/pull/3871 - thanks!
|
||||
class DPMPP2SStep(SingleStepSampler, DPMPPStepMixin):
|
||||
name = "dpmpp_2s"
|
||||
model_calls = 1
|
||||
allow_alt_cfgpp = True
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
t_fn, sigma_fn = self.t_fn, self.sigma_fn
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
# DPM-Solver++(2S)
|
||||
t, t_next = t_fn(ss.sigma), t_fn(sigma_down)
|
||||
r = 1 / 2
|
||||
h = t_next - t
|
||||
s = t + r * h
|
||||
eff_x = (
|
||||
x
|
||||
if self.alt_cfgpp_scale == 0 or ss.hcur.denoised_uncond is None
|
||||
else x + (ss.denoised - ss.hcur.denoised_uncond) * self.alt_cfgpp_scale
|
||||
)
|
||||
x_2 = (sigma_fn(s) / sigma_fn(t)) * eff_x - (-h * r).expm1() * ss.denoised
|
||||
denoised_2 = self.call_model(x_2, sigma_fn(s), call_index=1).denoised
|
||||
x = (sigma_fn(t_next) / sigma_fn(t)) * eff_x - (-h).expm1() * denoised_2
|
||||
yield from self.result(x, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
class DPMPPSDEStep(SingleStepSampler, DPMPPStepMixin):
|
||||
name = "dpmpp_sde"
|
||||
self_noise = 1
|
||||
model_calls = 1
|
||||
allow_alt_cfgpp = True # Implementation may not be correct.
|
||||
uses_alt_noise = True
|
||||
|
||||
def __init__(self, *args, r=1 / 2, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.r = r
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
t_fn, sigma_fn = self.t_fn, self.sigma_fn
|
||||
r, eta = self.r, self.get_dyn_eta()
|
||||
# DPM-Solver++
|
||||
t, t_next = t_fn(ss.sigma), t_fn(ss.sigma_next)
|
||||
h = t_next - t
|
||||
s = t + h * r
|
||||
fac = 1 / (2 * r)
|
||||
|
||||
# Step 1
|
||||
sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(s), eta)
|
||||
s_ = t_fn(sd)
|
||||
eff_x = (
|
||||
x
|
||||
if self.alt_cfgpp_scale == 0 or ss.hcur.denoised_uncond is None
|
||||
else x + (ss.denoised - ss.hcur.denoised_uncond) * self.alt_cfgpp_scale
|
||||
)
|
||||
x_2 = (sigma_fn(s_) / sigma_fn(t)) * eff_x - (t - s_).expm1() * ss.denoised
|
||||
x_2 = yield from self.result(
|
||||
x_2,
|
||||
su,
|
||||
sigma=sigma_fn(t),
|
||||
sigma_next=sigma_fn(s),
|
||||
noise_sampler=self.alt_noise_sampler,
|
||||
final=False,
|
||||
)
|
||||
denoised_2 = self.call_model(x_2, sigma_fn(s), call_index=1).denoised
|
||||
|
||||
# Step 2
|
||||
sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(t_next), eta)
|
||||
t_next_ = t_fn(sd)
|
||||
denoised_d = (1 - fac) * ss.denoised + fac * denoised_2
|
||||
x = (sigma_fn(t_next_) / sigma_fn(t)) * eff_x - (
|
||||
t - t_next_
|
||||
).expm1() * denoised_d
|
||||
yield from self.result(x, su, sigma_down=sd)
|
||||
|
||||
|
||||
# Adapted from https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py
|
||||
# under Apache 2 license
|
||||
class IPNDMStep(HistorySingleStepSampler):
|
||||
name = "ipndm"
|
||||
ancestralize = True
|
||||
default_history_limit, max_history = 1, 3
|
||||
allow_alt_cfgpp = True
|
||||
default_eta = 0.0
|
||||
|
||||
IPNDM_MULTIPLIERS = (
|
||||
((1,), 1),
|
||||
((3, -1), 2),
|
||||
((23, -16, 5), 12),
|
||||
((55, -59, 37, -9), 24),
|
||||
)
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
order = self.available_history() + 1
|
||||
if order > 1:
|
||||
hd = tuple(self.to_d(ss.hist[-hidx]) for hidx in range(order, 1, -1))
|
||||
(dm, *hms), divisor = self.IPNDM_MULTIPLIERS[order - 1]
|
||||
noise = dm * self.to_d(ss.hcur)
|
||||
for hidx, hm in enumerate(hms, start=1):
|
||||
noise += hm * hd[-hidx]
|
||||
noise /= divisor
|
||||
yield from self.result(x + ss.dt * noise)
|
||||
|
||||
|
||||
# Adapted from https://github.com/zju-pi/diff-sampler/blob/main/diff-solvers-main/solvers.py
|
||||
# under Apache 2 license
|
||||
class IPNDMVStep(HistorySingleStepSampler):
|
||||
name = "ipndm_v"
|
||||
ancestralize = True
|
||||
default_history_limit, max_history = 1, 3
|
||||
allow_alt_cfgpp = True
|
||||
default_eta = 0.0
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
dt = ss.dt
|
||||
d = self.to_d(ss.hcur)
|
||||
order = self.available_history() + 1
|
||||
if order > 1:
|
||||
hd = tuple(self.to_d(ss.hist[-hidx]) for hidx in range(order, 1, -1))
|
||||
hns = (
|
||||
ss.sigmas[ss.idx - (order - 2) : ss.idx + 1]
|
||||
- ss.sigmas[ss.idx - (order - 1) : ss.idx]
|
||||
)
|
||||
if order == 1:
|
||||
noise = d
|
||||
elif order == 2:
|
||||
coeff1 = (2 + (dt / hns[-1])) / 2
|
||||
coeff2 = -(dt / hns[-1]) / 2
|
||||
noise = coeff1 * d + coeff2 * hd[-1]
|
||||
elif order == 3:
|
||||
temp = (
|
||||
1
|
||||
- dt
|
||||
/ (3 * (dt + hns[-1]))
|
||||
* (dt * (dt + hns[-1]))
|
||||
/ (hns[-1] * (hns[-1] + hns[-2]))
|
||||
) / 2
|
||||
coeff1 = (2 + (dt / hns[-1])) / 2 + temp
|
||||
coeff2 = -(dt / hns[-1]) / 2 - (1 + hns[-1] / hns[-2]) * temp
|
||||
coeff3 = temp * hns[-1] / hns[-2]
|
||||
noise = coeff1 * d + coeff2 * hd[-1] + coeff3 * hd[-2]
|
||||
else:
|
||||
temp1 = (
|
||||
1
|
||||
- dt
|
||||
/ (3 * (dt + hns[-1]))
|
||||
* (dt * (dt + hns[-1]))
|
||||
/ (hns[-1] * (hns[-1] + hns[-2]))
|
||||
) / 2
|
||||
temp2 = (
|
||||
(
|
||||
(1 - dt / (3 * (dt + hns[-1]))) / 2
|
||||
+ (1 - dt / (2 * (dt + hns[-1])))
|
||||
* dt
|
||||
/ (6 * (dt + hns[-1] + hns[-2]))
|
||||
)
|
||||
* (dt * (dt + hns[-1]) * (dt + hns[-1] + hns[-2]))
|
||||
/ (hns[-1] * (hns[-1] + hns[-2]) * (hns[-1] + hns[-2] + hns[-3]))
|
||||
)
|
||||
coeff1 = (2 + (dt / hns[-1])) / 2 + temp1 + temp2
|
||||
coeff2 = (
|
||||
-(dt / hns[-1]) / 2
|
||||
- (1 + hns[-1] / hns[-2]) * temp1
|
||||
- (
|
||||
1
|
||||
+ (hns[-1] / hns[-2])
|
||||
+ (hns[-1] * (hns[-1] + hns[-2]) / (hns[-2] * (hns[-2] + hns[-3])))
|
||||
)
|
||||
* temp2
|
||||
)
|
||||
coeff3 = (
|
||||
temp1 * hns[-1] / hns[-2]
|
||||
+ (
|
||||
(hns[-1] / hns[-2])
|
||||
+ (hns[-1] * (hns[-1] + hns[-2]) / (hns[-2] * (hns[-2] + hns[-3])))
|
||||
* (1 + hns[-2] / hns[-3])
|
||||
)
|
||||
* temp2
|
||||
)
|
||||
coeff4 = (
|
||||
-temp2
|
||||
* (hns[-1] * (hns[-1] + hns[-2]) / (hns[-2] * (hns[-2] + hns[-3])))
|
||||
* hns[-1]
|
||||
/ hns[-2]
|
||||
)
|
||||
noise = coeff1 * d + coeff2 * hd[-1] + coeff3 * hd[-2] + coeff4 * hd[-3]
|
||||
yield from self.result(x + ss.dt * noise)
|
||||
|
||||
|
||||
class DEISStep(HistorySingleStepSampler):
|
||||
name = "deis"
|
||||
ancestralize = True
|
||||
default_history_limit, max_history = 1, 3
|
||||
allow_alt_cfgpp = True
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(self, *args, deis_mode="tab", **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.deis_mode = deis_mode
|
||||
self.deis_coeffs_key = None
|
||||
self.deis_coeffs = None
|
||||
|
||||
def get_deis_coeffs(self):
|
||||
ss = self.ss
|
||||
key = (
|
||||
self.history_limit,
|
||||
len(ss.sigmas),
|
||||
ss.sigmas[0].item(),
|
||||
ss.sigmas[-1].item(),
|
||||
)
|
||||
if self.deis_coeffs_key == key:
|
||||
return self.deis_coeffs
|
||||
self.deis_coeffs_key = key
|
||||
self.deis_coeffs = comfy.k_diffusion.deis.get_deis_coeff_list(
|
||||
ss.sigmas, self.history_limit + 1, deis_mode=self.deis_mode
|
||||
)
|
||||
return self.deis_coeffs
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
dt = ss.dt
|
||||
d = self.to_d(ss.hcur)
|
||||
order = self.available_history() + 1
|
||||
if order < 2:
|
||||
noise = dt * d # Euler
|
||||
else:
|
||||
c = self.get_deis_coeffs()[ss.idx]
|
||||
hd = tuple(self.to_d(ss.hist[-hidx]) for hidx in range(order, 1, -1))
|
||||
noise = c[0] * d
|
||||
for i in range(1, order):
|
||||
noise += c[i] * hd[-i]
|
||||
yield from self.result(x + noise)
|
||||
|
||||
|
||||
# https://openreview.net/pdf?id=o2ND9v0CeK
|
||||
# Implementation referenced from ComfyUI
|
||||
class GradientEstimationStep(HistorySingleStepSampler):
|
||||
name = "gradient_estimation"
|
||||
ancestralize = False
|
||||
default_history_limit, max_history = 1, 1
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(self, *args, ge_gamma=2.0, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.ge_gamma = ge_gamma
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
dt = sigma_down - ss.sigma
|
||||
d = self.to_d(ss.hcur)
|
||||
if self.available_history() < 1:
|
||||
noise_pred = dt * d # Euler
|
||||
else:
|
||||
gamma = self.ge_gamma
|
||||
noise_pred = dt * (gamma * d + (1 - gamma) * ss.hist[-2].d)
|
||||
yield from self.result(x + noise_pred, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
class HeunPP2Step(SingleStepSampler):
|
||||
name = "heunpp2"
|
||||
ancestralize = True
|
||||
model_calls = 2
|
||||
allow_alt_cfgpp = True
|
||||
|
||||
def __init__(self, *args, max_order=3, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.max_order = max(1, min(self.model_calls + 1, max_order))
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
steps_remain = max(0, len(ss.sigmas) - (ss.idx + 2))
|
||||
order = min(self.max_order, steps_remain + 1)
|
||||
sn = ss.sigma_next
|
||||
if order == 1:
|
||||
return (yield from self.euler_step(x))
|
||||
d = self.to_d(ss.hcur)
|
||||
dt = ss.dt
|
||||
w = order * ss.sigma
|
||||
w2 = sn / w
|
||||
x_2 = x + d * dt
|
||||
d_2 = self.to_d(self.call_model(x_2, sn, call_index=1))
|
||||
if order == 2:
|
||||
# Heun's method (ish)
|
||||
w1 = 1 - w2
|
||||
d_prime = d * w1 + d_2 * w2
|
||||
else:
|
||||
# Heun++ (ish)
|
||||
snn = ss.sigmas[ss.idx + 2]
|
||||
dt_2 = snn - sn
|
||||
x_3 = x_2 + d_2 * dt_2
|
||||
d_3 = self.to_d(self.call_model(x_3, snn, call_index=2))
|
||||
w3 = snn / w
|
||||
w1 = 1 - w2 - w3
|
||||
d_prime = w1 * d + w2 * d_2 + w3 * d_3
|
||||
yield from self.result(x + d_prime * dt)
|
||||
|
||||
|
||||
# Referenced from ComfyUI implementation
|
||||
class DPM2Step(SingleStepSampler):
|
||||
name = "dpm_2"
|
||||
model_calls = 1
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
eta = self.get_dyn_eta()
|
||||
sigma_down, sigma_up = self.get_ancestral_step(eta)
|
||||
sigma_mid = sigma.log().lerp(sigma_next.log(), 0.5).exp()
|
||||
dt_1, dt_2 = sigma_mid - sigma, sigma_down - sigma
|
||||
d = self.to_d(ss.hcur)
|
||||
mr_2 = self.call_model(x + d * dt_1, sigma_mid, call_index=1)
|
||||
d_2 = self.to_d(mr_2)
|
||||
yield from self.result(x + d_2 * dt_2, sigma_up)
|
||||
|
||||
|
||||
# Referenced from ComfyUI implementation
|
||||
class RESMultistepStep(HistorySingleStepSampler, DPMPPStepMixin):
|
||||
name = "res_multistep"
|
||||
default_history_limit, max_history = 1, 1
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def phi1_fn(t: torch.Tensor) -> torch.Tensor:
|
||||
return t.expm1() / t
|
||||
|
||||
@classmethod
|
||||
def phi2_fn(cls, t: torch.Tensor) -> torch.Tensor:
|
||||
return (cls.phi1_fn(t) - 1.0) / t
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma = ss.sigma
|
||||
eta = self.get_dyn_eta()
|
||||
sigma_down, sigma_up = self.get_ancestral_step(eta)
|
||||
if self.available_history() == 0:
|
||||
dt = sigma_down - sigma
|
||||
d = self.to_d(ss.hcur)
|
||||
return (yield from self.result(x + dt * d, sigma_up, sigma_down=sigma_down))
|
||||
prev_mr = ss.hist[-2]
|
||||
prev_sigma_down = self.get_ancestral_step(
|
||||
sigma=prev_mr.sigma, sigma_next=sigma, eta=eta
|
||||
)[0]
|
||||
# Second order multistep method in https://arxiv.org/pdf/2308.02157
|
||||
t, t_old, t_next, t_prev = (
|
||||
self.t_fn(sigma),
|
||||
self.t_fn(prev_sigma_down),
|
||||
self.t_fn(sigma_down),
|
||||
self.t_fn(prev_mr.sigma),
|
||||
)
|
||||
h = t_next - t
|
||||
h_s = self.sigma_fn(h)
|
||||
c2 = (t_prev - t_old) / h
|
||||
|
||||
phi1_val, phi2_val = self.phi1_fn(-h), self.phi2_fn(-h)
|
||||
b1 = torch.nan_to_num(phi1_val - phi2_val / c2, nan=0.0)
|
||||
b2 = torch.nan_to_num(phi2_val / c2, nan=0.0)
|
||||
result = h_s * x + h * (b1 * ss.denoised + b2 * prev_mr.denoised)
|
||||
yield from self.result(result, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
registry.add(
|
||||
DEISStep,
|
||||
DPMPP2MSDEStep,
|
||||
DPMPP2MStep,
|
||||
DPMPP3MSDEStep,
|
||||
DPMPPSDEStep,
|
||||
EulerStep,
|
||||
HeunPP2Step,
|
||||
IPNDMStep,
|
||||
IPNDMVStep,
|
||||
GradientEstimationStep,
|
||||
DPM2Step,
|
||||
DPMPP2SStep,
|
||||
RESMultistepStep,
|
||||
)
|
||||
@@ -0,0 +1,755 @@
|
||||
# Samplers based on Clybius' designs, mostly from https://github.com/Clybius/ComfyUI-Extra-Samplers/
|
||||
|
||||
import math
|
||||
import torch
|
||||
|
||||
from comfy.k_diffusion.sampling import get_ancestral_step, to_d
|
||||
|
||||
from .base import SingleStepSampler, ReversibleConfig, ReversibleSingleStepSampler
|
||||
from .builtins import DPMPP2MSDEStep
|
||||
from . import res_support
|
||||
from . import registry
|
||||
|
||||
from .. import filtering
|
||||
from .. import utils
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
# Apparently the only difference between Heun and Trapezoidal is the first step using ETA or not.
|
||||
class ReversibleHeunStep(ReversibleSingleStepSampler):
|
||||
name = "reversible_heun"
|
||||
model_calls = 1
|
||||
allow_alt_cfgpp = True
|
||||
allow_cfgpp = True
|
||||
trapezoidal_mode = False
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
blend_mode = self.options.get("blend_mode", "lerp").strip()
|
||||
self.blend = (
|
||||
filtering.BLENDING_MODES[blend_mode] if blend_mode != "lerp" else torch.lerp
|
||||
)
|
||||
|
||||
def reversible_correction(self, d, d_next, dt_reversible):
|
||||
if dt_reversible == 0 or self.reversible.scale == 0:
|
||||
return None
|
||||
return d_next.sub_(d).div_(4).mul_(dt_reversible**2).mul_(self.reversible.scale)
|
||||
|
||||
def step_internal(self, x, *, history_mode=False):
|
||||
ss = self.ss
|
||||
history_mode = history_mode and self.available_history() > 0
|
||||
if not history_mode:
|
||||
mr_1, mr_2 = ss.hcur, None
|
||||
else:
|
||||
mr_1, mr_2 = ss.hprev, ss.hcur
|
||||
sigma = ss.sigma
|
||||
denoised, uncond = mr_1.denoised, mr_1.denoised_uncond
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
ratio = sigma_down / sigma
|
||||
dratio = 1 - (sigma / sigma_down) * 0.5
|
||||
if mr_2 is None:
|
||||
x_2 = self.step_mix(x, denoised, uncond, ratio, blend=self.blend)
|
||||
mr_2 = self.call_model(x_2, sigma_down, call_index=1)
|
||||
del x_2
|
||||
denoised_2, uncond_2 = mr_2.denoised, mr_2.denoised_uncond
|
||||
denoised_prime = self.blend(denoised_2, denoised, dratio)
|
||||
if self.cfgpp:
|
||||
denoised_prime += denoised * 0.5
|
||||
uncond_prime = (uncond_2 * (1 - dratio)).add_(uncond)
|
||||
elif self.alt_cfgpp_scale != 0:
|
||||
uncond_prime = self.blend(uncond_2, uncond, dratio)
|
||||
else:
|
||||
uncond_prime = uncond
|
||||
x = self.step_mix(x, denoised_prime, uncond_prime, ratio, blend=self.blend)
|
||||
if self.reversible.scale != 0:
|
||||
correction = self.reversible_correction(
|
||||
d=self.to_d(mr_1, use_cfgpp=self.reversible.use_cfgpp),
|
||||
d_next=self.to_d(mr_2, use_cfgpp=self.reversible.use_cfgpp),
|
||||
dt_reversible=self.get_ancestral_step(self.dyn_reta)[0] - sigma,
|
||||
)
|
||||
if correction is not None:
|
||||
x -= correction
|
||||
yield from self.result(x, sigma_up)
|
||||
|
||||
def step(self, x):
|
||||
return self.step_internal(x, history_mode=False)
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class ReversibleHeun1SStep(ReversibleHeunStep):
|
||||
name = "reversible_heun_1s"
|
||||
model_calls = (0, 1)
|
||||
default_history_limit, max_history = 1, 1
|
||||
allow_alt_cfgpp = True
|
||||
allow_cfgpp = True
|
||||
|
||||
def step(self, x):
|
||||
return self.step_internal(x, history_mode=True)
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class RESStep(SingleStepSampler):
|
||||
name = "res"
|
||||
model_calls = 1
|
||||
allow_alt_cfgpp = True # May not be implemented correctly.
|
||||
|
||||
def __init__(self, *, res_simple_phi=False, res_c2=0.5, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.simple_phi = res_simple_phi
|
||||
self.c2 = res_c2
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
eta = self.get_dyn_eta()
|
||||
sigma_down, sigma_up = self.get_ancestral_step(eta)
|
||||
denoised = ss.denoised
|
||||
lam_next = sigma_down.log().neg() if eta != 0 else ss.sigma_next.log().neg()
|
||||
lam = ss.sigma.log().neg()
|
||||
|
||||
h = lam_next - lam
|
||||
a2_1, b1, b2 = res_support._de_second_order(
|
||||
h=h, c2=self.c2, simple_phi_calc=self.simple_phi
|
||||
)
|
||||
|
||||
c2_h = 0.5 * h
|
||||
|
||||
eff_x = (
|
||||
x
|
||||
if self.alt_cfgpp_scale == 0 or ss.hcur.denoised_uncond is None
|
||||
else x + (ss.denoised - ss.hcur.denoised_uncond) * self.alt_cfgpp_scale
|
||||
)
|
||||
x_2 = math.exp(-c2_h) * eff_x + a2_1 * h * denoised
|
||||
lam_2 = lam + c2_h
|
||||
sigma_2 = lam_2.neg().exp()
|
||||
|
||||
denoised2 = self.call_model(x_2, sigma_2, call_index=1).denoised
|
||||
|
||||
x = math.exp(-h) * eff_x + h * (b1 * denoised + b2 * denoised2)
|
||||
yield from self.result(x, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
class TrapezoidalStep(ReversibleHeunStep):
|
||||
reversible = False
|
||||
trapezoidal_mode = True
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class TrapezoidalStep_(SingleStepSampler):
|
||||
name = "trapezoidal"
|
||||
model_calls = 1
|
||||
allow_alt_cfgpp = True
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma_next = ss.sigma_next
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
|
||||
# Predict the sample at the next sigma using Euler step
|
||||
euler_sr = next(self.euler_step(x, sigma_down=sigma_next, sigma_up=0))
|
||||
d = euler_sr.noise_pred
|
||||
|
||||
# Denoised sample at the next sigma
|
||||
mr_next = self.call_model(euler_sr.x, euler_sr.sigma_down, call_index=1)
|
||||
|
||||
denoised_pred_next, d_next = self.get_split_prediction(mr=mr_next)
|
||||
yield from self.split_result(
|
||||
denoised_pred_next,
|
||||
(d + d_next) * 0.5,
|
||||
sigma_up=sigma_up,
|
||||
sigma_down=sigma_down,
|
||||
)
|
||||
|
||||
def step_(self, x):
|
||||
ss = self.ss
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
|
||||
# Calculate the derivative using the model
|
||||
d_i = self.to_d(ss.hcur)
|
||||
|
||||
# Predict the sample at the next sigma using Euler step
|
||||
x_pred = x + d_i * ss.dt
|
||||
|
||||
# Denoised sample at the next sigma
|
||||
mr_next = self.call_model(x_pred, ss.sigma_next, call_index=1)
|
||||
|
||||
# Calculate the derivative at the next sigma
|
||||
d_next = self.to_d(mr_next)
|
||||
dt_2 = sigma_down - ss.sigma
|
||||
|
||||
# Update the sample using the Trapezoidal rule
|
||||
x = x + dt_2 * (d_i + d_next) / 2
|
||||
yield from self.result(x, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class BogackiStep(ReversibleSingleStepSampler):
|
||||
name = "bogacki"
|
||||
reversible = False
|
||||
model_calls = 2
|
||||
allow_alt_cfgpp = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if not self.reversible:
|
||||
self.reversible.scale = 0
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
s = ss.sigma
|
||||
sd, su = self.get_ancestral_step(self.get_dyn_eta())
|
||||
reta, reversible_scale = self.get_reversible_cfg()
|
||||
sdr, _sur = self.get_ancestral_step(reta)
|
||||
dt, dtr = sd - s, sdr - s
|
||||
|
||||
# Calculate the derivative using the model
|
||||
d = self.to_d(ss.hcur)
|
||||
|
||||
# Bogacki-Shampine steps
|
||||
k1 = d * dt
|
||||
k2 = self.to_d(self.call_model(x + k1 / 2, s + dt / 2, call_index=1)) * dt
|
||||
k3 = (
|
||||
self.to_d(
|
||||
self.call_model(x + 3 * k1 / 4 + k2 / 4, s + 3 * dt / 4, call_index=2)
|
||||
)
|
||||
* dt
|
||||
)
|
||||
|
||||
# Reversible correction term (inspired by Reversible Heun)
|
||||
correction = dtr**2 * (k3 - k2) / 6
|
||||
|
||||
# Update the sample
|
||||
x = (x + 2 * k1 / 9 + k2 / 3 + 4 * k3 / 9) - correction * reversible_scale
|
||||
yield from self.result(x, su, sigma_down=sd)
|
||||
|
||||
|
||||
class ReversibleBogackiStep(BogackiStep):
|
||||
name = "reversible_bogacki"
|
||||
reversible = True
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class RK4Step(SingleStepSampler):
|
||||
name = "rk4"
|
||||
model_calls = 3
|
||||
allow_alt_cfgpp = True
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
sigma = ss.sigma
|
||||
d = self.to_d(ss.hcur)
|
||||
dt = sigma_down - sigma
|
||||
|
||||
# Runge-Kutta steps
|
||||
k1 = d * dt
|
||||
k2 = self.to_d(self.call_model(x + k1 / 2, sigma + dt / 2, call_index=1)) * dt
|
||||
k3 = self.to_d(self.call_model(x + k2 / 2, sigma + dt / 2, call_index=2)) * dt
|
||||
k4 = self.to_d(self.call_model(x + k3, sigma + dt, call_index=3)) * dt
|
||||
|
||||
# Update the sample
|
||||
x = x + (k1 + 2 * k2 + 2 * k3 + k4) / 6
|
||||
yield from self.result(x, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class RKF45Step(SingleStepSampler):
|
||||
name = "rkf45"
|
||||
model_calls = 5
|
||||
allow_alt_cfgpp = True
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
sigma = ss.sigma
|
||||
d = self.to_d(ss.hcur)
|
||||
dt = sigma_down - sigma
|
||||
|
||||
# Runge-Kutta steps
|
||||
sigma_progression = (
|
||||
sigma + dt / 4,
|
||||
sigma + 3 * dt / 8,
|
||||
sigma + 12 * dt / 13,
|
||||
sigma + dt,
|
||||
)
|
||||
|
||||
call_progression = (
|
||||
lambda k1: x + k1 / 4,
|
||||
lambda k1, k2: x + 3 * k1 / 32 + 9 * k2 / 32,
|
||||
lambda k1, k2, k3: x
|
||||
+ 1932 * k1 / 2197
|
||||
- 7200 * k2 / 2197
|
||||
+ 7296 * k3 / 2197,
|
||||
lambda k1, k2, k3, k4: x
|
||||
+ 439 * k1 / 216
|
||||
- 8 * k2
|
||||
+ 3680 * k3 / 513
|
||||
- 845 * k4 / 4104,
|
||||
)
|
||||
|
||||
k = [d * dt]
|
||||
for idx, (ksigma, kfun) in enumerate(zip(sigma_progression, call_progression)):
|
||||
curr_x = kfun(*k)
|
||||
k.append(self.to_d(self.call_model(curr_x, ksigma)) * dt)
|
||||
del curr_x
|
||||
x = x + 25 * k[0] / 216 + 1408 * k[2] / 2565 + 2197 * k[3] / 4104 - k[4] / 5
|
||||
yield from self.result(x, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class RKDynamicStep(SingleStepSampler):
|
||||
name = "rk_dynamic"
|
||||
model_calls = (0, 3)
|
||||
allow_alt_cfgpp = True
|
||||
|
||||
rk_weights = (
|
||||
(1,),
|
||||
(0.5, 0.5),
|
||||
(1 / 6, 2 / 3, 1 / 6),
|
||||
(1 / 8, 3 / 8, 3 / 8, 1 / 8),
|
||||
)
|
||||
|
||||
rk_error_orders = ((0.0375, 4), (0.075, 3), (0.15, 2))
|
||||
|
||||
def __init__(self, *args, max_order=4, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.max_order = max(0, min(max_order, 4))
|
||||
|
||||
def get_rk_error_order(self, error):
|
||||
for threshold, order in self.rk_error_orders:
|
||||
if error < threshold:
|
||||
return order
|
||||
return 1
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
order = self.max_order
|
||||
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
sigma = ss.sigma
|
||||
d = self.to_d(ss.hcur)
|
||||
dt = sigma_down - sigma
|
||||
|
||||
error = ss.hcur.get_error(ss.hprev) if len(ss.hist) > 1 else 0.0
|
||||
if order < 1:
|
||||
order = self.get_rk_error_order(error)
|
||||
|
||||
k = [d * dt]
|
||||
curr_weight = self.rk_weights[order - 1]
|
||||
|
||||
# print(
|
||||
# f"\nRK: weight={curr_weight!r}, histlen={len(ss.hist)}, order={order} ({self.max_order}), err={error:.6}\n"
|
||||
# )
|
||||
for j in range(1, order):
|
||||
# Calculate intermediate k values based on the current order
|
||||
k_sum = sum(curr_weight[i] * k[i] for i in range(j))
|
||||
mr = self.call_model(x + k_sum, sigma + dt * sum(curr_weight[:j]))
|
||||
k.append(self.to_d(mr) * dt)
|
||||
del mr
|
||||
|
||||
# Update the sample using the weighted sum of k values
|
||||
x = x + sum(curr_weight[j] * k[j] for j in range(order))
|
||||
|
||||
yield from self.result(x, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class EulerDancingStep(SingleStepSampler):
|
||||
name = "clybius_euler_dancing"
|
||||
self_noise = 1
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
deta=1.0,
|
||||
ds_noise=None,
|
||||
leap=2,
|
||||
dyn_deta_start=None,
|
||||
dyn_deta_end=None,
|
||||
dyn_deta_mode="lerp",
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
self.deta = deta
|
||||
self.ds_noise = ds_noise if ds_noise is not None else self.s_noise
|
||||
self.leap = leap
|
||||
self.dyn_deta_start = dyn_deta_start
|
||||
self.dyn_deta_end = dyn_deta_end
|
||||
if dyn_deta_mode not in ("lerp", "lerp_alt", "deta"):
|
||||
raise ValueError("Bad dyn_deta_mode")
|
||||
self.dyn_deta_mode = dyn_deta_mode
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
eta = self.eta
|
||||
deta = self.deta
|
||||
leap_sigmas = ss.sigmas[ss.idx :]
|
||||
leap_sigmas = leap_sigmas[: utils.find_first_unsorted(leap_sigmas)]
|
||||
zero_idx = (leap_sigmas <= 0).nonzero().flatten()[:1]
|
||||
max_leap = (zero_idx.item() if len(zero_idx) else len(leap_sigmas)) - 1
|
||||
is_danceable = max_leap > 1 and ss.sigma_next != 0
|
||||
curr_leap = max(1, min(self.leap, max_leap))
|
||||
sigma_leap = leap_sigmas[curr_leap] if is_danceable else ss.sigma_next
|
||||
del leap_sigmas
|
||||
sigma_down, sigma_up = get_ancestral_step(ss.sigma, sigma_leap, eta)
|
||||
print("???", sigma_down, sigma_up)
|
||||
d = to_d(x, ss.sigma, ss.denoised)
|
||||
# Euler method
|
||||
dt = sigma_down - ss.sigma
|
||||
x = x + d * dt
|
||||
if curr_leap == 1:
|
||||
return (yield from self.result(x, sigma_up))
|
||||
noise_strength = self.ds_noise * sigma_up
|
||||
if noise_strength != 0:
|
||||
x = yield from self.result(x, sigma_up, sigma_next=sigma_leap, final=False)
|
||||
|
||||
# x = x + self.noise_sampler(ss.sigma, sigma_leap).mul_(
|
||||
# self.ds_noise * sigma_up
|
||||
# )
|
||||
# sigma_down2, sigma_up2 = get_ancestral_step(sigma_leap, ss.sigma, eta=deta)
|
||||
# _sigma_down2, sigma_up2 = get_ancestral_step(sigma_leap, ss.sigma, eta=deta)
|
||||
# sigma_up2 = ss.sigma_next + (ss.sigma - ss.sigma_next) * 0.5
|
||||
sigma_up2 = get_ancestral_step(ss.sigma_next, sigma_leap, eta=deta)[1] + (
|
||||
ss.sigma_next * 0.5
|
||||
)
|
||||
sigma_down2, _sigma_up2 = get_ancestral_step(
|
||||
ss.sigma_next, sigma_leap, eta=deta
|
||||
)
|
||||
print(">>>", sigma_down2, sigma_up2, "--", ss.sigma, "->", sigma_leap)
|
||||
# sigma_down2, sigma_up2 = get_ancestral_step(ss.sigma_next, sigma_leap, eta=deta)
|
||||
d_2 = to_d(x, sigma_leap, ss.denoised)
|
||||
dt_2 = sigma_down2 - sigma_leap
|
||||
x = x + d_2 * dt_2
|
||||
yield from self.result(x, sigma_up2, sigma_down=sigma_down2)
|
||||
|
||||
# def _step(self, x, ss):
|
||||
# eta = self.get_dyn_eta(ss)
|
||||
# leap_sigmas = ss.sigmas[ss.idx :]
|
||||
# leap_sigmas = leap_sigmas[: utils.find_first_unsorted(leap_sigmas)]
|
||||
# zero_idx = (leap_sigmas <= 0).nonzero().flatten()[:1]
|
||||
# max_leap = (zero_idx.item() if len(zero_idx) else len(leap_sigmas)) - 1
|
||||
# is_danceable = max_leap > 1 and ss.sigma_next != 0
|
||||
# curr_leap = max(1, min(self.leap, max_leap))
|
||||
# sigma_leap = leap_sigmas[curr_leap] if is_danceable else ss.sigma_next
|
||||
# # DANCE 35 6 tensor(10.0947, device='cuda:0') -- tensor([21.9220,
|
||||
# # print("DANCE", max_leap, curr_leap, sigma_leap, "--", leap_sigmas)
|
||||
# del leap_sigmas
|
||||
# sigma_down, sigma_up = get_ancestral_step(ss.sigma, sigma_leap, eta)
|
||||
# d = to_d(x, ss.sigma, ss.denoised)
|
||||
# # Euler method
|
||||
# dt = sigma_down - ss.sigma
|
||||
# x = x + d * dt
|
||||
# if curr_leap == 1:
|
||||
# return x, sigma_up
|
||||
# dance_scale = self.get_dyn_value(ss, self.dyn_deta_start, self.dyn_deta_end)
|
||||
# if curr_leap == 1 or not is_danceable or abs(dance_scale) < 1e-04:
|
||||
# print("NODANCE", dance_scale, self.deta, is_danceable, ss.sigma_next)
|
||||
# yield SamplerResult(ss, self, x, sigma_up)
|
||||
# print(
|
||||
# "DANCE", dance_scale, self.deta, self.dyn_deta_mode, self.ds_noise, sigma_up
|
||||
# )
|
||||
# sigma_down_normal, sigma_up_normal = get_ancestral_step(
|
||||
# ss.sigma, ss.sigma_next, eta
|
||||
# )
|
||||
# if self.dyn_deta_mode == "lerp":
|
||||
# dt_normal = sigma_down_normal - ss.sigma
|
||||
# x_normal = x + d * dt_normal
|
||||
# else:
|
||||
# x_normal = x
|
||||
# sigma_down2, sigma_up2 = get_ancestral_step(
|
||||
# sigma_leap,
|
||||
# ss.sigma_next,
|
||||
# eta=self.deta * (1.0 if self.dyn_deta_mode != "deta" else dance_scale),
|
||||
# )
|
||||
# print(
|
||||
# "-->",
|
||||
# sigma_down2,
|
||||
# sigma_up2,
|
||||
# "--",
|
||||
# self.deta * (1.0 if self.dyn_deta_mode != "deta" else dance_scale),
|
||||
# )
|
||||
# x = x + self.noise_sampler(ss.sigma, sigma_leap).mul_(self.ds_noise * sigma_up)
|
||||
# d_2 = to_d(x, sigma_leap, ss.denoised)
|
||||
# dt_2 = sigma_down2 - sigma_leap
|
||||
# result = x + d_2 * dt_2
|
||||
# # SIGMA: norm_up=9.062416076660156, up=10.703859329223633, up2=19.376544952392578, str=21.955078125
|
||||
# noise_strength = sigma_up2 + ((sigma_up - sigma_up_normal) ** 5.0)
|
||||
# noise_strength = sigma_up2 + ((sigma_up2 - sigma_up) * 0.5)
|
||||
# # noise_strength = sigma_up2 + (
|
||||
# # (sigma_up2 - sigma_up) ** (1.0 - (sigma_up_normal / sigma_up2))
|
||||
# # )
|
||||
# noise_diff = (
|
||||
# sigma_up - sigma_up_normal
|
||||
# if sigma_up > sigma_up_normal
|
||||
# else sigma_up_normal - sigma_up
|
||||
# )
|
||||
# noise_div = (
|
||||
# sigma_up / sigma_up_normal
|
||||
# if sigma_up > sigma_up_normal
|
||||
# else sigma_up_normal / sigma_up
|
||||
# )
|
||||
# noise_diff = sigma_up2 - sigma_up_normal
|
||||
# noise_div = sigma_up2 / sigma_up_normal
|
||||
# noise_div = ss.sigma / sigma_leap
|
||||
|
||||
# # noise_strength = sigma_up2 + (noise_diff * noise_div)
|
||||
# # noise_strength = sigma_up2 + ((noise_diff * 0.5) ** 2.0)
|
||||
# # noise_strength = sigma_up2 + ((1.0 - noise_diff) ** 0.5)
|
||||
# # noise_strength = sigma_up2 + (((sigma_up2 - sigma_up) * 0.5) ** 2.0)
|
||||
# # noise_strength = sigma_up2 + (((sigma_up2 - sigma_up_normal) * 0.5) ** 1.5)
|
||||
# # noise_strength = sigma_up2 + (
|
||||
# # (noise_diff * 0.1875) ** (1.0 / (noise_div - 0.0))
|
||||
# # )
|
||||
# # noise_strength = sigma_up2 + (
|
||||
# # (noise_diff * 0.125) ** (1.0 / (noise_div * 1.25))
|
||||
# # )
|
||||
# # noise_strength = sigma_up2 + ((noise_diff * 0.2) ** (1.0 / (noise_div * 1.0)))
|
||||
# noise_strength = sigma_up2 + (noise_diff * 0.9 * max(0.0, noise_div - 0.8))
|
||||
# noise_strength = sigma_up2 + (
|
||||
# (noise_diff / (curr_leap * 0.4))
|
||||
# * ((noise_div - (curr_leap / 2.0)).clamp(min=0, max=1.5) * 1.0)
|
||||
# )
|
||||
# # (1.0 / (noise_div * 1.25)))
|
||||
# # noise_strength = sigma_up2 + ((noise_diff * 0.5) ** noise_div)
|
||||
# print(
|
||||
# f"SIGMA: norm_up={sigma_up_normal}, up={sigma_up}, up2={sigma_up2}, str={noise_strength}",
|
||||
# # noise_diff,
|
||||
# noise_div,
|
||||
# )
|
||||
# return result, noise_strength
|
||||
|
||||
# noise_diff = sigma_up2 - sigma_up * dance_scale
|
||||
# noise_scale = sigma_up2 + noise_diff * (0.025 * curr_leap)
|
||||
# # noise_scale = sigma_up2 * self.ds_noise
|
||||
# if self.dyn_deta_mode == "deta" or dance_scale == 1.0:
|
||||
# return result, noise_scale
|
||||
# result = torch.lerp(x_normal, result, dance_scale)
|
||||
# # FIXME: Broken for noise samplers that care about s/sn
|
||||
# return result, noise_scale
|
||||
|
||||
# def step(self, x, ss):
|
||||
# eta = self.get_dyn_eta(ss)
|
||||
# leap_sigmas = ss.sigmas[ss.idx :]
|
||||
# leap_sigmas = leap_sigmas[: find_first_unsorted(leap_sigmas)]
|
||||
# zero_idx = (leap_sigmas <= 0).nonzero().flatten()[:1]
|
||||
# max_leap = (zero_idx.item() if len(zero_idx) else len(leap_sigmas)) - 1
|
||||
# is_danceable = max_leap > 1 and ss.sigma_next != 0
|
||||
# curr_leap = max(1, min(self.leap, max_leap))
|
||||
# sigma_leap = leap_sigmas[curr_leap] if is_danceable else ss.sigma_next
|
||||
# # print("DANCE", max_leap, curr_leap, sigma_leap, "--", leap_sigmas)
|
||||
# del leap_sigmas
|
||||
# sigma_down, sigma_up = get_ancestral_step(ss.sigma, sigma_leap, eta)
|
||||
# d = to_d(x, ss.sigma, ss.denoised)
|
||||
# # Euler method
|
||||
# dt = sigma_down - ss.sigma
|
||||
# x = x + d * dt
|
||||
# if curr_leap == 1:
|
||||
# return x, sigma_up
|
||||
# dance_scale = self.get_dyn_value(ss, self.dyn_deta_start, self.dyn_deta_end)
|
||||
# if not is_danceable or abs(dance_scale) < 1e-04:
|
||||
# print("NODANCE", dance_scale, self.deta)
|
||||
# return x, sigma_up
|
||||
# print("NODANCE", dance_scale, self.deta)
|
||||
# sigma_down_normal, _sigma_up_normal = get_ancestral_step(
|
||||
# ss.sigma, ss.sigma_next, eta
|
||||
# )
|
||||
# if self.dyn_deta_mode == "lerp":
|
||||
# dt_normal = sigma_down_normal - ss.sigma
|
||||
# x_normal = x + d * dt_normal
|
||||
# else:
|
||||
# x_normal = x
|
||||
# x = x + self.noise_sampler(ss.sigma, sigma_leap).mul_(self.s_noise * sigma_up)
|
||||
# sigma_down2, sigma_up2 = get_ancestral_step(
|
||||
# sigma_leap,
|
||||
# ss.sigma_next,
|
||||
# eta=self.deta * (1.0 if self.dyn_deta_mode != "deta" else dance_scale),
|
||||
# )
|
||||
# d_2 = to_d(x, sigma_leap, ss.denoised)
|
||||
# dt_2 = sigma_down2 - sigma_leap
|
||||
# result = x + d_2 * dt_2
|
||||
# noise_diff = sigma_up2 - sigma_up * dance_scale
|
||||
# noise_scale = sigma_up2 + noise_diff * (0.025 * curr_leap)
|
||||
# if self.dyn_deta_mode == "deta" or dance_scale == 1.0:
|
||||
# return result, noise_scale
|
||||
# result = torch.lerp(x_normal, result, dance_scale)
|
||||
# # FIXME: Broken for noise samplers that care about s/sn
|
||||
# return result, noise_scale
|
||||
|
||||
|
||||
# Based on implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
# Which was originally written by Katherine Crowson
|
||||
class TTMJVPStep(SingleStepSampler):
|
||||
name = "ttm_jvp"
|
||||
model_calls = 1
|
||||
|
||||
def __init__(self, *args, alternate_phi_2_calc=True, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.alternate_phi_2_calc = alternate_phi_2_calc
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
eta = self.get_dyn_eta()
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
# 2nd order truncated Taylor method
|
||||
t, s = -sigma.log(), -sigma_next.log()
|
||||
h = s - t
|
||||
h_eta = h * (eta + 1)
|
||||
|
||||
eps = to_d(x, sigma, ss.denoised)
|
||||
denoised_prime = self.call_model(
|
||||
x, sigma, tangents=(eps * -sigma, -sigma), call_index=1
|
||||
).jdenoised
|
||||
|
||||
phi_1 = -torch.expm1(-h_eta)
|
||||
if self.alternate_phi_2_calc:
|
||||
phi_2 = torch.expm1(-h) + h # seems to work better with eta > 0
|
||||
else:
|
||||
phi_2 = torch.expm1(-h_eta) + h_eta
|
||||
x = torch.exp(-h_eta) * x + phi_1 * ss.denoised + phi_2 * denoised_prime
|
||||
|
||||
noise_scale = (
|
||||
sigma_next * torch.sqrt(-torch.expm1(-2 * h * eta))
|
||||
if eta
|
||||
else ss.sigma.new_zeros(1)
|
||||
)
|
||||
yield from self.result(x, noise_scale)
|
||||
|
||||
|
||||
class HeunStep(ReversibleSingleStepSampler):
|
||||
name = "heun"
|
||||
model_calls = 1
|
||||
default_history_limit, max_history = 0, 0
|
||||
allow_alt_cfgpp = True
|
||||
|
||||
def reversible_correction(self, d_from, d_to):
|
||||
reta, reversible_scale = self.get_reversible_cfg()
|
||||
if reversible_scale == 0:
|
||||
return 0
|
||||
sdr = self.get_ancestral_step(reta)[0]
|
||||
dtr = sdr - self.ss.sigma
|
||||
return (dtr**2 * (d_to - d_from) / 4) * self.reversible.scale
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
s = ss.sigma
|
||||
sd, su = self.get_ancestral_step(self.get_dyn_eta())
|
||||
dt = sd - s
|
||||
hcur = ss.hcur
|
||||
d = self.to_d(hcur)
|
||||
x_next = hcur.denoised + d * sd
|
||||
d_next = self.to_d(self.call_model(x_next, sd, call_index=1))
|
||||
result = hcur.denoised + d * s
|
||||
result += (dt * (d + d_next)) * 0.5
|
||||
result -= self.reversible_correction(d, d_next)
|
||||
yield from self.result(result, su, sigma_down=sd)
|
||||
|
||||
|
||||
class Heun1SStep(HeunStep):
|
||||
name = "heun_1s"
|
||||
model_calls = (0, 1)
|
||||
allow_alt_cfgpp = True
|
||||
default_history_limit, max_history = 1, 1
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
s = ss.sigma
|
||||
if self.available_history() == 0:
|
||||
return (yield from super().step(x))
|
||||
hcur, hprev = ss.hcur, ss.hprev
|
||||
d_prev = self.to_d(hprev)
|
||||
sd, su = self.get_ancestral_step(self.get_dyn_eta())
|
||||
dt = sd - s
|
||||
d = self.to_d(hcur)
|
||||
result = hcur.denoised + hcur.sigma * self.to_d(hcur)
|
||||
result += (dt * (d_prev + d)) * 0.5
|
||||
result -= self.reversible_correction(d_prev, d)
|
||||
yield from self.result(result, su, sigma_down=sd)
|
||||
|
||||
|
||||
class ClybiusSENSStep(DPMPP2MSDEStep):
|
||||
name = "clybius_sens"
|
||||
default_history_limit, max_history = 2, 2
|
||||
allow_alt_cfgpp = False
|
||||
default_reta = 1.0
|
||||
default_reversible_scale = 1.0
|
||||
|
||||
def __init__(self, *, tsde_reversible=None, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.tsde_reversible = ReversibleConfig.build(
|
||||
default_eta=self.default_reta,
|
||||
default_scale=self.default_reversible_scale,
|
||||
**utils.fallback(tsde_reversible, {}),
|
||||
)
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
denoised = ss.denoised
|
||||
# DPM-Solver++(2M) SDE
|
||||
t, s = -sigma.log(), -sigma_next.log()
|
||||
h = s - t
|
||||
eta_h = self.get_dyn_eta() * h
|
||||
ratio = sigma_next / sigma
|
||||
x = ((ratio * (-eta_h).exp()) * x).add_((-h - eta_h).expm1().neg() * denoised)
|
||||
noise_strength = sigma_next * (-2 * eta_h).expm1().neg().sqrt()
|
||||
if self.available_history() == 0:
|
||||
return (yield from self.result(x, noise_strength))
|
||||
sigma_prev, old_denoised = ss.hprev.sigma, ss.hprev.denoised
|
||||
h_last = (-sigma.log()) - (-sigma_prev.log())
|
||||
r = h_last / h
|
||||
if self.solver_type == "midpoint":
|
||||
multiplier = 0.5 * (-h - eta_h).expm1().neg()
|
||||
else:
|
||||
multiplier = (-h - eta_h).expm1().neg() / (-h - eta_h) + 1
|
||||
reta, reversible_scale = self.get_reversible_cfg()
|
||||
if reversible_scale != 0:
|
||||
multiplier *= 0.5
|
||||
x += (denoised - old_denoised).mul_((1 / r) * multiplier)
|
||||
if reversible_scale != 0:
|
||||
reta_h = reta * h
|
||||
if self.solver_type == "midpoint":
|
||||
rmultiplier = 0.5 * (-h - reta_h).expm1().neg()
|
||||
else:
|
||||
rmultiplier = (-h - reta_h).expm1().neg() / (-h - reta_h) + 1
|
||||
rmultiplier = ((1 / r) * (rmultiplier**2 / 2)) * reversible_scale
|
||||
x -= (old_denoised - denoised).mul_(rmultiplier)
|
||||
if self.available_history() > 1:
|
||||
tsde_reta, tsde_reversible_scale = self.get_reversible_cfg(
|
||||
reversible=self.tsde_reversible
|
||||
)
|
||||
tsde_reta_h = tsde_reta * h
|
||||
sigma_prev_2 = ss.hist[-3].sigma
|
||||
h_last_2 = (-sigma_prev.log()) - (-sigma_prev_2.log())
|
||||
r = h_last_2 / h
|
||||
old_denoised_2 = ss.hist[-3].denoised
|
||||
d = (old_denoised - old_denoised_2).div_(r)
|
||||
d_2 = (old_denoised - denoised).div_(r)
|
||||
|
||||
d_rev = (denoised - old_denoised).div_(r)
|
||||
d_2_rev = (old_denoised_2 - old_denoised).div_(r)
|
||||
|
||||
rphi = tsde_reta_h.neg().expm1() / tsde_reta_h + 1
|
||||
tsde_adjustment = rphi * (d + d_2) / 2
|
||||
if tsde_reversible_scale != 0:
|
||||
tsde_adjustment -= (rphi**2 * (d_rev + d_2_rev) / 2).mul_(
|
||||
tsde_reversible_scale
|
||||
)
|
||||
x += tsde_adjustment
|
||||
yield from self.result(x, noise_strength)
|
||||
|
||||
|
||||
registry.add(
|
||||
BogackiStep,
|
||||
ClybiusSENSStep,
|
||||
EulerDancingStep,
|
||||
ReversibleBogackiStep,
|
||||
ReversibleHeunStep,
|
||||
ReversibleHeun1SStep,
|
||||
RESStep,
|
||||
TTMJVPStep,
|
||||
TrapezoidalStep,
|
||||
RK4Step,
|
||||
RKDynamicStep,
|
||||
RKF45Step,
|
||||
Heun1SStep,
|
||||
HeunStep,
|
||||
)
|
||||
@@ -0,0 +1,131 @@
|
||||
# Samplers based on design from https://github.com/Extraltodeus/
|
||||
|
||||
import typing
|
||||
|
||||
import torch
|
||||
import tqdm
|
||||
|
||||
from .base import SingleStepSampler
|
||||
from . import registry
|
||||
|
||||
|
||||
class DistanceConfig(typing.NamedTuple):
|
||||
resample: int = 3
|
||||
resample_end: int = 1
|
||||
eta: float = 0.0
|
||||
s_noise: float = 1.0
|
||||
alt_cfgpp_scale: float = 0.0
|
||||
first_eta_step: int = 0
|
||||
last_eta_step: int = -1
|
||||
custom_noise_name: str = "alt"
|
||||
immiscible: dict | bool | None = None
|
||||
|
||||
|
||||
# Based on https://github.com/Extraltodeus/DistanceSampler
|
||||
class DistanceStep(SingleStepSampler):
|
||||
name = "extraltodeus_distance"
|
||||
allow_alt_cfgpp = True
|
||||
model_calls = -1
|
||||
uses_alt_noise = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.distance = DistanceConfig(**self.options.get("distance", {}))
|
||||
|
||||
@property
|
||||
def require_uncond(self):
|
||||
return super().require_uncond or self.distance.alt_cfgpp_scale != 0
|
||||
|
||||
def distance_resample_steps(self):
|
||||
ss = self.ss
|
||||
resample, resample_end = self.distance.resample, self.distance.resample_end
|
||||
if resample == -1:
|
||||
current_resample = min(10, (ss.sigmas.shape[0] - ss.idx) // 2)
|
||||
else:
|
||||
current_resample = resample
|
||||
if resample_end < 0:
|
||||
return current_resample
|
||||
sigma = ss.sigma
|
||||
s_min = (ss.sigmas if ss.sigmas[-1] > 0 else ss.sigmas[:-1]).min()
|
||||
s_max = ss.sigmas.max()
|
||||
res_mul = max(0, min(1, ((sigma - s_min) / (s_max - s_min)) ** 0.5))
|
||||
return max(
|
||||
min(current_resample, resample_end),
|
||||
min(
|
||||
max(current_resample, resample_end),
|
||||
int(current_resample * res_mul + resample_end * (1 - res_mul)),
|
||||
),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def distance_weights(t, p):
|
||||
batch = t.shape[0]
|
||||
d = torch.stack(
|
||||
tuple((t - t[idx]).abs().sum(dim=0) for idx in range(batch)),
|
||||
dim=0,
|
||||
)
|
||||
d_min, d_max = d.min(), d.max()
|
||||
d = torch.nan_to_num(
|
||||
(1 - (d - d_min) / (d_max - d_min)).pow(p),
|
||||
nan=1,
|
||||
neginf=1,
|
||||
posinf=1,
|
||||
)
|
||||
d /= d.sum(dim=0)
|
||||
return d.mul_(t).sum(dim=0)
|
||||
|
||||
def step(self, x):
|
||||
resample_steps = self.distance_resample_steps()
|
||||
if resample_steps < 1:
|
||||
return (yield from self.euler_step(x))
|
||||
distance = self.distance
|
||||
ss = self.ss
|
||||
sigma_down, sigma_up = self.get_ancestral_step(self.get_dyn_eta())
|
||||
rsigma_down, rsigma_up = self.get_ancestral_step(eta=distance.eta)
|
||||
rsigma_up *= distance.s_noise
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
zero_up = sigma * 0
|
||||
d = self.to_d(ss.hcur)
|
||||
can_ancestral = not torch.equal(rsigma_down, sigma_next)
|
||||
start_eta_idx, end_eta_idx = (
|
||||
max(0, resample_steps + v if v < 0 else v)
|
||||
for v in (
|
||||
distance.first_eta_step,
|
||||
distance.last_eta_step,
|
||||
)
|
||||
)
|
||||
dt = sigma_down - sigma
|
||||
d = self.to_d(ss.hcur)
|
||||
x_n = [d]
|
||||
for re_step in tqdm.trange(
|
||||
resample_steps, desc="distance_resample", disable=ss.disable_status
|
||||
):
|
||||
if can_ancestral and start_eta_idx <= re_step <= end_eta_idx:
|
||||
curr_sigma_down, curr_sigma_up = rsigma_down, rsigma_up
|
||||
else:
|
||||
curr_sigma_down, curr_sigma_up = sigma_next, zero_up
|
||||
rdt = curr_sigma_down - sigma
|
||||
x_new = x + d * rdt
|
||||
if curr_sigma_up != 0:
|
||||
x_new = yield from self.result(
|
||||
x_new,
|
||||
curr_sigma_up,
|
||||
sigma=sigma,
|
||||
sigma_down=curr_sigma_down,
|
||||
noise_sampler=self.alt_noise_sampler,
|
||||
final=False,
|
||||
)
|
||||
sr = self.call_model(x_new, sigma_next, call_index=re_step + 1)
|
||||
new_d = sr.to_d(
|
||||
sigma=curr_sigma_down, alt_cfgpp_scale=distance.alt_cfgpp_scale
|
||||
)
|
||||
x_n.append(new_d)
|
||||
if re_step == 0:
|
||||
d = (new_d + d) / 2
|
||||
else:
|
||||
d = self.distance_weights(torch.stack(x_n), re_step + 2)
|
||||
x_n.append(d)
|
||||
yield from self.result(x + d * dt, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
registry.add(DistanceStep)
|
||||
@@ -0,0 +1,29 @@
|
||||
from .base import SingleStepSampler, registry
|
||||
|
||||
|
||||
# Referenced from https://github.com/ace-step/ACE-Step/
|
||||
class PingPongStep(SingleStepSampler):
|
||||
name = "pingpong"
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
pingpong_options = self.options.pop("pingpong", {})
|
||||
self.pingpong_start_step = pingpong_options.get("start_step", 0)
|
||||
self.pingpong_end_step = pingpong_options.get("end_step", 0)
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
use_pingpong = self.pingpong_start_step <= ss.step <= self.pingpong_end_step
|
||||
if not use_pingpong:
|
||||
return (yield from self.euler_step(x, eta=0.0))
|
||||
sn = ss.sigma_next
|
||||
denoised = (
|
||||
ss.denoised * (1.0 - sn) if ss.model.is_rectified_flow else ss.denoised
|
||||
)
|
||||
yield from self.result(denoised, sn, sigma_down=sn)
|
||||
|
||||
|
||||
registry.add(
|
||||
PingPongStep,
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
SAMPLER_LIST = []
|
||||
|
||||
STEP_SAMPLERS = {}
|
||||
STEP_SAMPLER_SIMPLE_NAMES = {}
|
||||
|
||||
|
||||
def add(*objs):
|
||||
global SAMPLER_LIST
|
||||
SAMPLER_LIST += objs
|
||||
|
||||
|
||||
def init():
|
||||
global STEP_SAMPLERS, STEP_SAMPLER_SIMPLE_NAMES
|
||||
STEP_SAMPLER_SIMPLE_NAMES.clear()
|
||||
STEP_SAMPLERS.clear()
|
||||
euler = None
|
||||
temp = []
|
||||
for c in SAMPLER_LIST:
|
||||
mc = c.model_calls
|
||||
if mc == 0:
|
||||
prettymc = ""
|
||||
elif isinstance(mc, tuple):
|
||||
prettymc = f" ({mc[0]}-{mc[-1]})"
|
||||
elif mc < 0:
|
||||
prettymc = " (variable)"
|
||||
else:
|
||||
prettymc = f" ({mc})"
|
||||
if c.name == "euler":
|
||||
euler = c
|
||||
temp.append((f"{c.name}{prettymc}", c))
|
||||
temp.sort(key=lambda item: item[1].name)
|
||||
if euler is None:
|
||||
raise RuntimeError(
|
||||
"Impossible: euler sampler not found when building sampler registry"
|
||||
)
|
||||
STEP_SAMPLERS["default (euler)"] = euler
|
||||
STEP_SAMPLERS |= {k: v for k, v in temp}
|
||||
STEP_SAMPLER_SIMPLE_NAMES["default"] = euler
|
||||
STEP_SAMPLER_SIMPLE_NAMES |= {v.name: v for _k, v in temp}
|
||||
@@ -0,0 +1,49 @@
|
||||
from .base import SingleStepSampler, MinSigmaStepMixin
|
||||
|
||||
|
||||
class DESolverStep(SingleStepSampler, MinSigmaStepMixin):
|
||||
de_default_solver = None
|
||||
sample_sigma_zero = True
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args,
|
||||
de_solver=None,
|
||||
de_max_nfe=100,
|
||||
de_rtol=-2.5,
|
||||
de_atol=-3.5,
|
||||
de_fixup_hack=0.025,
|
||||
de_split=1,
|
||||
de_min_sigma=0.0292,
|
||||
**kwargs,
|
||||
):
|
||||
self.check_solver_support()
|
||||
super().__init__(*args, **kwargs)
|
||||
de_solver = self.de_default_solver if de_solver is None else de_solver
|
||||
self.de_solver_name = de_solver
|
||||
self.de_max_nfe = de_max_nfe
|
||||
self.de_rtol = 10**de_rtol
|
||||
self.de_atol = 10**de_atol
|
||||
self.de_fixup_hack = de_fixup_hack
|
||||
self.de_split = de_split
|
||||
self.de_min_sigma = de_min_sigma if de_min_sigma is not None else 0.0
|
||||
|
||||
def check_solver_support(self):
|
||||
raise NotImplementedError
|
||||
|
||||
def de_get_step(self, x):
|
||||
eta = self.get_dyn_eta()
|
||||
ss = self.ss
|
||||
s, sn = ss.sigma, ss.sigma_next
|
||||
sn = self.adjust_step(sn, self.de_min_sigma)
|
||||
sigma_down, sigma_up = self.get_ancestral_step(eta, sigma_next=sn)
|
||||
if self.de_fixup_hack != 0:
|
||||
sigma_down = (sigma_down - (s - sigma_down) * self.de_fixup_hack).clamp(
|
||||
min=0
|
||||
)
|
||||
return s, sn, sigma_down, sigma_up
|
||||
|
||||
@staticmethod
|
||||
def reverse_time(t, t0, t1):
|
||||
return t1 + (t0 - t)
|
||||
@@ -0,0 +1,304 @@
|
||||
import contextlib
|
||||
import os
|
||||
import typing
|
||||
import warnings
|
||||
|
||||
import numpy
|
||||
import torch
|
||||
import tqdm
|
||||
|
||||
import comfy
|
||||
|
||||
from . import registry
|
||||
from .solver_base import DESolverStep
|
||||
|
||||
HAVE_DIFFRAX = False
|
||||
|
||||
|
||||
if not os.environ.get("COMFYUI_OCS_NO_DIFFRAX_SOLVER"):
|
||||
with contextlib.suppress(ImportError):
|
||||
import diffrax
|
||||
import jax
|
||||
|
||||
if not os.environ.get("COMFYUI_OCS_NO_DISABLE_JAX_PREALLOCATE"):
|
||||
os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"] = "false"
|
||||
# jax.config.update("jax_enable_x64", True)
|
||||
|
||||
HAVE_DIFFRAX = True
|
||||
|
||||
|
||||
if HAVE_DIFFRAX:
|
||||
|
||||
class RevVirtualBrownianTree(diffrax.VirtualBrownianTree):
|
||||
def evaluate(self, t0, t1, *args, **kwargs):
|
||||
if t1 is not None:
|
||||
return super().evaluate(t1, t0, *args, **kwargs)
|
||||
return super().evaluate(t0, t1, *args, **kwargs)
|
||||
|
||||
class StepCallbackTqdmProgressMeter(diffrax.TqdmProgressMeter):
|
||||
step_callback: typing.Callable = None
|
||||
|
||||
def _init_bar(self, *args, **kwargs):
|
||||
if self.step_callback is None:
|
||||
return super()._init_bar(*args, **kwargs)
|
||||
bar_format = "{percentage:.2f}%{step_callback}|{bar}| [{elapsed}<{remaining}, {rate_fmt}{postfix}]"
|
||||
step_callback = self.step_callback
|
||||
|
||||
class WrapTqdm(tqdm.tqdm):
|
||||
@property
|
||||
def format_dict(self):
|
||||
d = super().format_dict
|
||||
d.update(step_callback=step_callback())
|
||||
return d
|
||||
|
||||
return WrapTqdm(total=100, unit="%", bar_format=bar_format)
|
||||
|
||||
|
||||
class DiffraxStep(DESolverStep):
|
||||
name = "diffrax"
|
||||
model_calls = -1
|
||||
allow_alt_cfgpp = True
|
||||
de_default_solver = "dopri5"
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args,
|
||||
de_split=1,
|
||||
de_initial_step=0.25,
|
||||
de_ctl_pcoeff=0.3,
|
||||
de_ctl_icoeff=0.9,
|
||||
de_ctl_dcoeff=0.2,
|
||||
diffrax_adaptive=False,
|
||||
diffrax_fake_pure_callback=True,
|
||||
diffrax_g_multiplier=0.0,
|
||||
diffrax_half_solver=False,
|
||||
diffrax_batch_channels=False,
|
||||
diffrax_levy_area_approx="brownian_increment",
|
||||
diffrax_error_order=None,
|
||||
diffrax_sde_mode=False,
|
||||
diffrax_g_reverse_time=False,
|
||||
diffrax_g_time_scaling=False,
|
||||
diffrax_g_split_time_mode=False,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(*args, **kwargs)
|
||||
solvers = dict(
|
||||
euler=diffrax.Euler,
|
||||
heun=diffrax.Heun,
|
||||
midpoint=diffrax.Midpoint,
|
||||
ralston=diffrax.Ralston,
|
||||
bosh3=diffrax.Bosh3,
|
||||
tsit5=diffrax.Tsit5,
|
||||
dopri5=diffrax.Dopri5,
|
||||
dopri8=diffrax.Dopri8,
|
||||
implicit_euler=diffrax.ImplicitEuler,
|
||||
# kvaerno3=diffrax.Kvaerno3,
|
||||
# kvaerno4=diffrax.Kvaerno4,
|
||||
# kvaerno5=diffrax.Kvaerno5,
|
||||
semi_implicit_euler=diffrax.SemiImplicitEuler,
|
||||
reversible_heun=diffrax.ReversibleHeun,
|
||||
leapfrog_midpoint=diffrax.LeapfrogMidpoint,
|
||||
euler_heun=diffrax.EulerHeun,
|
||||
ito_milstein=diffrax.ItoMilstein,
|
||||
stratonovich_milstein=diffrax.StratonovichMilstein,
|
||||
sea=diffrax.SEA,
|
||||
sra1=diffrax.SRA1,
|
||||
shark=diffrax.ShARK,
|
||||
general_shark=diffrax.GeneralShARK,
|
||||
slow_rk=diffrax.SlowRK,
|
||||
spark=diffrax.SPaRK,
|
||||
)
|
||||
levy_areas = dict(
|
||||
brownian_increment=diffrax.BrownianIncrement,
|
||||
space_time=diffrax.SpaceTimeLevyArea,
|
||||
space_time_time=diffrax.SpaceTimeTimeLevyArea,
|
||||
)
|
||||
# jax.config.update("jax_disable_jit", True)
|
||||
self.de_solver_method = solvers[self.de_solver_name]()
|
||||
if diffrax_half_solver:
|
||||
self.de_solver_method = diffrax.HalfSolver(self.de_solver_method)
|
||||
self.de_ctl_pcoeff = de_ctl_pcoeff
|
||||
self.de_ctl_icoeff = de_ctl_icoeff
|
||||
self.de_ctl_dcoeff = de_ctl_dcoeff
|
||||
self.de_initial_step = de_initial_step
|
||||
self.de_adaptive = diffrax_adaptive
|
||||
self.de_split = de_split
|
||||
self.de_fake_pure_callback = diffrax_fake_pure_callback
|
||||
self.de_g_multiplier = diffrax_g_multiplier
|
||||
self.de_batch_channels = diffrax_batch_channels
|
||||
self.de_levy_area_approx = levy_areas[diffrax_levy_area_approx]
|
||||
self.de_error_order = diffrax_error_order
|
||||
self.de_sde_mode = diffrax_sde_mode
|
||||
self.de_g_reverse_time = diffrax_g_reverse_time
|
||||
self.de_g_time_scaling = diffrax_g_time_scaling
|
||||
self.de_g_split_time_mode = diffrax_g_split_time_mode
|
||||
|
||||
# As slow and safe as possible.
|
||||
@staticmethod
|
||||
def t2j(t):
|
||||
return jax.block_until_ready(
|
||||
jax.numpy.array(numpy.array(t.detach().cpu().contiguous()))
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def j2t(t):
|
||||
return torch.from_numpy(numpy.array(jax.block_until_ready(t))).contiguous()
|
||||
|
||||
def check_solver_support(self):
|
||||
if not HAVE_DIFFRAX:
|
||||
raise RuntimeError(
|
||||
"Diffrax sampler requires diffrax and jax installed in venv."
|
||||
)
|
||||
|
||||
def step(self, x):
|
||||
s, sn, sigma_down, sigma_up = self.de_get_step(x)
|
||||
if self.de_min_sigma is not None and s <= self.de_min_sigma:
|
||||
return (yield from self.euler_step(x))
|
||||
ss = self.ss
|
||||
bidx = 0
|
||||
mcc = 0
|
||||
_b, c, h, w = x.shape
|
||||
interrupted = None
|
||||
t0, t1 = sigma_down.item(), s.item()
|
||||
|
||||
def odefn_(t_orig, y_flat, args=()):
|
||||
nonlocal mcc, interrupted
|
||||
t = self.reverse_time(self.j2t(t_orig).to(s), t0, t1)
|
||||
if t <= 1e-05:
|
||||
return jax.numpy.zeros_like(y_flat)
|
||||
if mcc >= self.de_max_nfe:
|
||||
raise RuntimeError("DiffraxStep: Model call limit exceeded")
|
||||
y = self.j2t(y_flat.reshape(1, c, h, w)).to(x)
|
||||
t32 = t.to(s).clamp(min=1e-05)
|
||||
flat_shape = y_flat.shape
|
||||
del y_flat
|
||||
|
||||
if not args and mcc == 0 and torch.all(t == s):
|
||||
mr_cached = True
|
||||
mr = ss.hcur
|
||||
mcc = 1
|
||||
else:
|
||||
mr_cached = False
|
||||
try:
|
||||
if not args:
|
||||
mr = self.call_model(y, t32, call_index=mcc, s_in=t.new_ones(1))
|
||||
else:
|
||||
print("TANGENTS")
|
||||
mr = self.call_model(
|
||||
y,
|
||||
t32,
|
||||
call_index=mcc,
|
||||
tangents=args,
|
||||
s_in=t.new_ones(1),
|
||||
)
|
||||
except comfy.model_management.InterruptProcessingException as exc:
|
||||
interrupted = exc
|
||||
raise
|
||||
mcc += 1
|
||||
result = self.to_d(mr)[bidx if mr_cached else 0].reshape(*flat_shape)
|
||||
return self.t2j(-result)
|
||||
|
||||
if not self.de_fake_pure_callback:
|
||||
|
||||
def odefn(t, y_flat, args):
|
||||
return jax.experimental.io_callback(
|
||||
odefn_, y_flat, t, y_flat, ordered=True
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
def odefn(t, y_flat, args):
|
||||
return jax.pure_callback(odefn_, y_flat, t, y_flat)
|
||||
|
||||
def g(t, y, _args):
|
||||
if self.de_g_split_time_mode:
|
||||
val = jax.lax.cond(
|
||||
t < t0 + (t1 - t0) * 0.5,
|
||||
lambda: self.de_g_multiplier,
|
||||
lambda: -self.de_g_multiplier,
|
||||
)
|
||||
else:
|
||||
val = self.de_g_multiplier
|
||||
if self.de_g_time_scaling:
|
||||
val *= self.reverse_time(t, t0, t1) if self.de_g_reverse_time else t
|
||||
if not self.de_batch_channels:
|
||||
return val
|
||||
return jax.numpy.float32(val).broadcast((y.shape[0],))
|
||||
|
||||
def progress_callback():
|
||||
return f" ({mcc:>3}/{self.de_max_nfe:>3}) {self.de_solver_name}"
|
||||
|
||||
term = diffrax.ODETerm(odefn)
|
||||
method = self.de_solver_method
|
||||
if self.de_adaptive:
|
||||
controller = diffrax.PIDController(
|
||||
atol=self.de_atol,
|
||||
rtol=self.de_rtol,
|
||||
dtmin=1e-05,
|
||||
pcoeff=self.de_ctl_pcoeff,
|
||||
icoeff=self.de_ctl_icoeff,
|
||||
dcoeff=self.de_ctl_dcoeff,
|
||||
error_order=self.de_error_order,
|
||||
)
|
||||
else:
|
||||
controller = diffrax.ConstantStepSize()
|
||||
|
||||
if not self.de_adaptive:
|
||||
dt0 = (t1 - t0) / self.de_split
|
||||
else:
|
||||
dt0 = (t1 - t0) * self.de_initial_step
|
||||
if self.de_sde_mode:
|
||||
bm = diffrax.VirtualBrownianTree(
|
||||
t0=ss.sigmas.min().item(),
|
||||
t1=ss.sigmas.max().item(),
|
||||
tol=1e-06,
|
||||
levy_area=self.de_levy_area_approx,
|
||||
shape=(c,) if self.de_batch_channels else (),
|
||||
key=jax.random.PRNGKey(ss.noise.seed + ss.noise.seed_offset),
|
||||
)
|
||||
term = diffrax.MultiTerm(term, diffrax.ControlTerm(g, bm))
|
||||
results = []
|
||||
for batch in tqdm.trange(
|
||||
1,
|
||||
x.shape[0] + 1,
|
||||
desc="batch",
|
||||
leave=False,
|
||||
disable=x.shape[0] == 1 or ss.disable_status,
|
||||
):
|
||||
bidx = batch - 1
|
||||
mcc = 0
|
||||
if self.de_batch_channels:
|
||||
y_flat = x[bidx].flatten(start_dim=1)
|
||||
else:
|
||||
y_flat = x[bidx].unsqueeze(0).flatten(start_dim=1)
|
||||
y_flat = self.t2j(y_flat)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter(action="ignore", category=FutureWarning)
|
||||
try:
|
||||
solution = diffrax.diffeqsolve(
|
||||
terms=term,
|
||||
solver=method,
|
||||
t0=t0,
|
||||
t1=t1,
|
||||
dt0=dt0,
|
||||
y0=y_flat,
|
||||
saveat=diffrax.SaveAt(t1=True),
|
||||
stepsize_controller=controller,
|
||||
progress_meter=StepCallbackTqdmProgressMeter(
|
||||
step_callback=progress_callback,
|
||||
refresh_steps=1,
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
if interrupted is not None:
|
||||
raise interrupted
|
||||
raise
|
||||
results.append(self.j2t(solution.ys).view(1, *x.shape[1:]))
|
||||
del solution
|
||||
result = torch.cat(results).to(x)
|
||||
sigma_up, result = yield from self.adjusted_step(sn, result, mcc, sigma_up)
|
||||
yield from self.result(result, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
registry.add(DiffraxStep)
|
||||
@@ -0,0 +1,118 @@
|
||||
import contextlib
|
||||
|
||||
import torch
|
||||
import tqdm
|
||||
|
||||
from . import registry
|
||||
from .solver_base import DESolverStep
|
||||
|
||||
HAVE_TDE = False
|
||||
with contextlib.suppress(ImportError):
|
||||
import torchdiffeq as tde
|
||||
|
||||
HAVE_TDE = True
|
||||
|
||||
|
||||
class TDEStep(DESolverStep):
|
||||
name = "tde"
|
||||
model_calls = -1
|
||||
allow_alt_cfgpp = True
|
||||
allow_cfgpp = False
|
||||
de_default_solver = "rk4"
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args,
|
||||
de_split=1,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.de_split = de_split
|
||||
|
||||
def check_solver_support(self):
|
||||
if not HAVE_TDE:
|
||||
raise RuntimeError(
|
||||
"TDE sampler requires torchdiffeq installed in venv. Example: pip install torchdiffeq"
|
||||
)
|
||||
|
||||
def step(self, x):
|
||||
s, sn, sigma_down, sigma_up = self.de_get_step(x)
|
||||
if self.de_min_sigma is not None and s <= self.de_min_sigma:
|
||||
return (yield from self.euler_step(x))
|
||||
ss = self.ss
|
||||
delta = (s - sigma_down).item()
|
||||
mcc = 0
|
||||
bidx = 0
|
||||
pbar = None
|
||||
|
||||
def odefn(t, y):
|
||||
nonlocal mcc
|
||||
if t < 1e-05:
|
||||
return torch.zeros_like(y)
|
||||
if mcc >= self.de_max_nfe:
|
||||
raise RuntimeError("TDEStep: Model call limit exceeded")
|
||||
|
||||
pct = (s - t) / delta
|
||||
pbar.n = round(min(999, pct.item() * 999))
|
||||
pbar.update(0)
|
||||
pbar.set_description(
|
||||
f"{self.de_solver_name}({mcc}/{self.de_max_nfe})", refresh=True
|
||||
)
|
||||
|
||||
if t == ss.sigma and torch.equal(x[bidx], y):
|
||||
mr_cached = True
|
||||
mr = ss.hcur
|
||||
mcc = 1
|
||||
else:
|
||||
mr_cached = False
|
||||
mr = self.call_model(
|
||||
y.unsqueeze(0), t, call_index=mcc, s_in=t.new_ones(1)
|
||||
)
|
||||
mcc += 1
|
||||
return self.to_d(mr)[bidx if mr_cached else 0]
|
||||
|
||||
result = torch.zeros_like(x)
|
||||
t = sigma_down.new_zeros(self.de_split + 1)
|
||||
torch.linspace(ss.sigma, sigma_down, t.shape[0], out=t)
|
||||
|
||||
for batch in tqdm.trange(
|
||||
1,
|
||||
x.shape[0] + 1,
|
||||
desc="batch",
|
||||
leave=False,
|
||||
disable=x.shape[0] == 1 or ss.disable_status,
|
||||
):
|
||||
bidx = batch - 1
|
||||
mcc = 0
|
||||
if pbar is not None:
|
||||
pbar.close()
|
||||
pbar = tqdm.tqdm(
|
||||
total=1000,
|
||||
desc=self.de_solver_name,
|
||||
leave=True,
|
||||
disable=ss.disable_status,
|
||||
)
|
||||
solution = tde.odeint(
|
||||
odefn,
|
||||
x[bidx],
|
||||
t,
|
||||
rtol=self.de_rtol,
|
||||
atol=self.de_atol,
|
||||
method=self.de_solver_name,
|
||||
options={
|
||||
"min_step": 1e-05,
|
||||
"dtype": torch.float64,
|
||||
},
|
||||
)[-1]
|
||||
result[bidx] = solution
|
||||
|
||||
sigma_up, result = yield from self.adjusted_step(sn, result, mcc, sigma_up)
|
||||
if pbar is not None:
|
||||
pbar.n = pbar.total
|
||||
pbar.update(0)
|
||||
pbar.close()
|
||||
yield from self.result(result, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
registry.add(TDEStep)
|
||||
@@ -0,0 +1,132 @@
|
||||
import contextlib
|
||||
|
||||
import torch
|
||||
import tqdm
|
||||
|
||||
from . import registry
|
||||
from .solver_base import DESolverStep
|
||||
|
||||
|
||||
HAVE_TODE = False
|
||||
with contextlib.suppress(ImportError, RuntimeError):
|
||||
import torchode as tode
|
||||
|
||||
HAVE_TODE = True
|
||||
|
||||
|
||||
class TODEStep(DESolverStep):
|
||||
name = "tode"
|
||||
model_calls = -1
|
||||
allow_alt_cfgpp = True
|
||||
de_default_solver = "dopri5"
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args,
|
||||
de_initial_step=0.25,
|
||||
tode_compile=False,
|
||||
de_ctl_pcoeff=0.3,
|
||||
de_ctl_icoeff=0.9,
|
||||
de_ctl_dcoeff=0.2,
|
||||
**kwargs,
|
||||
):
|
||||
if not HAVE_TODE:
|
||||
raise RuntimeError(
|
||||
"TODE sampler requires torchode installed in venv. Example: pip install torchode"
|
||||
)
|
||||
super().__init__(*args, **kwargs)
|
||||
self.de_solver_method = tode.interface.METHODS[self.de_solver_name]
|
||||
self.de_ctl_pcoeff = de_ctl_pcoeff
|
||||
self.de_ctl_icoeff = de_ctl_icoeff
|
||||
self.de_ctl_dcoeff = de_ctl_dcoeff
|
||||
self.de_compile = tode_compile
|
||||
self.de_initial_step = de_initial_step
|
||||
|
||||
def check_solver_support(self):
|
||||
if not HAVE_TODE:
|
||||
raise RuntimeError(
|
||||
"TODE sampler requires torchode installed in venv. Example: pip install torchode"
|
||||
)
|
||||
|
||||
def step(self, x):
|
||||
s, sn, sigma_down, sigma_up = self.de_get_step(x)
|
||||
if self.de_min_sigma is not None and s <= self.de_min_sigma:
|
||||
return (yield from self.euler_step(x))
|
||||
ss = self.ss
|
||||
delta = (ss.sigma - sigma_down).item()
|
||||
mcc = 0
|
||||
pbar = None
|
||||
b, c, h, w = x.shape
|
||||
|
||||
def odefn(t, y_flat):
|
||||
nonlocal mcc
|
||||
if torch.all(t <= 1e-05).item():
|
||||
return torch.zeros_like(y_flat)
|
||||
if mcc >= self.de_max_nfe:
|
||||
raise RuntimeError("TDEStep: Model call limit exceeded")
|
||||
|
||||
pct = (s - t) / delta
|
||||
pbar.n = round(pct.min().item() * 999)
|
||||
pbar.update(0)
|
||||
pbar.set_description(
|
||||
f"{self.de_solver_name}({mcc}/{self.de_max_nfe})", refresh=True
|
||||
)
|
||||
y = y_flat.reshape(-1, c, h, w)
|
||||
t32 = t.to(torch.float32)
|
||||
del y_flat
|
||||
|
||||
if mcc == 0 and torch.all(t == s):
|
||||
mr = ss.hcur
|
||||
mcc = 1
|
||||
else:
|
||||
mr = self.call_model(y, t32.clamp(min=1e-05), call_index=mcc)
|
||||
mcc += 1
|
||||
result = self.to_d(mr).flatten(start_dim=1)
|
||||
for bi in range(t.shape[0]):
|
||||
if t[bi] <= 1e-05:
|
||||
result[bi, :] = 0
|
||||
return result
|
||||
|
||||
t = torch.stack((s, sigma_down)).to(torch.float64).repeat(b, 1)
|
||||
|
||||
pbar = tqdm.tqdm(
|
||||
total=1000, desc=self.de_solver_name, leave=True, disable=ss.disable_status
|
||||
)
|
||||
|
||||
term = tode.ODETerm(odefn)
|
||||
method = self.de_solver_method(term=term)
|
||||
controller = tode.PIDController(
|
||||
term=term,
|
||||
atol=self.de_atol,
|
||||
rtol=self.de_rtol,
|
||||
dt_min=1e-05,
|
||||
pcoeff=self.de_ctl_pcoeff,
|
||||
icoeff=self.de_ctl_icoeff,
|
||||
dcoeff=self.de_ctl_dcoeff,
|
||||
)
|
||||
solver_ = tode.AutoDiffAdjoint(method, controller)
|
||||
solver = solver_ if not self.de_compile else torch.compile(solver_)
|
||||
problem = tode.InitialValueProblem(
|
||||
y0=x.flatten(start_dim=1), t_start=t[:, 0], t_end=t[:, -1]
|
||||
)
|
||||
dt0 = (
|
||||
(t[:, -1] - t[:, 0]) * self.de_initial_step
|
||||
if self.de_initial_step
|
||||
else None
|
||||
)
|
||||
solution = solver.solve(problem, dt0=dt0)
|
||||
|
||||
# print("\nSOLUTION", solution.stats, solution.ys.shape)
|
||||
result = solution.ys[:, -1].reshape(-1, c, h, w)
|
||||
del solution
|
||||
|
||||
sigma_up, result = yield from self.adjusted_step(sn, result, mcc, sigma_up)
|
||||
if pbar is not None:
|
||||
pbar.n = pbar.total
|
||||
pbar.update(0)
|
||||
pbar.close()
|
||||
yield from self.result(result, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
registry.add(TODEStep)
|
||||
@@ -0,0 +1,192 @@
|
||||
import contextlib
|
||||
|
||||
import torch
|
||||
import tqdm
|
||||
|
||||
from . import registry
|
||||
from .solver_base import DESolverStep
|
||||
|
||||
HAVE_TSDE = False
|
||||
with contextlib.suppress(ImportError):
|
||||
import torchsde
|
||||
|
||||
HAVE_TSDE = True
|
||||
|
||||
|
||||
class TSDEStep(DESolverStep):
|
||||
name = "tsde"
|
||||
model_calls = -1
|
||||
allow_alt_cfgpp = True
|
||||
de_default_solver = "reversible_heun"
|
||||
default_eta = 0.0
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*args,
|
||||
de_initial_step=0.25,
|
||||
de_split=1,
|
||||
de_adaptive=False,
|
||||
tsde_noise_type="scalar",
|
||||
tsde_sde_type="stratonovich",
|
||||
tsde_levy_area_approx="none",
|
||||
tsde_noise_channels=1,
|
||||
tsde_g_multiplier=0.05,
|
||||
tsde_g_reverse_time=True,
|
||||
tsde_g_derp_mode=False,
|
||||
tsde_batch_channels=True,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.de_initial_step = de_initial_step
|
||||
self.de_adaptive = de_adaptive
|
||||
self.de_split = de_split
|
||||
self.de_noise_type = tsde_noise_type
|
||||
self.de_sde_type = tsde_sde_type
|
||||
self.de_levy_area_approx = tsde_levy_area_approx
|
||||
self.de_g_multiplier = tsde_g_multiplier
|
||||
self.de_noise_channels = tsde_noise_channels
|
||||
self.de_g_reverse_time = tsde_g_reverse_time
|
||||
self.de_g_derp_mode = tsde_g_derp_mode
|
||||
self.de_batch_channels = tsde_batch_channels
|
||||
|
||||
def check_solver_support(self):
|
||||
if not HAVE_TSDE:
|
||||
raise RuntimeError(
|
||||
"TSDE sampler requires torchsde installed in venv. Example: pip install torchsde"
|
||||
)
|
||||
|
||||
def step(self, x):
|
||||
s, sn, sigma_down, sigma_up = self.de_get_step(x)
|
||||
if self.de_min_sigma is not None and s <= self.de_min_sigma:
|
||||
return (yield from self.euler_step(x))
|
||||
ss = self.ss
|
||||
delta = (ss.sigma - sigma_down).item()
|
||||
bidx = 0
|
||||
mcc = 0
|
||||
pbar = None
|
||||
_b, c, h, w = x.shape
|
||||
outer_self = self
|
||||
|
||||
class SDE(torch.nn.Module):
|
||||
noise_type = outer_self.de_noise_type
|
||||
sde_type = outer_self.de_sde_type
|
||||
|
||||
@torch.no_grad()
|
||||
def f(self, t_rev, y_flat):
|
||||
nonlocal mcc
|
||||
t = s - (t_rev - sigma_down)
|
||||
# print(f"\nf at t_rev={t_rev}, t={t} :: {y_flat.shape}")
|
||||
if torch.all(t <= 1e-05).item():
|
||||
return torch.zeros_like(y_flat)
|
||||
if mcc >= outer_self.de_max_nfe:
|
||||
raise RuntimeError("TSDEStep: Model call limit exceeded")
|
||||
|
||||
pct = (s - t) / delta
|
||||
pbar.n = round(pct.min().item() * 999)
|
||||
pbar.update(0)
|
||||
pbar.set_description(
|
||||
f"{outer_self.de_solver_name}({mcc}/{outer_self.de_max_nfe})",
|
||||
refresh=True,
|
||||
)
|
||||
flat_shape = y_flat.shape
|
||||
y = y_flat.view(1, c, h, w)
|
||||
t32 = t.to(torch.float32)
|
||||
del y_flat
|
||||
|
||||
if mcc == 0 and torch.all(t == s):
|
||||
mr_cached = True
|
||||
mr = ss.hcur
|
||||
mcc = 1
|
||||
else:
|
||||
mr_cached = False
|
||||
mr = outer_self.call_model(
|
||||
y, t32.clamp(min=1e-05), call_index=mcc, s_in=t.new_ones(1)
|
||||
)
|
||||
mcc += 1
|
||||
return -outer_self.to_d(mr)[bidx if mr_cached else 0].view(*flat_shape)
|
||||
|
||||
@torch.no_grad()
|
||||
def g(self, t_rev, y_flat):
|
||||
t = (s - sigma_down) - (t_rev - sigma_down)
|
||||
pct = t / (s - sigma_down)
|
||||
if outer_self.de_g_reverse_time:
|
||||
pct = 1.0 - pct
|
||||
multiplier = outer_self.de_g_multiplier
|
||||
if outer_self.de_g_derp_mode and mcc % 2 == 0:
|
||||
multiplier *= -1
|
||||
val = t * pct * multiplier
|
||||
if self.noise_type == "diagonal":
|
||||
out = val.repeat(*y_flat.shape)
|
||||
elif self.noise_type == "scalar":
|
||||
out = val.repeat(*y_flat.shape, 1)
|
||||
else:
|
||||
out = val.repeat(*y_flat.shape, outer_self.de_noise_channels)
|
||||
return out
|
||||
|
||||
t = torch.stack((sigma_down, s)).to(torch.float)
|
||||
|
||||
pbar = tqdm.tqdm(
|
||||
total=1000, desc=self.de_solver_name, leave=True, disable=ss.disable_status
|
||||
)
|
||||
|
||||
dt0 = (
|
||||
delta * self.de_initial_step if self.de_adaptive else delta / self.de_split
|
||||
)
|
||||
results = []
|
||||
for batch in tqdm.trange(
|
||||
1,
|
||||
x.shape[0] + 1,
|
||||
desc="batch",
|
||||
leave=False,
|
||||
disable=x.shape[0] == 1 or ss.disable_status,
|
||||
):
|
||||
bidx = batch - 1
|
||||
mcc = 0
|
||||
sde = SDE()
|
||||
if self.de_batch_channels:
|
||||
y_flat = x[bidx].flatten(start_dim=1)
|
||||
else:
|
||||
y_flat = x[bidx].unsqueeze(0).flatten(start_dim=1)
|
||||
if sde.noise_type == "diagonal":
|
||||
bm_size = (y_flat.shape[0], y_flat.shape[1])
|
||||
elif sde.noise_type == "scalar":
|
||||
bm_size = (y_flat.shape[0], 1)
|
||||
else:
|
||||
bm_size = (y_flat.shape[0], self.de_noise_channels)
|
||||
bm = torchsde.BrownianInterval(
|
||||
dtype=x.dtype,
|
||||
device=x.device,
|
||||
t0=-s,
|
||||
t1=s,
|
||||
entropy=ss.noise.seed,
|
||||
levy_area_approximation=self.de_levy_area_approx,
|
||||
tol=1e-06,
|
||||
size=bm_size,
|
||||
)
|
||||
|
||||
ys = torchsde.sdeint(
|
||||
sde,
|
||||
y_flat,
|
||||
t,
|
||||
method=self.de_solver_name,
|
||||
adaptive=self.de_adaptive,
|
||||
atol=self.de_atol,
|
||||
rtol=self.de_rtol,
|
||||
dt=dt0,
|
||||
bm=bm,
|
||||
)
|
||||
del y_flat
|
||||
results.append(ys[-1].view(1, c, h, w))
|
||||
del ys
|
||||
result = torch.cat(results)
|
||||
del results
|
||||
|
||||
sigma_up, result = yield from self.adjusted_step(sn, result, mcc, sigma_up)
|
||||
if pbar is not None:
|
||||
pbar.n = pbar.total
|
||||
pbar.update(0)
|
||||
pbar.close()
|
||||
yield from self.result(result, sigma_up, sigma_down=sigma_down)
|
||||
|
||||
|
||||
registry.add(TSDEStep)
|
||||
+694
-195
@@ -1,214 +1,394 @@
|
||||
import torch
|
||||
import operator
|
||||
|
||||
from .utils import scale_noise, find_first_unsorted
|
||||
from .substep_sampling import History
|
||||
import torch
|
||||
import tqdm
|
||||
|
||||
from . import expression as expr
|
||||
from . import utils
|
||||
|
||||
from .filtering import make_filter, FilterRefs, FILTER_HANDLERS
|
||||
from .noise import ImmiscibleNoise
|
||||
from .restart import Restart
|
||||
from .step_samplers import STEP_SAMPLERS
|
||||
from .step_samplers.base import StepSamplerContext
|
||||
from .substep_sampling import StepSamplerChain
|
||||
from .utils import check_time, fallback
|
||||
|
||||
|
||||
class MergeSubstepsSampler:
|
||||
def __init__(self, ss, samplers, **_kwargs):
|
||||
name = "unknown"
|
||||
|
||||
def __init__(self, ss, group):
|
||||
samplers = tuple(
|
||||
STEP_SAMPLERS[sitem["step_method"]](**sitem) for sitem in group.items
|
||||
)
|
||||
options = group.options.copy()
|
||||
self.group = group
|
||||
self.time_mode = group.time_mode
|
||||
self.time_start = group.time_start
|
||||
self.time_end = group.time_end
|
||||
self.ss = ss
|
||||
self.samplers = samplers
|
||||
self.substeps = sum(sampler.substeps for sampler in samplers)
|
||||
when_expr = options.pop("when", None)
|
||||
self.when = expr.Expression(when_expr) if when_expr else None
|
||||
pre_filter = options.pop("pre_filter", None)
|
||||
post_filter = options.pop("post_filter", None)
|
||||
self.pre_filter = None if pre_filter is None else make_filter(pre_filter)
|
||||
self.post_filter = None if post_filter is None else make_filter(post_filter)
|
||||
self.preview_mode = options.pop("preview_mode", "denoised")
|
||||
self.require_uncond = any(sampler.require_uncond for sampler in samplers)
|
||||
self.cfg_scale_override = options.pop("cfg_scale_override", None)
|
||||
self.afs_start_step = options.pop("afs_start_step", 0)
|
||||
self.afs_end_step = options.pop("afs_end_step", -1)
|
||||
self.options = options
|
||||
|
||||
def check_match(self, handlers: None | object, *, ss: None | object = None):
|
||||
ss = fallback(ss, self.ss)
|
||||
if not check_time(
|
||||
self.time_mode,
|
||||
self.time_start,
|
||||
self.time_end,
|
||||
ss.sigma,
|
||||
ss.step,
|
||||
ss.total_steps,
|
||||
):
|
||||
return False
|
||||
if self.when is None:
|
||||
return True
|
||||
if handlers is None:
|
||||
raise ValueError("Group has when expression but handlers not passed")
|
||||
return operator.truth(self.when.eval(handlers))
|
||||
|
||||
def step_input(self, x, *, ss=None):
|
||||
ss = fallback(ss, self.ss)
|
||||
ss.noise.update_x(x)
|
||||
if self.pre_filter is None:
|
||||
return x
|
||||
x = self.pre_filter.apply(x, refs=fallback(ss, self.ss).refs)
|
||||
ss.noise.update_x(x)
|
||||
return x
|
||||
|
||||
def step_output(self, x, *, orig_x=None, ss=None):
|
||||
ss = fallback(ss, self.ss)
|
||||
ss.noise.update_x(x)
|
||||
if self.post_filter is None:
|
||||
return x
|
||||
refs = ss.refs if orig_x is None else ss.refs | FilterRefs({"orig_x": orig_x})
|
||||
x = self.post_filter.apply(x, refs=refs)
|
||||
ss.noise.update_x(x)
|
||||
return x
|
||||
|
||||
def __call__(self, x):
|
||||
orig_x = x
|
||||
x = self.step_input(x)
|
||||
if self.afs_start_step <= self.ss.step <= self.afs_end_step:
|
||||
x = self.afs_step(x)
|
||||
else:
|
||||
x = self.step(x)
|
||||
return self.step_output(x, orig_x=orig_x)
|
||||
|
||||
# From https://arxiv.org/abs/2210.05475
|
||||
def afs_step(self, x):
|
||||
sigma, sigma_next = self.ss.sigma, self.ss.sigma_next
|
||||
afs_d = x / ((1 + sigma**2).sqrt())
|
||||
dt = sigma_next - sigma
|
||||
return x + afs_d * dt
|
||||
|
||||
def step(self, x):
|
||||
raise NotImplementedError
|
||||
|
||||
def merge_steps(self, _x, result):
|
||||
def substep(self, x, sampler):
|
||||
sg = sampler(x)
|
||||
yield from utils.step_generator(sg, get_next=lambda sr: sr.x)
|
||||
|
||||
def simple_substep(self, x, sampler):
|
||||
for sr in self.substep(x, sampler):
|
||||
if not sr.final:
|
||||
raise RuntimeError("Unexpected non-final sampler result in substep!")
|
||||
return sr
|
||||
|
||||
def merge_steps(self, x, result=None, *, noise=None, ss=None, denoised=True):
|
||||
ss = ss if ss is not None else self.ss
|
||||
result = fallback(result, x)
|
||||
if noise is not None:
|
||||
result = result + noise
|
||||
return result
|
||||
|
||||
def step_max_noise_samples(self):
|
||||
return sum(
|
||||
(1 + sampler.self_noise) * sampler.substeps for sampler in self.samplers
|
||||
)
|
||||
|
||||
class NormalMergeSubstepsSampler(MergeSubstepsSampler):
|
||||
def __init__(self, ss, samplers, **kwargs):
|
||||
super().__init__(ss, samplers, **kwargs)
|
||||
self.ss = ss
|
||||
def reset(self):
|
||||
pass
|
||||
|
||||
def callback(self, *, ss=None, mr=None, preview_mode=None):
|
||||
ss = fallback(ss, self.ss)
|
||||
preview_mode = fallback(preview_mode, self.preview_mode)
|
||||
return ss.callback(hi=mr, preview_mode=preview_mode)
|
||||
|
||||
def call_model(self, x, ss=None, sigma=None, **kwargs):
|
||||
ss = fallback(ss, self.ss)
|
||||
sigma = fallback(sigma, ss.sigma)
|
||||
return ss.call_model(
|
||||
x,
|
||||
sigma,
|
||||
ss=ss,
|
||||
cfg_scale_override=self.cfg_scale_override,
|
||||
require_uncond=self.require_uncond,
|
||||
)
|
||||
|
||||
|
||||
class SimpleSubstepsSampler(MergeSubstepsSampler):
|
||||
name = "simple"
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if not len(self.samplers):
|
||||
raise ValueError("Missing sampler")
|
||||
|
||||
def step_max_noise_samples(self):
|
||||
return 1 + self.samplers[0].self_noise
|
||||
|
||||
def step(self, x):
|
||||
ss, ssampler = self.ss, self.samplers[0]
|
||||
ss.hist.push(self.call_model(x))
|
||||
ss.refs = FilterRefs.from_ss(ss, have_current=True)
|
||||
self.callback()
|
||||
with StepSamplerContext(ssampler, ss) as ssampler:
|
||||
sr = self.simple_substep(x, ssampler)
|
||||
return self.merge_steps(sr.noise_x(ss=ss))
|
||||
|
||||
|
||||
class SupremeAvgMergeSubstepsSampler(MergeSubstepsSampler):
|
||||
name = "supreme_avg"
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
substeps = self.substeps
|
||||
renoise_weight = 1.0 / substeps
|
||||
z_avg = torch.zeros_like(x)
|
||||
noise = torch.zeros_like(x)
|
||||
noise = z_avg.clone()
|
||||
noise_total = 0.0
|
||||
for idx, ssampler in enumerate(
|
||||
sampler for sampler in self.samplers for _ in range(sampler.substeps)
|
||||
):
|
||||
print(f" SUBSTEP {idx+1}: {ssampler.name}")
|
||||
ss.denoised = ss.model(x, ss.sigma)
|
||||
z_k, noise_strength = ssampler.step(x, ss)
|
||||
z_avg += renoise_weight * z_k
|
||||
noise_strength *= ssampler.s_noise
|
||||
if ss.sigma_next == 0 or noise_strength == 0:
|
||||
continue
|
||||
noise_curr = ssampler.noise_sampler(ss.sigma, ss.sigma_next)
|
||||
x = z_k
|
||||
if idx != substeps - 1:
|
||||
x += noise_curr * noise_strength
|
||||
noise_total += noise_strength.item() * renoise_weight
|
||||
noise += noise_curr * noise_strength
|
||||
ss.dhist.push(ss.denoised)
|
||||
ss.denoised = None
|
||||
x = self.merge_steps(x, z_avg)
|
||||
if ss.sigma_next != 0 and noise_total != 0:
|
||||
x += scale_noise(noise, noise_total * ss.s_noise)
|
||||
ss.xhist.push(x)
|
||||
ss.callback(x)
|
||||
return x
|
||||
substep = 0
|
||||
pbar = tqdm.tqdm(total=self.substeps, initial=1, disable=ss.disable_status)
|
||||
ss.hist.push(self.call_model(x))
|
||||
ss.refs = FilterRefs.from_ss(ss, have_current=True)
|
||||
self.callback()
|
||||
for ssampler_ in self.samplers:
|
||||
with StepSamplerContext(ssampler_, ss) as ssampler:
|
||||
for subidx in range(ssampler.substeps):
|
||||
pbar.set_description(f"{ssampler.name}: {substep + 1}/{substeps}")
|
||||
sr = self.simple_substep(x, ssampler)
|
||||
z_avg += renoise_weight * sr.x
|
||||
if sr.noise_scale != 0 and ss.sigma_next != 0:
|
||||
noise_total += renoise_weight * sr.noise_scale
|
||||
noise += renoise_weight * sr.get_noise(ss=ss)
|
||||
substep += 1
|
||||
ss.substep = substep
|
||||
pbar.update(1)
|
||||
|
||||
noise = ss.noise.scale_noise(
|
||||
noise,
|
||||
noise_total * self.options.get("s_noise", 1.0),
|
||||
normalized=True,
|
||||
)
|
||||
return self.merge_steps(
|
||||
x, z_avg, noise=None if noise_total == 0 else noise, denoised=ss.denoised
|
||||
)
|
||||
|
||||
|
||||
class AverageMergeSubstepsSampler(NormalMergeSubstepsSampler):
|
||||
def __init__(self, ss, samplers, *, avgmerge_stretch=0.4, **kwargs):
|
||||
super().__init__(ss, samplers, **kwargs)
|
||||
self.ss = ss
|
||||
self.stretch = avgmerge_stretch
|
||||
# class AverageMergeSubstepsSampler(NormalMergeSubstepsSampler):
|
||||
# name = "average"
|
||||
|
||||
def step(self, x):
|
||||
ss = orig_ss = self.ss
|
||||
substeps = self.substeps
|
||||
renoise_weight = 1.0 / substeps
|
||||
z_avg = torch.zeros_like(x)
|
||||
noise = torch.zeros_like(x)
|
||||
stretch = (ss.sigma - ss.sigma_next) * self.stretch
|
||||
sig_adj = ss.sigma + stretch
|
||||
ss = self.ss.clone_edit(sigma=sig_adj)
|
||||
orig_x = x
|
||||
x = x + ss.noise_sampler(orig_ss.sigma, ss.sigma_next) * stretch * ss.s_noise
|
||||
ss.denoised = ss.model(x, sig_adj)
|
||||
noise_total = 0.0
|
||||
step = 0
|
||||
for idx, ssampler in enumerate(self.samplers):
|
||||
print(
|
||||
f" SUBSTEP {step+1} .. {step+ssampler.substeps}: {ssampler.name}, stretch={stretch}"
|
||||
)
|
||||
for sidx in range(ssampler.substeps):
|
||||
curr_x = orig_x + scale_noise(
|
||||
ssampler.noise_sampler(sig_adj, ss.sigma_next), stretch
|
||||
)
|
||||
z_k, noise_strength = ssampler.step(curr_x, ss)
|
||||
z_avg += renoise_weight * z_k
|
||||
if ss.sigma_next == 0:
|
||||
continue
|
||||
noise_strength *= ssampler.s_noise
|
||||
if noise_strength == 0:
|
||||
continue
|
||||
noise_curr = ssampler.noise_sampler(ss.sigma, ss.sigma_next)
|
||||
noise_total += noise_strength.item() * renoise_weight
|
||||
noise += noise_curr * noise_strength
|
||||
step += ssampler.substeps
|
||||
ss.dhist.push(ss.denoised)
|
||||
ss.denoised = None
|
||||
x = self.merge_steps(x, z_avg)
|
||||
if ss.sigma_next != 0 and noise_total != 0:
|
||||
x += scale_noise(noise, noise_total * ss.s_noise)
|
||||
ss.xhist.push(x)
|
||||
ss.callback(x)
|
||||
return x
|
||||
# def __init__(self, ss, sitems, *, avgmerge_stretch=0.4, **kwargs):
|
||||
# super().__init__(ss, sitems, **kwargs)
|
||||
# self.stretch = avgmerge_stretch
|
||||
|
||||
# def step_max_noise_samples(self):
|
||||
# return sum(
|
||||
# 1 + (2 + sampler.self_noise) * sampler.substeps for sampler in self.samplers
|
||||
# )
|
||||
|
||||
# def step(self, x):
|
||||
# ss = orig_ss = self.ss
|
||||
# substeps = self.substeps
|
||||
# renoise_weight = 1.0 / substeps
|
||||
# z_avg = torch.zeros_like(x)
|
||||
# noise = torch.zeros_like(x)
|
||||
# stretch = (ss.sigma - ss.sigma_next) * self.stretch
|
||||
# sig_adj = ss.sigma + stretch
|
||||
# ss = self.ss.clone_edit(sigma=sig_adj)
|
||||
# orig_x = x
|
||||
# stretch_strength = stretch * ss.s_noise
|
||||
# if stretch_strength != 0:
|
||||
# noise_sampler = ss.noise.make_caching_noise_sampler(
|
||||
# self.options.get("custom_noise"), 1, orig_ss.sigma, ss.sigma_next
|
||||
# )
|
||||
# x = x + (
|
||||
# noise_sampler(orig_ss.sigma, ss.sigma_next).mul_(stretch * ss.s_noise)
|
||||
# )
|
||||
# self.ss.denoised = ss.denoised = ss.model(x, sig_adj)
|
||||
# noise_total = 0.0
|
||||
# substep = 0
|
||||
# for idx, ssampler in enumerate(self.samplers):
|
||||
# print(
|
||||
# f" SUBSTEP {substep + 1} .. {substep + ssampler.substeps}: {ssampler.name}, stretch={stretch}"
|
||||
# )
|
||||
# custom_noise = ssampler.options.get(
|
||||
# "custom_noise", self.options.get("custom_noise")
|
||||
# )
|
||||
# noise_sampler = ss.noise.make_caching_noise_sampler(
|
||||
# custom_noise,
|
||||
# ssampler.substeps
|
||||
# + (0 if ss.sigma_next == 0 else ssampler.max_noise_samples),
|
||||
# ss.sigma,
|
||||
# ss.sigma_next,
|
||||
# )
|
||||
# ssampler.noise_sampler = noise_sampler
|
||||
# for sidx in range(ssampler.substeps):
|
||||
# curr_x = orig_x + noise_sampler(sig_adj, ss.sigma_next).mul_(stretch)
|
||||
# sr = self.simple_substep(curr_x, ssampler, ss=ss)
|
||||
# z_avg += renoise_weight * sr.x
|
||||
# noise_strength = sr.noise_scale
|
||||
# if ss.sigma_next == 0 or noise_strength == 0:
|
||||
# continue
|
||||
# if noise_strength != 0 and ss.sigma_next != 0:
|
||||
# noise_curr = sr.get_noise()
|
||||
# noise_total += noise_strength.item() * renoise_weight
|
||||
# noise += noise_curr
|
||||
# substep += 1
|
||||
# substep += ssampler.substeps
|
||||
# return self.merge_steps(
|
||||
# x,
|
||||
# z_avg,
|
||||
# noise=None
|
||||
# if not noise_total
|
||||
# else ss.noise.scale_noise(noise, noise_total * ss.s_noise, normalized=True),
|
||||
# ss=ss,
|
||||
# )
|
||||
|
||||
|
||||
class SampleMergeSubstepsSampler(AverageMergeSubstepsSampler):
|
||||
cache_model = True
|
||||
# class SampleMergeSubstepsSampler(AverageMergeSubstepsSampler):
|
||||
# name = "sample"
|
||||
# cache_model = True
|
||||
|
||||
def __init__(self, ss, samplers, *, merge_sampler, **kwargs):
|
||||
super().__init__(ss, samplers, **kwargs)
|
||||
self.merge_sampler = merge_sampler
|
||||
self.merge_ss = None
|
||||
# def __init__(self, ss, sitems, *, merge_sampler=None, **kwargs):
|
||||
# super().__init__(ss, sitems, **kwargs)
|
||||
# if merge_sampler is None:
|
||||
# merge_sampler = STEP_SAMPLERS["euler"](step_method="euler")
|
||||
# else:
|
||||
# msitem = merge_sampler.items[0]
|
||||
# merge_sampler = STEP_SAMPLERS[msitem["step_method"]](**msitem)
|
||||
# self.merge_sampler = merge_sampler
|
||||
# self.merge_ss = None
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
substeps = self.substeps
|
||||
renoise_weight = 1.0 / substeps
|
||||
z_avg = torch.zeros_like(x)
|
||||
curr_x = x
|
||||
ss.denoised = None
|
||||
stretch = (ss.sigma - ss.sigma_next) * self.stretch
|
||||
sig_adj = ss.sigma + stretch
|
||||
ss = self.ss.clone_edit(sigma=sig_adj)
|
||||
step = 0
|
||||
for idx, ssampler in enumerate(self.samplers):
|
||||
print(
|
||||
f" SUBSTEP {step+1} .. {step+ssampler.substeps}: {ssampler.name}, stretch={stretch}"
|
||||
)
|
||||
if idx == 0 or not self.cache_model:
|
||||
ss.denoised = ss.model(
|
||||
curr_x,
|
||||
# + ss.noise_sampler(sig_adj.sigma, ss.sigma_next) * stretch * ss.s_noise,
|
||||
sig_adj,
|
||||
)
|
||||
for sidx in range(ssampler.substeps):
|
||||
curr_x = (
|
||||
x
|
||||
+ ssampler.noise_sampler(sig_adj, ss.sigma_next)
|
||||
* ssampler.s_noise
|
||||
* stretch
|
||||
)
|
||||
z_k, noise_strength = ssampler.step(curr_x, ss)
|
||||
z_avg += renoise_weight * z_k
|
||||
curr_x = z_k
|
||||
if noise_strength == 0 or ss.sigma_next == 0:
|
||||
continue
|
||||
curr_x += (
|
||||
ssampler.noise_sampler(ss.sigma, ss.sigma_next)
|
||||
* ssampler.s_noise
|
||||
* noise_strength
|
||||
)
|
||||
step += ssampler.substeps
|
||||
ss.dhist.push(ss.denoised)
|
||||
ss.denoised = None
|
||||
x = self.merge_steps(curr_x, z_avg)
|
||||
ss.xhist.push(x)
|
||||
ss.callback(x)
|
||||
return x
|
||||
# def step(self, x):
|
||||
# ss = self.ss
|
||||
# substeps = self.substeps
|
||||
# renoise_weight = 1.0 / substeps
|
||||
# z_avg = torch.zeros_like(x)
|
||||
# curr_x = x
|
||||
# ss.denoised = None
|
||||
# stretch = (ss.sigma - ss.sigma_next) * self.stretch
|
||||
# sig_adj = ss.sigma + stretch
|
||||
# ss = self.ss.clone_edit(sigma=sig_adj)
|
||||
# step = 0
|
||||
# for idx, ssampler in enumerate(self.samplers):
|
||||
# print(
|
||||
# f" SUBSTEP {step + 1} .. {step + ssampler.substeps}: {ssampler.name}, stretch={stretch}"
|
||||
# )
|
||||
# custom_noise = ssampler.options.get(
|
||||
# "custom_noise", self.options.get("custom_noise")
|
||||
# )
|
||||
# noise_sampler = ss.noise.make_caching_noise_sampler(
|
||||
# custom_noise,
|
||||
# ssampler.max_noise_samples + ssampler.substeps,
|
||||
# ss.sigma,
|
||||
# ss.sigma_next,
|
||||
# )
|
||||
# ssampler.noise_sampler = noise_sampler
|
||||
# for sidx in range(ssampler.substeps):
|
||||
# if idx + sidx == 0 or not self.cache_model:
|
||||
# self.ss.denoised = ss.denoised = ss.model(
|
||||
# curr_x,
|
||||
# ss.sigma,
|
||||
# # + ss.noise_sampler(sig_adj.sigma, ss.sigma_next) * stretch * ss.s_noise,
|
||||
# # sig_adj,
|
||||
# )
|
||||
# curr_x = x + noise_sampler(sig_adj, ss.sigma_next).mul_(
|
||||
# ssampler.s_noise * stretch
|
||||
# )
|
||||
# sr = self.simple_substep(curr_x, ssampler, ss=ss)
|
||||
# z_avg += renoise_weight * sr.x
|
||||
# curr_x = sr.noise_x(sr.x)
|
||||
# step += ssampler.substeps
|
||||
# return self.merge_steps(curr_x, z_avg)
|
||||
|
||||
def merge_steps(self, x, result):
|
||||
self.ss.model.reset_cache()
|
||||
msampler = self.merge_sampler
|
||||
if self.merge_ss is None:
|
||||
merge_ss = self.merge_ss = self.ss.clone_edit(
|
||||
denoised=result,
|
||||
dhist=History(x, 3),
|
||||
xhist=History(x, 2),
|
||||
s_noise=msampler.s_noise,
|
||||
eta=msampler.eta,
|
||||
# model_call_cache=None,
|
||||
)
|
||||
else:
|
||||
merge_ss = self.merge_ss
|
||||
merge_ss.denoised = result
|
||||
merge_ss.update(self.ss.idx)
|
||||
final = merge_ss.sigma_next == 0
|
||||
merged, noise_strength = msampler.step(x, merge_ss)
|
||||
if not final:
|
||||
ss = self.ss
|
||||
merged = (
|
||||
merged
|
||||
+ msampler.noise_sampler(ss.sigma, ss.sigma_next)
|
||||
* msampler.s_noise
|
||||
* ss.sigma_up
|
||||
)
|
||||
merge_ss.dhist.push(result)
|
||||
merge_ss.xhist.push(merged)
|
||||
merge_ss.denoised = None
|
||||
return merged
|
||||
# def merge_steps(self, x, result):
|
||||
# ss = self.ss
|
||||
# ss.dhist.push(ss.denoised)
|
||||
# ss.denoised = None
|
||||
# ss.model.reset_cache()
|
||||
# msampler = self.merge_sampler
|
||||
# if self.merge_ss is None:
|
||||
# merge_ss = self.merge_ss = self.ss.clone_edit(
|
||||
# denoised=result,
|
||||
# dhist=History(x, 3),
|
||||
# xhist=History(x, 2),
|
||||
# s_noise=msampler.s_noise,
|
||||
# eta=msampler.eta,
|
||||
# )
|
||||
# else:
|
||||
# merge_ss = self.merge_ss
|
||||
# merge_ss.denoised = result
|
||||
# merge_ss.update(self.ss.idx, step=self.ss.step)
|
||||
# final = merge_ss.sigma_next == 0
|
||||
# noise_sampler = merge_ss.noise.make_caching_noise_sampler(
|
||||
# msampler.options.get("custom_noise", self.options.get("custom_noise")),
|
||||
# msampler.max_noise_samples + int(not final),
|
||||
# merge_ss.sigma,
|
||||
# merge_ss.sigma_next,
|
||||
# )
|
||||
# msampler.noise_sampler = noise_sampler
|
||||
# sr = self.simple_substep(x, msampler, ss=merge_ss)
|
||||
# self.ss.callback(sr.x)
|
||||
# sr.noise_x()
|
||||
# merge_ss.dhist.push(result)
|
||||
# merge_ss.xhist.push(sr.x)
|
||||
# merge_ss.denoised = None
|
||||
# ss.xhist.push(sr.x)
|
||||
# return sr.x
|
||||
|
||||
# def reset(self):
|
||||
# if self.merge_ss is None:
|
||||
# return
|
||||
# self.merge_ss.reset()
|
||||
# self.merge_ss.sigmas = self.ss.sigmas
|
||||
# self.merge_ss.update(self.ss.idx, step=self.ss.step)
|
||||
|
||||
|
||||
class SampleUncachedMergeSubstepsSampler(SampleMergeSubstepsSampler):
|
||||
cache_model = False
|
||||
# class SampleUncachedMergeSubstepsSampler(SampleMergeSubstepsSampler):
|
||||
# name = "sample_uncached"
|
||||
# cache_model = False
|
||||
|
||||
|
||||
class DivideMergeSubstepsSampler(MergeSubstepsSampler):
|
||||
def __init__(self, ss, samplers, *, schedule_multiplier=4, **kwargs):
|
||||
super().__init__(ss, samplers, **kwargs)
|
||||
self.schedule_multiplier = schedule_multiplier
|
||||
name = "divide"
|
||||
|
||||
def __init__(self, ss, group, **kwargs):
|
||||
super().__init__(ss, group, **kwargs)
|
||||
self.schedule_multiplier = self.options.pop("schedule_multiplier", 4)
|
||||
|
||||
def make_schedule(self, ss):
|
||||
max_steps = len(self.ss.sigmas) - 1
|
||||
sigmas_slice = ss.sigmas[
|
||||
ss.idx : min(max_steps + 1, ss.idx + self.schedule_multiplier)
|
||||
]
|
||||
# print("SLICE", sigmas_slice)
|
||||
unsorted_idx = find_first_unsorted(sigmas_slice)
|
||||
unsorted_idx = utils.find_first_unsorted(sigmas_slice)
|
||||
if unsorted_idx is not None:
|
||||
sigmas_slice = sigmas_slice[:unsorted_idx]
|
||||
# print("SLICE ADJ", sigmas_slice)
|
||||
chunks = tuple(
|
||||
torch.linspace(
|
||||
sigmas_slice[idx],
|
||||
@@ -219,42 +399,361 @@ class DivideMergeSubstepsSampler(MergeSubstepsSampler):
|
||||
)[0 if not idx else 1 :]
|
||||
for idx in range(len(sigmas_slice) - 1)
|
||||
)
|
||||
# print("CHUNKS", chunks)
|
||||
return torch.cat(chunks)
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
# print("SUBSIGMAS", subsigmas)
|
||||
subss = self.ss.clone_edit(idx=0, sigmas=self.make_schedule(ss))
|
||||
subss.main_idx = ss.idx
|
||||
subss.main_sigmas = ss.sigmas
|
||||
|
||||
for idx, ssampler in enumerate(
|
||||
sampler for sampler in self.samplers for _ in range(sampler.substeps)
|
||||
):
|
||||
print(f" SUBSTEP {idx+1}: {ssampler.name}")
|
||||
subss.update(idx)
|
||||
subss.denoised = subss.model(x, subss.sigma)
|
||||
x, noise_strength = ssampler.step(x, subss)
|
||||
if noise_strength == 0 or subss.sigma_next == 0:
|
||||
continue
|
||||
x = (
|
||||
x
|
||||
+ ssampler.noise_sampler(subss.sigma, subss.sigma_next)
|
||||
* ssampler.s_noise
|
||||
* noise_strength
|
||||
)
|
||||
subss.xhist.push(x)
|
||||
subss.dhist.push(subss.denoised)
|
||||
subss.denoised = None
|
||||
ss.callback(x)
|
||||
substep = 0
|
||||
pbar = tqdm.tqdm(total=self.substeps, initial=0, disable=ss.disable_status)
|
||||
for ssampler_ in self.samplers:
|
||||
with StepSamplerContext(ssampler_, subss) as ssampler:
|
||||
for subidx in range(ssampler.substeps):
|
||||
subss.update(substep, substep=substep)
|
||||
pbar.set_description(
|
||||
f"substep({ssampler.name}): {subss.sigma.item():.03} -> {subss.sigma_next.item():.03}"
|
||||
)
|
||||
subss.hist.push(self.call_model(x, ss=subss))
|
||||
subss.refs = FilterRefs.from_ss(subss, have_current=True)
|
||||
if substep == 0:
|
||||
self.callback(ss=subss)
|
||||
sr = self.simple_substep(x, ssampler)
|
||||
x = sr.x
|
||||
noise_strength = sr.noise_scale
|
||||
if noise_strength != 0 and subss.sigma_next != 0:
|
||||
x = sr.noise_x(ss=subss)
|
||||
substep += 1
|
||||
pbar.update(1)
|
||||
pbar.update(0)
|
||||
return x
|
||||
|
||||
|
||||
class OvershootMergeSubstepsSampler(MergeSubstepsSampler):
|
||||
name = "overshoot"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
ss,
|
||||
group,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(ss, group, **kwargs)
|
||||
self.overshoot_expand_steps = self.options.pop("overshoot_expand_steps", 1)
|
||||
restart = self.options.pop("restart", {})
|
||||
restart_custom_noise = self.options.get("restart_custom_noise")
|
||||
if isinstance(restart_custom_noise, str):
|
||||
restart_custom_noise = self.options.get(
|
||||
f"restart_custom_noise_{restart_custom_noise}"
|
||||
)
|
||||
self.restart = Restart(
|
||||
s_noise=restart.get("s_noise", 1.0),
|
||||
custom_noise=restart_custom_noise,
|
||||
immiscible=restart.get("immiscible", False),
|
||||
)
|
||||
|
||||
def make_schedule(self, ss):
|
||||
expand = self.overshoot_expand_steps
|
||||
if expand > self.substeps:
|
||||
raise ValueError(
|
||||
"overshoot_expand_steps > substeps: can't make it to the end of step 1"
|
||||
)
|
||||
if expand < 2:
|
||||
return ss.sigmas, ss.idx
|
||||
sigmas_cpu = ss.sigmas.cpu()
|
||||
sigmas = torch.cat(
|
||||
tuple(
|
||||
torch.linspace(f, t, expand + 1)[:-1]
|
||||
for f, t in torch.stack((sigmas_cpu[:-1], sigmas_cpu[1:]), dim=1)
|
||||
)
|
||||
+ (sigmas_cpu[-1].unsqueeze(0),)
|
||||
)
|
||||
return sigmas.to(ss.sigmas), ss.idx * expand
|
||||
|
||||
def step(self, x):
|
||||
ss = self.ss
|
||||
sigmas, sigidx = self.make_schedule(ss)
|
||||
subss = ss.clone_edit(idx=sigidx, sigmas=sigmas)
|
||||
subss.hist = subss.hist.clone()
|
||||
substep = 0
|
||||
pbar = tqdm.tqdm(total=self.substeps, initial=0, disable=ss.disable_status)
|
||||
max_idx = len(subss.sigmas) - 2
|
||||
last_down = None
|
||||
for ssampler_ in self.samplers:
|
||||
with StepSamplerContext(ssampler_, subss) as ssampler:
|
||||
for subidx in range(ssampler.substeps):
|
||||
subss.update(subss.idx + substep, substep=substep)
|
||||
pbar.set_description(
|
||||
f"substep({ssampler.name}): {subss.sigma.item():.03} -> {subss.sigma_next.item():.03}"
|
||||
)
|
||||
subss.hist.push(self.call_model(x, ss=subss))
|
||||
subss.refs = FilterRefs.from_ss(subss, have_current=True)
|
||||
if substep == 0:
|
||||
ss.hist.push(subss.hcur)
|
||||
self.callback(ss=subss)
|
||||
sr = self.simple_substep(x, ssampler)
|
||||
x = sr.x
|
||||
noise_strength = sr.noise_scale
|
||||
if noise_strength != 0 and subss.sigma_next != 0:
|
||||
x = sr.noise_x(ss=subss)
|
||||
substep += 1
|
||||
pbar.update(1)
|
||||
last_down = subss.sigma_next.item()
|
||||
if subss.idx + substep >= max_idx:
|
||||
break
|
||||
if subss.idx >= max_idx:
|
||||
break
|
||||
if last_down is not None and last_down < ss.sigma_next:
|
||||
restart_ns = self.restart.get_noise_sampler(ss.noise)
|
||||
x += ss.noise.scale_noise(
|
||||
restart_ns(last_down, ss.sigma_next, refs=ss.refs),
|
||||
self.restart.get_noise_scale(last_down, ss.sigma_next),
|
||||
)
|
||||
pbar.update(0)
|
||||
return x
|
||||
|
||||
|
||||
class LookaheadMergeSubstepsSampler(MergeSubstepsSampler):
|
||||
name = "lookahead"
|
||||
|
||||
def __init__(self, ss, group, **kwargs):
|
||||
super().__init__(ss, group, **kwargs)
|
||||
lookahead = self.options.pop("lookahead", {}).copy()
|
||||
self.lookahead_eta = lookahead.pop("eta", 0.0)
|
||||
self.lookahead_s_noise = lookahead.pop("s_noise", 1.0)
|
||||
self.lookahead_dt_factor = lookahead.pop("dt_factor", 1.0)
|
||||
immiscible = lookahead.get("immiscible", False)
|
||||
self.immiscible = (
|
||||
ImmiscibleNoise(**immiscible) if immiscible is not False else False
|
||||
)
|
||||
|
||||
self.custom_noise = self.options.get("custom_noise")
|
||||
if isinstance(self.custom_noise, str):
|
||||
self.custom_noise = self.options.get(f"custom_noise_{self.custom_noise}")
|
||||
|
||||
def step(self, x):
|
||||
orig_x = x.clone()
|
||||
ss = self.ss
|
||||
subss = self.ss.clone_edit(idx=ss.idx, sigmas=ss.sigmas)
|
||||
substep = 0
|
||||
max_idx = len(ss.sigmas) - 1
|
||||
eff_substeps = min(max_idx - ss.idx, self.substeps)
|
||||
pbar = tqdm.tqdm(total=eff_substeps, initial=0, disable=ss.disable_status)
|
||||
for ssampler_ in self.samplers:
|
||||
substeps_remain = eff_substeps - substep
|
||||
if substeps_remain == 0:
|
||||
break
|
||||
with StepSamplerContext(ssampler_, subss) as ssampler:
|
||||
for subidx in range(min(substeps_remain, ssampler.substeps)):
|
||||
subss.update(ss.idx + substep, substep=substep)
|
||||
pbar.set_description(
|
||||
f"substep({ssampler.name}): {subss.sigma.item():.03} -> {subss.sigma_next.item():.03}"
|
||||
)
|
||||
subss.hist.push(self.call_model(x, ss=subss))
|
||||
subss.refs = FilterRefs.from_ss(subss, have_current=True)
|
||||
if substep == 0:
|
||||
self.callback(ss=subss)
|
||||
sr = self.simple_substep(x, ssampler)
|
||||
x = sr.x
|
||||
noise_strength = sr.noise_scale
|
||||
if noise_strength != 0 and subss.sigma_next != 0:
|
||||
x = sr.noise_x(ss=subss)
|
||||
substep += 1
|
||||
pbar.update(1)
|
||||
if substeps_remain == 1:
|
||||
break
|
||||
pbar.update(0)
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(
|
||||
eta=self.lookahead_eta, sigma=ss.sigma, sigma_next=ss.sigma_next
|
||||
)
|
||||
if sr.sigma_next == sigma_down:
|
||||
return x
|
||||
dt = (
|
||||
torch.sqrt(1.0 + (ss.sigma - sigma_down) ** 2) * 0.05
|
||||
+ (ss.sigma - sigma_down) * 0.95
|
||||
) * self.lookahead_dt_factor
|
||||
denoised = sr.denoised
|
||||
d = (orig_x - denoised) / ss.sigma
|
||||
x = orig_x + d * -dt
|
||||
if sigma_down == 0 or sigma_up == 0:
|
||||
return x
|
||||
noise_sampler = ss.noise.make_caching_noise_sampler(
|
||||
self.custom_noise,
|
||||
1,
|
||||
ss.sigma,
|
||||
ss.sigma_next,
|
||||
immiscible=fallback(self.immiscible, ss.noise.immiscible),
|
||||
)
|
||||
# FIXME: This sigma, sigma_next is probably wrong.
|
||||
x += ss.noise.scale_noise(
|
||||
noise_sampler(ss.sigma, ss.sigma_next, refs=ss.refs),
|
||||
sigma_up * self.lookahead_s_noise,
|
||||
)
|
||||
return x
|
||||
|
||||
|
||||
class PingpongMergeSubstepsSampler(MergeSubstepsSampler):
|
||||
name = "pingpong"
|
||||
|
||||
def __init__(self, ss, group, **kwargs):
|
||||
super().__init__(ss, group, **kwargs)
|
||||
pingpong = self.options.pop("pingpong", {}).copy()
|
||||
self.pingpong_s_noise = pingpong.pop("s_noise", 1.0)
|
||||
immiscible = pingpong.get("immiscible", False)
|
||||
self.immiscible = (
|
||||
ImmiscibleNoise(**immiscible) if immiscible is not False else False
|
||||
)
|
||||
|
||||
self.custom_noise = self.options.get("custom_noise")
|
||||
if isinstance(self.custom_noise, str):
|
||||
self.custom_noise = self.options.get(f"custom_noise_{self.custom_noise}")
|
||||
|
||||
def step(self, x):
|
||||
orig_x = x.clone()
|
||||
ss = self.ss
|
||||
subss = self.ss.clone_edit(idx=ss.idx, sigmas=ss.sigmas)
|
||||
substep = 0
|
||||
max_idx = len(ss.sigmas) - 1
|
||||
eff_substeps = min(max_idx - ss.idx, self.substeps)
|
||||
pbar = tqdm.tqdm(total=eff_substeps, initial=0, disable=ss.disable_status)
|
||||
for ssampler_ in self.samplers:
|
||||
substeps_remain = eff_substeps - substep
|
||||
if substeps_remain == 0:
|
||||
break
|
||||
with StepSamplerContext(ssampler_, subss) as ssampler:
|
||||
for subidx in range(min(substeps_remain, ssampler.substeps)):
|
||||
subss.update(ss.idx + substep, substep=substep)
|
||||
pbar.set_description(
|
||||
f"substep({ssampler.name}): {subss.sigma.item():.03} -> {subss.sigma_next.item():.03}"
|
||||
)
|
||||
subss.hist.push(self.call_model(x, ss=subss))
|
||||
subss.refs = FilterRefs.from_ss(subss, have_current=True)
|
||||
if substep == 0:
|
||||
self.callback(ss=subss)
|
||||
sr = self.simple_substep(x, ssampler)
|
||||
x = sr.x
|
||||
noise_strength = sr.noise_scale
|
||||
if noise_strength != 0 and subss.sigma_next != 0:
|
||||
x = sr.noise_x(ss=subss)
|
||||
substep += 1
|
||||
pbar.update(1)
|
||||
if substeps_remain == 1:
|
||||
break
|
||||
pbar.update(0)
|
||||
if sr.sigma_next == 0:
|
||||
return x
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
alpha = subss.sigma_next / sigma
|
||||
synth_denoised = (x - alpha * orig_x) / (1 - alpha)
|
||||
noise_sampler = ss.noise.make_caching_noise_sampler(
|
||||
self.custom_noise,
|
||||
1,
|
||||
sigma,
|
||||
sigma_next,
|
||||
immiscible=fallback(self.immiscible, ss.noise.immiscible),
|
||||
)
|
||||
noise_refs = ss.refs | FilterRefs({
|
||||
"orig_x": orig_x,
|
||||
"x": x,
|
||||
"denoised": synth_denoised,
|
||||
})
|
||||
noise = (
|
||||
noise_sampler(sigma, sigma_next, refs=noise_refs) * self.pingpong_s_noise
|
||||
)
|
||||
if ss.model.is_rectified_flow:
|
||||
return torch.lerp(synth_denoised, noise, sigma_next)
|
||||
return synth_denoised + noise * sigma_next
|
||||
|
||||
|
||||
class DynamicMergeSubstepsSampler(MergeSubstepsSampler):
|
||||
name = "dynamic"
|
||||
|
||||
def __init__(self, ss, group, **kwargs):
|
||||
super().__init__(ss, group, **kwargs)
|
||||
dynamic = self.options.get("dynamic")
|
||||
if dynamic is None:
|
||||
raise ValueError(
|
||||
"Dynamic group type requires specifying dynamic block in text parameters"
|
||||
)
|
||||
if isinstance(dynamic, str):
|
||||
dynamic = ({"expression": dynamic},)
|
||||
elif not isinstance(dynamic, (tuple, list)):
|
||||
raise ValueError(
|
||||
"Bad type for dynamic block: must be string or list of objects"
|
||||
)
|
||||
elif len(dynamic) == 0:
|
||||
raise ValueError("Dynamic block as a list cannot be empty")
|
||||
dynresult = []
|
||||
for idx, item in enumerate(dynamic):
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError(
|
||||
f"Bad item in dynamic block at index {idx}: must be a dict"
|
||||
)
|
||||
dyn_when = item.get("when")
|
||||
if isinstance(dyn_when, str):
|
||||
dyn_when = expr.Expression(dyn_when)
|
||||
elif dyn_when is not None:
|
||||
raise ValueError(
|
||||
f"Unexpected type for when key in dynamic block at index {idx}, must be string or null/unset"
|
||||
)
|
||||
dyn_params = item.get("expression")
|
||||
if not isinstance(dyn_params, str):
|
||||
raise ValueError(
|
||||
f"Missing or incorrectly typed expression key for dynamic block at index {idx}: must be a string"
|
||||
)
|
||||
dynresult.append((dyn_when, expr.Expression(dyn_params)))
|
||||
self.dynamic = tuple(dynresult)
|
||||
|
||||
def step(self, x):
|
||||
group_params = None
|
||||
handlers = FILTER_HANDLERS.clone(constants=self.ss.refs)
|
||||
for idx, (dyn_when, dyn_params) in enumerate(self.dynamic):
|
||||
if dyn_when is not None and not bool(dyn_when.eval(handlers)):
|
||||
continue
|
||||
group_params = dyn_params.eval(handlers)
|
||||
if group_params is not None:
|
||||
break
|
||||
if group_params is None:
|
||||
raise RuntimeError(
|
||||
"Dynamic group could not find matching group: all expressions failed to return a result"
|
||||
)
|
||||
if not isinstance(group_params, dict):
|
||||
raise TypeError(
|
||||
f"Dynamic group expression must evaluate to a dict, got type {type(group_params)}"
|
||||
)
|
||||
if bool(group_params.get("dynamic_inherit")):
|
||||
copy_keys = ("preview_mode",)
|
||||
opts = {k: getattr(self, k) for k in copy_keys}
|
||||
else:
|
||||
opts = {}
|
||||
opts |= {
|
||||
k: v
|
||||
for k, v in self.options.items()
|
||||
if k.startswith("custom_noise") or k.startswith("restart_custom_noise")
|
||||
}
|
||||
opts |= group_params
|
||||
# print("\n\nDYN GROUP OPTS", opts)
|
||||
merge_method = opts.pop("merge_method", "simple").strip()
|
||||
if merge_method == "default":
|
||||
merge_method = "simple"
|
||||
group_class = MERGE_SUBSTEPS_CLASSES.get(merge_method)
|
||||
if group_class is None:
|
||||
raise ValueError(f"Unknown merge method {merge_method} in dynamic group")
|
||||
group = StepSamplerChain(
|
||||
merge_method=merge_method, items=self.group.items, **opts
|
||||
)
|
||||
sampler = group_class(self.ss, group)
|
||||
return sampler.step(x)
|
||||
|
||||
|
||||
MERGE_SUBSTEPS_CLASSES = {
|
||||
"normal": NormalMergeSubstepsSampler,
|
||||
"default (simple)": SimpleSubstepsSampler,
|
||||
"supreme_avg": SupremeAvgMergeSubstepsSampler,
|
||||
"divide": DivideMergeSubstepsSampler,
|
||||
"average": AverageMergeSubstepsSampler,
|
||||
"sample": SampleMergeSubstepsSampler,
|
||||
"sample_uncached": SampleUncachedMergeSubstepsSampler,
|
||||
"overshoot": OvershootMergeSubstepsSampler,
|
||||
"simple": SimpleSubstepsSampler,
|
||||
"lookahead": LookaheadMergeSubstepsSampler,
|
||||
"pingpong": PingpongMergeSubstepsSampler,
|
||||
"dynamic": DynamicMergeSubstepsSampler,
|
||||
}
|
||||
|
||||
@@ -1,624 +0,0 @@
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
from comfy.k_diffusion.sampling import (
|
||||
get_ancestral_step,
|
||||
to_d,
|
||||
)
|
||||
|
||||
from .res_support import _de_second_order
|
||||
from .utils import find_first_unsorted
|
||||
|
||||
|
||||
class SingleStepSampler:
|
||||
name = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
noise_sampler=None,
|
||||
substeps=1,
|
||||
s_noise=1.0,
|
||||
eta=1.0,
|
||||
dyn_eta_start=None,
|
||||
dyn_eta_end=None,
|
||||
weight=1.0,
|
||||
**kwargs,
|
||||
):
|
||||
self.s_noise = s_noise
|
||||
self.eta = eta
|
||||
self.dyn_eta_start = dyn_eta_start
|
||||
self.dyn_eta_end = dyn_eta_end
|
||||
self.noise_sampler = noise_sampler
|
||||
self.weight = weight
|
||||
self.substeps = substeps
|
||||
self.kwargs = kwargs
|
||||
|
||||
def step(self, x, ss):
|
||||
raise NotImplementedError
|
||||
|
||||
# Euler - based on original ComfyUI implementation
|
||||
def euler_step(self, x, ss):
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(self.get_dyn_eta(ss))
|
||||
d = to_d(x, ss.sigma, ss.denoised)
|
||||
dt = sigma_down - ss.sigma
|
||||
return x + d * dt, sigma_up
|
||||
|
||||
def __str__(self):
|
||||
return f"<SS({self.name}): s_noise={self.s_noise}, eta={self.eta}>"
|
||||
|
||||
def get_dyn_value(self, ss, start, end):
|
||||
if None in (start, end):
|
||||
return 1.0
|
||||
if start == end:
|
||||
return start
|
||||
main_idx = getattr(ss, "main_idx", ss.idx)
|
||||
main_sigmas = getattr(ss, "main_sigmas", ss.sigmas)
|
||||
step_pct = main_idx / (len(main_sigmas) - 1)
|
||||
dd_diff = end - start
|
||||
return start + dd_diff * step_pct
|
||||
|
||||
def get_dyn_eta(self, ss):
|
||||
return self.eta * self.get_dyn_value(ss, self.dyn_eta_start, self.dyn_eta_end)
|
||||
|
||||
|
||||
class ReversibleSingleStepSampler(SingleStepSampler):
|
||||
def __init__(self, *, reta=1.0, dyn_reta_start=None, dyn_reta_end=None, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.reta = reta
|
||||
self.dyn_reta_start = dyn_reta_start
|
||||
self.dyn_reta_end = dyn_reta_end
|
||||
|
||||
def get_dyn_reta(self, ss):
|
||||
return self.reta * self.get_dyn_value(
|
||||
ss, self.dyn_reta_start, self.dyn_reta_end
|
||||
)
|
||||
|
||||
|
||||
class EulerStep(SingleStepSampler):
|
||||
name = "euler"
|
||||
step = SingleStepSampler.euler_step
|
||||
|
||||
|
||||
class DPMPPStepBase(SingleStepSampler):
|
||||
@staticmethod
|
||||
def sigma_fn(t):
|
||||
return t.neg().exp()
|
||||
|
||||
@staticmethod
|
||||
def t_fn(t):
|
||||
return t.log().neg()
|
||||
|
||||
|
||||
class DPMPP2MStep(DPMPPStepBase):
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
t, t_next = self.t_fn(ss.sigma), self.t_fn(ss.sigma_next)
|
||||
h = t_next - t
|
||||
st, st_next = self.sigma_fn(t), self.sigma_fn(t_next)
|
||||
if len(ss.dhist) == 0 or ss.sigma_prev is None:
|
||||
return (st_next / st) * x - (-h).expm1() * ss.denoised, 0.0
|
||||
h_last = t - self.t_fn(ss.sigma_prev)
|
||||
r = h_last / h
|
||||
denoised, old_denoised = ss.denoised, ss.dhist[-1]
|
||||
denoised_d = (1 + 1 / (2 * r)) * denoised - (1 / (2 * r)) * old_denoised
|
||||
return (st_next / st) * x - (-h).expm1() * denoised_d, 0.0
|
||||
|
||||
|
||||
class DPMPP2MSDEStep(SingleStepSampler):
|
||||
name = "dpmpp_2m_sde"
|
||||
|
||||
def __init__(self, *, solver_type="midpoint", **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.solver_type = solver_type
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
denoised = ss.denoised
|
||||
if ss.sigma_next == 0:
|
||||
return denoised, None
|
||||
# DPM-Solver++(2M) SDE
|
||||
t, s = -ss.sigma.log(), -ss.sigma_next.log()
|
||||
h = s - t
|
||||
eta_h = self.get_dyn_eta(ss) * h
|
||||
|
||||
x = (
|
||||
ss.sigma_next / ss.sigma * (-eta_h).exp() * x
|
||||
+ (-h - eta_h).expm1().neg() * denoised
|
||||
)
|
||||
noise_strength = ss.sigma_next * (-2 * eta_h).expm1().neg().sqrt()
|
||||
if len(ss.dhist) == 0 or ss.sigma_prev is None:
|
||||
return x, noise_strength
|
||||
h_last = (-ss.sigma.log()) - (-ss.sigma_prev.log())
|
||||
r = h_last / h
|
||||
old_denoised = ss.dhist[-1]
|
||||
if self.solver_type == "heun":
|
||||
x = x + (
|
||||
((-h - eta_h).expm1().neg() / (-h - eta_h) + 1)
|
||||
* (1 / r)
|
||||
* (denoised - old_denoised)
|
||||
)
|
||||
elif self.solver_type == "midpoint":
|
||||
x = x + 0.5 * (-h - eta_h).expm1().neg() * (1 / r) * (
|
||||
denoised - old_denoised
|
||||
)
|
||||
return x, noise_strength
|
||||
|
||||
|
||||
class DPMPP3MSDEStep(SingleStepSampler):
|
||||
name = "dpmpp_3m_sde"
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
denoised = ss.denoised
|
||||
if ss.sigma_next == 0:
|
||||
return denoised, 0
|
||||
t, s = -ss.sigma.log(), -ss.sigma_next.log()
|
||||
h = s - t
|
||||
eta = self.get_dyn_eta(ss)
|
||||
h_eta = h * (eta + 1)
|
||||
|
||||
x = torch.exp(-h_eta) * x + (-h_eta).expm1().neg() * denoised
|
||||
noise_strength = ss.sigma_next * (-2 * h * eta).expm1().neg().sqrt()
|
||||
if len(ss.dhist) == 0 or ss.sigma_prev is None:
|
||||
return x, noise_strength
|
||||
h_1 = (-ss.sigma.log()) - (-ss.sigma_prev.log())
|
||||
denoised_1 = ss.dhist[-1]
|
||||
if len(ss.dhist) == 1:
|
||||
r = h_1 / h
|
||||
d = (denoised - denoised_1) / r
|
||||
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
||||
x = x + phi_2 * d
|
||||
else:
|
||||
h_2 = (-ss.sigma_prev.log()) - (-ss.sigmas[ss.idx - 2].log())
|
||||
denoised_2 = ss.dhist[-2]
|
||||
r0 = h_1 / h
|
||||
r1 = h_2 / h
|
||||
d1_0 = (denoised - denoised_1) / r0
|
||||
d1_1 = (denoised_1 - denoised_2) / r1
|
||||
d1 = d1_0 + (d1_0 - d1_1) * r0 / (r0 + r1)
|
||||
d2 = (d1_0 - d1_1) / (r0 + r1)
|
||||
phi_2 = h_eta.neg().expm1() / h_eta + 1
|
||||
phi_3 = phi_2 / h_eta - 0.5
|
||||
x = x + phi_2 * d1 - phi_3 * d2
|
||||
return x, noise_strength
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class ReversibleHeunStep(ReversibleSingleStepSampler):
|
||||
name = "reversible_heun"
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(self.get_dyn_eta(ss))
|
||||
sigma_down_reversible, sigma_up_reversible = ss.get_ancestral_step(
|
||||
self.get_dyn_reta(ss)
|
||||
)
|
||||
dt = sigma_down - ss.sigma
|
||||
dt_reversible = sigma_down_reversible - ss.sigma
|
||||
|
||||
# Calculate the derivative using the model
|
||||
d = to_d(x, ss.sigma, ss.denoised)
|
||||
|
||||
# Predict the sample at the next sigma using Euler step
|
||||
x_pred = x + d * dt
|
||||
|
||||
# Denoised sample at the next sigma
|
||||
denoised_next = ss.model(x_pred, sigma_down, model_call_idx=1)
|
||||
|
||||
# Calculate the derivative at the next sigma
|
||||
d_next = to_d(x_pred, sigma_down, denoised_next)
|
||||
|
||||
# Update the sample using the Reversible Heun formula
|
||||
x = x + dt * (d + d_next) / 2 - dt_reversible**2 * (d_next - d) / 4
|
||||
return x, sigma_up
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class ReversibleHeun1SStep(ReversibleSingleStepSampler):
|
||||
name = "reversible_heun_1s"
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
# Reversible Heun-inspired update (first-order)
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(self.get_dyn_eta(ss))
|
||||
sigma_down_reversible, sigma_up_reversible = ss.get_ancestral_step(
|
||||
self.get_dyn_reta(ss)
|
||||
)
|
||||
sigma_i, sigma_i_plus_1 = ss.sigma, sigma_down
|
||||
dt = sigma_i_plus_1 - sigma_i
|
||||
dt_reversible = sigma_down_reversible - sigma_i
|
||||
|
||||
eff_x = ss.xhist[-1] if len(ss.xhist) else x
|
||||
|
||||
# Calculate the derivative using the model
|
||||
d_i_old = to_d(
|
||||
eff_x,
|
||||
sigma_i,
|
||||
ss.dhist[-1]
|
||||
if len(ss.dhist)
|
||||
else ss.model(eff_x, sigma_i, model_call_idx=1),
|
||||
)
|
||||
|
||||
# Predict the sample at the next sigma using Euler step
|
||||
x_pred = eff_x + d_i_old * dt
|
||||
|
||||
# Calculate the derivative at the next sigma
|
||||
d_i_plus_1 = to_d(x_pred, sigma_i_plus_1, ss.denoised)
|
||||
|
||||
# Update the sample using the Reversible Heun formula
|
||||
x = (
|
||||
x
|
||||
+ dt * (d_i_old + d_i_plus_1) / 2
|
||||
- dt_reversible**2 * (d_i_plus_1 - d_i_old) / 4
|
||||
)
|
||||
return x, sigma_up
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class RESStep(SingleStepSampler):
|
||||
name = "res"
|
||||
|
||||
def __init__(self, *, res_simple_phi=False, res_c2=0.5, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.simple_phi = res_simple_phi
|
||||
self.c2 = res_c2
|
||||
pass
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
eta = self.get_dyn_eta(ss)
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(eta)
|
||||
denoised = ss.denoised
|
||||
lam_next = sigma_down.log().neg() if eta != 0 else ss.sigma_next.log().neg()
|
||||
lam = ss.sigma.log().neg()
|
||||
|
||||
h = lam_next - lam
|
||||
a2_1, b1, b2 = _de_second_order(
|
||||
h=h, c2=self.c2, simple_phi_calc=self.simple_phi
|
||||
)
|
||||
|
||||
c2_h = 0.5 * h
|
||||
|
||||
x_2 = math.exp(-c2_h) * x + a2_1 * h * denoised
|
||||
lam_2 = lam + c2_h
|
||||
sigma_2 = lam_2.neg().exp()
|
||||
|
||||
denoised2 = ss.model(x_2, sigma_2, model_call_idx=1)
|
||||
|
||||
x = math.exp(-h) * x + h * (b1 * denoised + b2 * denoised2)
|
||||
return x, sigma_up
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class TrapezoidalStep(SingleStepSampler):
|
||||
name = "trapezoidal"
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(self.get_dyn_eta(ss))
|
||||
dt = ss.sigma_next - ss.sigma
|
||||
denoised = ss.denoised
|
||||
|
||||
# Calculate the derivative using the model
|
||||
d_i = to_d(x, ss.sigma, denoised)
|
||||
|
||||
# Predict the sample at the next sigma using Euler step
|
||||
x_pred = x + d_i * dt
|
||||
|
||||
# Denoised sample at the next sigma
|
||||
denoised_next = ss.model(x_pred, ss.sigma_next, model_call_idx=1)
|
||||
|
||||
# Calculate the derivative at the next sigma
|
||||
d_next = to_d(x_pred, ss.sigma_next, denoised_next)
|
||||
|
||||
dt_2 = sigma_down - ss.sigma
|
||||
# Update the sample using the Trapezoidal rule
|
||||
x = x + dt_2 * (d_i + d_next) / 2
|
||||
return x, sigma_up
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class BogackiStep(ReversibleSingleStepSampler):
|
||||
name = "bogacki"
|
||||
reversible = False
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(self.get_dyn_eta(ss))
|
||||
sigma_down_reversible, sigma_up_reversible = ss.get_ancestral_step(
|
||||
self.get_dyn_reta(ss)
|
||||
)
|
||||
sigma, sigma_next = ss.sigma, sigma_down
|
||||
dt = sigma_next - sigma
|
||||
dt_reversible = sigma_down_reversible - sigma
|
||||
denoised = ss.denoised
|
||||
|
||||
# Calculate the derivative using the model
|
||||
d = to_d(x, sigma, denoised)
|
||||
|
||||
# Bogacki-Shampine steps
|
||||
k1 = d * dt
|
||||
k2 = (
|
||||
to_d(
|
||||
x + k1 / 2,
|
||||
sigma + dt / 2,
|
||||
ss.model(x + k1 / 2, sigma + dt / 2, model_call_idx=1),
|
||||
)
|
||||
* dt
|
||||
)
|
||||
k3 = (
|
||||
to_d(
|
||||
x + 3 * k1 / 4 + k2 / 4,
|
||||
sigma + 3 * dt / 4,
|
||||
ss.model(x + 3 * k1 / 4 + k2 / 4, sigma + 3 * dt / 4, model_call_idx=2),
|
||||
)
|
||||
* dt
|
||||
)
|
||||
|
||||
# Reversible correction term (inspired by Reversible Heun)
|
||||
correction = dt_reversible**2 * (k3 - k2) / 6 if self.reversible else 0.0
|
||||
|
||||
# Update the sample
|
||||
x = x + 2 * k1 / 9 + k2 / 3 + 4 * k3 / 9 - correction
|
||||
return x, sigma_up
|
||||
|
||||
|
||||
class ReversibleBogackiStep(BogackiStep):
|
||||
name = "reversible_bogacki"
|
||||
reversible = True
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class RK4Step(SingleStepSampler):
|
||||
name = "rk4"
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(self.get_dyn_eta(ss))
|
||||
sigma = ss.sigma
|
||||
# Calculate the derivative using the model
|
||||
d = to_d(x, sigma, ss.denoised)
|
||||
dt = sigma_down - sigma
|
||||
|
||||
# Runge-Kutta steps
|
||||
k1 = d * dt
|
||||
k2 = (
|
||||
to_d(
|
||||
x + k1 / 2,
|
||||
sigma + dt / 2,
|
||||
ss.model(x + k1 / 2, sigma + dt / 2, model_call_idx=1),
|
||||
)
|
||||
* dt
|
||||
)
|
||||
k3 = (
|
||||
to_d(
|
||||
x + k2 / 2,
|
||||
sigma + dt / 2,
|
||||
ss.model(x + k2 / 2, sigma + dt / 2, model_call_idx=2),
|
||||
)
|
||||
* dt
|
||||
)
|
||||
k4 = (
|
||||
to_d(
|
||||
x + k3,
|
||||
sigma + dt,
|
||||
ss.model(x + k3, sigma + dt, model_call_idx=3),
|
||||
)
|
||||
* dt
|
||||
)
|
||||
|
||||
# Update the sample
|
||||
x = x + (k1 + 2 * k2 + 2 * k3 + k4) / 6
|
||||
return x, sigma_up
|
||||
|
||||
|
||||
# Based on original implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
class EulerDancingStep(SingleStepSampler):
|
||||
name = "euler_dancing"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
deta=1.0,
|
||||
ds_noise=1.0,
|
||||
leap=2,
|
||||
dyn_deta_start=None,
|
||||
dyn_deta_end=None,
|
||||
dyn_deta_mode="lerp",
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(**kwargs)
|
||||
self.deta = deta
|
||||
self.ds_noise = ds_noise
|
||||
self.leap = leap
|
||||
self.dyn_deta_start = dyn_deta_start
|
||||
self.dyn_deta_end = dyn_deta_end
|
||||
if dyn_deta_mode not in ("lerp", "lerp_alt", "deta"):
|
||||
raise ValueError("Bad dyn_deta_mode")
|
||||
self.dyn_deta_mode = dyn_deta_mode
|
||||
|
||||
def step(self, x, ss):
|
||||
eta = self.get_dyn_eta(ss)
|
||||
leap_sigmas = ss.sigmas[ss.idx :]
|
||||
leap_sigmas = leap_sigmas[: find_first_unsorted(leap_sigmas)]
|
||||
zero_idx = (leap_sigmas <= 0).nonzero().flatten()[:1]
|
||||
max_leap = (zero_idx.item() if len(zero_idx) else len(leap_sigmas)) - 1
|
||||
is_danceable = max_leap > 1 and ss.sigma_next != 0
|
||||
curr_leap = max(1, min(self.leap, max_leap))
|
||||
sigma_leap = leap_sigmas[curr_leap] if is_danceable else ss.sigma_next
|
||||
print("DANCE", max_leap, curr_leap, sigma_leap, "--", leap_sigmas)
|
||||
del leap_sigmas
|
||||
sigma_down, sigma_up = get_ancestral_step(ss.sigma, sigma_leap, eta)
|
||||
d = to_d(x, ss.sigma, ss.denoised)
|
||||
# Euler method
|
||||
dt = sigma_down - ss.sigma
|
||||
x = x + d * dt
|
||||
if curr_leap == 1:
|
||||
return x, sigma_up
|
||||
dance_scale = self.get_dyn_value(ss, self.dyn_deta_start, self.dyn_deta_end)
|
||||
if not is_danceable or abs(dance_scale) < 1e-04:
|
||||
return x, sigma_up
|
||||
sigma_down_normal, sigma_up_normal = get_ancestral_step(
|
||||
ss.sigma, ss.sigma_next, eta
|
||||
)
|
||||
if self.dyn_deta_mode == "lerp":
|
||||
dt_normal = sigma_down_normal - ss.sigma
|
||||
x_normal = x + d * dt_normal
|
||||
else:
|
||||
x_normal = x
|
||||
x = x + self.noise_sampler(ss.sigma, sigma_leap) * self.s_noise * sigma_up
|
||||
sigma_down2, sigma_up2 = get_ancestral_step(
|
||||
sigma_leap,
|
||||
ss.sigma_next,
|
||||
eta=self.deta * (1.0 if self.dyn_deta_mode != "deta" else dance_scale),
|
||||
)
|
||||
d_2 = to_d(x, sigma_leap, ss.denoised)
|
||||
dt_2 = sigma_down2 - sigma_leap
|
||||
result = x + d_2 * dt_2
|
||||
noise_diff = sigma_up2 - sigma_up * dance_scale
|
||||
noise_scale = sigma_up2 + noise_diff * (0.025 * curr_leap)
|
||||
if self.dyn_deta_mode == "deta" or dance_scale == 1.0:
|
||||
return result, noise_scale
|
||||
result = torch.lerp(x_normal, result, dance_scale)
|
||||
# FIXME: Broken for noise samplers that care about s/sn
|
||||
return result, noise_scale
|
||||
|
||||
|
||||
class DPMPP2SStep(DPMPPStepBase):
|
||||
name = "dpmpp_2s"
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
t_fn, sigma_fn = self.t_fn, self.sigma_fn
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(self.get_dyn_eta(ss))
|
||||
# DPM-Solver++(2S)
|
||||
t, t_next = t_fn(ss.sigma), t_fn(sigma_down)
|
||||
r = 1 / 2
|
||||
h = t_next - t
|
||||
s = t + r * h
|
||||
x_2 = (sigma_fn(s) / sigma_fn(t)) * x - (-h * r).expm1() * ss.denoised
|
||||
denoised_2 = ss.model(x_2, sigma_fn(s), model_call_idx=0)
|
||||
x = (sigma_fn(t_next) / sigma_fn(t)) * x - (-h).expm1() * denoised_2
|
||||
return x, sigma_up
|
||||
|
||||
|
||||
class DPMPPSDEStep(DPMPPStepBase):
|
||||
name = "dpmpp_sde"
|
||||
|
||||
def __init__(self, *args, r=1 / 2, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.r = r
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return self.euler_step(x, ss)
|
||||
t_fn, sigma_fn = self.t_fn, self.sigma_fn
|
||||
r, eta, s_noise = self.r, self.get_dyn_eta(ss), self.s_noise
|
||||
noise_sampler = self.noise_sampler
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(eta)
|
||||
# DPM-Solver++
|
||||
t, t_next = t_fn(ss.sigma), t_fn(ss.sigma_next)
|
||||
h = t_next - t
|
||||
s = t + h * r
|
||||
fac = 1 / (2 * r)
|
||||
|
||||
# Step 1
|
||||
sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(s), eta)
|
||||
s_ = t_fn(sd)
|
||||
x_2 = (sigma_fn(s_) / sigma_fn(t)) * x - (t - s_).expm1() * ss.denoised
|
||||
x_2 = x_2 + noise_sampler(sigma_fn(t), sigma_fn(s)) * s_noise * su
|
||||
denoised_2 = ss.model(x_2, sigma_fn(s), model_call_idx=1)
|
||||
|
||||
# Step 2
|
||||
sd, su = get_ancestral_step(sigma_fn(t), sigma_fn(t_next), eta)
|
||||
t_next_ = t_fn(sd)
|
||||
denoised_d = (1 - fac) * ss.denoised + fac * denoised_2
|
||||
x = (sigma_fn(t_next_) / sigma_fn(t)) * x - (t - t_next_).expm1() * denoised_d
|
||||
return x, su
|
||||
|
||||
|
||||
# Based on implementation from https://github.com/Clybius/ComfyUI-Extra-Samplers
|
||||
# Which was originally written by Katherine Crowson
|
||||
class TTMJVPStep(SingleStepSampler):
|
||||
name = "ttm_jvp"
|
||||
|
||||
def __init__(self, *args, alternate_phi_2_calc=True, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.alternate_phi_2_calc = alternate_phi_2_calc
|
||||
|
||||
def step(self, x, ss):
|
||||
if ss.sigma_next == 0:
|
||||
return ss.denoised, ss.sigma.new_zeros(1)
|
||||
eta = self.get_dyn_eta(ss)
|
||||
sigma_down, sigma_up = ss.get_ancestral_step(eta)
|
||||
sigma, sigma_next = ss.sigma, ss.sigma_next
|
||||
# 2nd order truncated Taylor method
|
||||
t, s = -sigma.log(), -sigma_next.log()
|
||||
h = s - t
|
||||
h_eta = h * (eta + 1)
|
||||
|
||||
eps = to_d(x, sigma, ss.denoised)
|
||||
denoised, denoised_prime = ss.model(
|
||||
x, sigma, tangents=(eps * -sigma, -sigma), model_call_idx=1
|
||||
)
|
||||
|
||||
phi_1 = -torch.expm1(-h_eta)
|
||||
if self.alternate_phi_2_calc:
|
||||
phi_2 = torch.expm1(-h) + h # seems to work better with eta > 0
|
||||
else:
|
||||
phi_2 = torch.expm1(-h_eta) + h_eta
|
||||
x = torch.exp(-h_eta) * x + phi_1 * ss.denoised + phi_2 * denoised_prime
|
||||
|
||||
if not eta:
|
||||
return x, ss.sigma.new_zeros(1)
|
||||
|
||||
phi_1_noise = torch.sqrt(-torch.expm1(-2 * h * eta))
|
||||
return x, sigma_next * phi_1_noise
|
||||
|
||||
|
||||
STEP_SAMPLERS = {
|
||||
"euler": EulerStep,
|
||||
"dpmpp_sde": DPMPPSDEStep,
|
||||
"dpmpp_2m": DPMPP2MStep,
|
||||
"dpmpp_2m_sde": DPMPP2MSDEStep,
|
||||
"dpmpp_3m_sde": DPMPP3MSDEStep,
|
||||
"dpmpp_2s": DPMPP2SStep,
|
||||
"reversible_heun": ReversibleHeunStep,
|
||||
"reversible_heun_1s": ReversibleHeun1SStep,
|
||||
"res": RESStep,
|
||||
"trapezoidal": TrapezoidalStep,
|
||||
"bogacki": BogackiStep,
|
||||
"reversible_bogacki": ReversibleBogackiStep,
|
||||
"rk4": RK4Step,
|
||||
"euler_dancing": EulerDancingStep,
|
||||
"ttm_jvp": TTMJVPStep,
|
||||
}
|
||||
|
||||
__all__ = (
|
||||
"STEP_SAMPLERS",
|
||||
"EulerStep",
|
||||
"DPMPP2MStep",
|
||||
"DPMPP2MSDEStep",
|
||||
"DPMPP3MSDEStep",
|
||||
"DPMPP2SStep",
|
||||
"ReversibleHeunStep",
|
||||
"ReversibleHeun1SStep",
|
||||
"RESStep",
|
||||
"TrapezoidalStep",
|
||||
"BogackiStep",
|
||||
"ReversibleBogackiStep",
|
||||
"EulerDancingStep",
|
||||
"TTMJVPStep",
|
||||
)
|
||||
+215
-122
@@ -2,188 +2,281 @@ import torch
|
||||
|
||||
from comfy.k_diffusion.sampling import get_ancestral_step
|
||||
|
||||
from .filtering import FilterRefs
|
||||
from .model import History
|
||||
from .utils import fallback
|
||||
|
||||
class StepSamplerChain:
|
||||
|
||||
class Items:
|
||||
def __init__(self, items=None):
|
||||
self.items = [] if items is None else items
|
||||
|
||||
def clone(self):
|
||||
return self.__class__(items=self.items.copy())
|
||||
|
||||
def append(self, item):
|
||||
self.items.append(item)
|
||||
return item
|
||||
|
||||
class History:
|
||||
def __init__(self, x, size):
|
||||
self.history = torch.zeros(size, *x.shape, device=x.device, dtype=x.dtype)
|
||||
self.size = size
|
||||
self.pos = 0
|
||||
self.last = None
|
||||
def __getitem__(self, key):
|
||||
return self.items[key]
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
self.items[key] = value
|
||||
|
||||
def __len__(self):
|
||||
return min(self.pos, self.size)
|
||||
return len(self.items)
|
||||
|
||||
def __getitem__(self, k):
|
||||
idx = (self.pos + k if k < 0 else self.pos + -self.size + k) % self.size
|
||||
# print(f"\nFETCH {k}: pos={self.pos}, size={self.size}, at={idx}")
|
||||
return self.history[idx]
|
||||
|
||||
def push(self, val):
|
||||
# print(f"\nPUSH {self.pos % self.size}: pos={self.pos}, size={self.size}")
|
||||
self.last = self.pos % self.size
|
||||
self.history[self.last] = val
|
||||
self.pos += 1
|
||||
|
||||
def reset(self):
|
||||
self.pos = 0
|
||||
self.last = None
|
||||
def __iter__(self):
|
||||
return self.items.__iter__()
|
||||
|
||||
|
||||
class ModelCallCache:
|
||||
class CommonOptionsItems(Items):
|
||||
def __init__(self, *, s_noise=1.0, eta=1.0, items=None, **kwargs):
|
||||
super().__init__(items=items)
|
||||
self.options = kwargs
|
||||
self.s_noise = s_noise
|
||||
self.eta = eta
|
||||
|
||||
def clone(self):
|
||||
obj = super().clone()
|
||||
obj.options = self.options.copy()
|
||||
obj.s_noise = self.s_noise
|
||||
obj.eta = self.eta
|
||||
return obj
|
||||
|
||||
|
||||
class StepSamplerChain(CommonOptionsItems):
|
||||
def __init__(
|
||||
self, model, x, s_in, extra_args, *, size=0, max_use=1000000, threshold=1
|
||||
self,
|
||||
*,
|
||||
merge_method="divide",
|
||||
time_mode="step",
|
||||
time_start=0,
|
||||
time_end=999,
|
||||
**kwargs,
|
||||
):
|
||||
self.size = size
|
||||
self.model = model
|
||||
self.threshold = threshold
|
||||
self.s_in = s_in
|
||||
self.extra_args = extra_args
|
||||
self.max_use = max_use
|
||||
if self.size < 1:
|
||||
return
|
||||
self.mcc = torch.zeros(size, *x.shape, device=x.device, dtype=x.dtype)
|
||||
self.jmcc = torch.zeros_like(self.mcc)
|
||||
self.reset_cache()
|
||||
super().__init__(**kwargs)
|
||||
self.merge_method = merge_method
|
||||
if time_mode not in ("step", "step_pct", "sigma"):
|
||||
raise ValueError("Bad time mode")
|
||||
self.time_mode = time_mode
|
||||
self.time_start, self.time_end = time_start, time_end
|
||||
|
||||
def reset_cache(self):
|
||||
size = self.size
|
||||
self.slot = [None] * size
|
||||
self.jslot = [None] * size
|
||||
self.slot_use = [self.max_use] * size
|
||||
def clone(self):
|
||||
obj = super().clone()
|
||||
obj.merge_method = self.merge_method
|
||||
obj.time_mode = self.time_mode
|
||||
obj.time_start, obj.time_end = self.time_start, self.time_end
|
||||
obj.options = self.options.copy()
|
||||
return obj
|
||||
|
||||
def get(self, idx, *, jvp=False):
|
||||
idx -= self.threshold
|
||||
if (
|
||||
idx >= self.size
|
||||
or idx < 0
|
||||
or self.slot[idx] is None
|
||||
or self.slot_use[idx] < 1
|
||||
):
|
||||
return None
|
||||
if jvp and self.jslot[idx] is None:
|
||||
return None
|
||||
self.slot_use[idx] -= 1
|
||||
return self.slot[idx] if not jvp else (self.slot[idx], self.jslot[idx])
|
||||
|
||||
def set(self, idx, denoised, jdenoised=None):
|
||||
idx -= self.threshold
|
||||
if idx < 0 or idx >= self.size:
|
||||
return
|
||||
self.slot_use[idx] = self.max_use
|
||||
self.slot[idx] = denoised
|
||||
self.jslot[idx] = jdenoised
|
||||
class ParamGroup(Items):
|
||||
pass
|
||||
|
||||
def call_model(self, x, sigma, **kwargs):
|
||||
return self.model(x, sigma * self.s_in, **self.extra_args, **kwargs)
|
||||
|
||||
def __call__(self, x, sigma, *, model_call_idx=0, tangents=None, **kwargs):
|
||||
result = self.get(model_call_idx, jvp=tangents is not None)
|
||||
# print(
|
||||
# f"MODEL: idx={model_call_idx}, size={self.size}, threshold={self.threshold}, cached={result is not None}"
|
||||
# )
|
||||
if result is not None:
|
||||
return result
|
||||
if tangents is None:
|
||||
denoised = self.call_model(x, sigma, **kwargs)
|
||||
self.set(model_call_idx, denoised)
|
||||
return denoised
|
||||
denoised, denoised_prime = torch.func.jvp(self.call_model, (x, sigma), tangents)
|
||||
self.set(model_call_idx, denoised, jdenoised=denoised_prime)
|
||||
return denoised, denoised_prime
|
||||
class StepSamplerGroups(CommonOptionsItems):
|
||||
pass
|
||||
|
||||
|
||||
class SamplerState:
|
||||
CLONE_KEYS = (
|
||||
"cfg_scale_override",
|
||||
"model",
|
||||
"hist",
|
||||
"extra_args",
|
||||
"disable_status",
|
||||
"eta",
|
||||
"reta",
|
||||
"s_noise",
|
||||
"sigmas",
|
||||
"callback_",
|
||||
"noise_sampler",
|
||||
"noise",
|
||||
"idx",
|
||||
"total_steps",
|
||||
"step",
|
||||
"substep",
|
||||
"sigma",
|
||||
"sigma_next",
|
||||
"sigma_prev",
|
||||
"sigma_down",
|
||||
"sigma_up",
|
||||
"refs",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
model,
|
||||
sigmas,
|
||||
idx,
|
||||
dhist,
|
||||
xhist,
|
||||
extra_args,
|
||||
*,
|
||||
step=0,
|
||||
substep=0,
|
||||
noise_sampler,
|
||||
callback=None,
|
||||
denoised=None,
|
||||
noise=None,
|
||||
eta=1.0,
|
||||
reta=1.0,
|
||||
s_noise=1.0,
|
||||
disable_status=False,
|
||||
history_size=4,
|
||||
cfg_scale_override=None,
|
||||
):
|
||||
self.model = model
|
||||
self.dhist = dhist
|
||||
self.xhist = xhist
|
||||
self.hist = History(max(1, history_size))
|
||||
self.extra_args = extra_args
|
||||
self.eta = eta
|
||||
self.reta = reta
|
||||
self.s_noise = s_noise
|
||||
self.sigmas = sigmas
|
||||
self.denoised = denoised
|
||||
self.callback_ = callback
|
||||
self.noise_sampler = noise_sampler
|
||||
self.update(idx)
|
||||
self.noise = noise
|
||||
self.disable_status = disable_status
|
||||
self.step = 0
|
||||
self.substep = 0
|
||||
self.total_steps = len(sigmas) - 1
|
||||
self.cfg_scale_override = cfg_scale_override
|
||||
self.update(idx) # Sets idx, sigma_prev, sigma, sigma_down, refs
|
||||
|
||||
def update(self, idx=None):
|
||||
@property
|
||||
def hcur(self):
|
||||
return self.hist[-1]
|
||||
|
||||
@property
|
||||
def hprev(self):
|
||||
return self.hist[-2]
|
||||
|
||||
@property
|
||||
def denoised(self):
|
||||
return self.hcur.denoised
|
||||
|
||||
@property
|
||||
def denoised_uncond(self):
|
||||
return self.hcur.denoised_uncond
|
||||
|
||||
@property
|
||||
def denoised_cond(self):
|
||||
return self.hcur.denoised_cond
|
||||
|
||||
@property
|
||||
def dt(self):
|
||||
return self.sigma_next - self.sigma
|
||||
|
||||
@property
|
||||
def d(self):
|
||||
return self.hcur.d
|
||||
|
||||
def update(self, idx=None, step=None, substep=None):
|
||||
idx = self.idx if idx is None else idx
|
||||
self.idx = idx
|
||||
self.sigma_prev = None if idx < 1 else self.sigmas[idx - 1]
|
||||
self.sigma, self.sigma_next = self.sigmas[idx], self.sigmas[idx + 1]
|
||||
# if self.sigma_prev is not None and self.sigma < self.sigma_prev:
|
||||
# self.dhist.reset()
|
||||
# self.xhist.reset()
|
||||
self.sigma_down, self.sigma_up = get_ancestral_step(
|
||||
self.sigma, self.sigma_next, eta=self.eta
|
||||
)
|
||||
self.sigma_down_reversible, self.sigma_up_reversible = get_ancestral_step(
|
||||
self.sigma, self.sigma_next, eta=self.reta
|
||||
)
|
||||
if step is not None:
|
||||
self.step = step
|
||||
if substep is not None:
|
||||
self.substep = substep
|
||||
self.refs = FilterRefs.from_ss(self)
|
||||
|
||||
def get_ancestral_step(self, eta=1.0):
|
||||
return get_ancestral_step(self.sigma, self.sigma_next, eta=eta)
|
||||
def get_ancestral_step(
|
||||
self, eta=1.0, sigma=None, sigma_next=None, retry_increment=0
|
||||
):
|
||||
if self.model.is_rectified_flow:
|
||||
return self.get_ancestral_step_rf(
|
||||
eta=eta,
|
||||
sigma=sigma,
|
||||
sigma_next=sigma_next,
|
||||
retry_increment=retry_increment,
|
||||
)
|
||||
sigma = fallback(sigma, self.sigma)
|
||||
sigma_next = fallback(sigma_next, self.sigma_next)
|
||||
if eta <= 0 or sigma_next <= 0:
|
||||
return sigma_next, sigma_next.new_zeros(1)
|
||||
while eta > 0:
|
||||
sd, su = (
|
||||
v if isinstance(v, torch.Tensor) else sigma.new_full((1,), v)
|
||||
for v in get_ancestral_step(
|
||||
sigma, sigma_next, eta=eta if sigma_next != 0 else 0
|
||||
)
|
||||
)
|
||||
if sd > 0 and su > 0:
|
||||
return sd, su
|
||||
if retry_increment <= 0:
|
||||
break
|
||||
# print(f"\nETA {eta} failed, retrying with {eta - retry_increment}")
|
||||
eta -= retry_increment
|
||||
return sigma_next, sigma_next.new_zeros(1)
|
||||
|
||||
# Referenced from Comfy dpmpp_2s_ancestral_RF
|
||||
def get_ancestral_step_rf(
|
||||
self, eta=1.0, sigma=None, sigma_next=None, retry_increment=0
|
||||
):
|
||||
sigma = fallback(sigma, self.sigma)
|
||||
sigma_next = fallback(sigma_next, self.sigma_next)
|
||||
if eta <= 0 or sigma_next <= 0:
|
||||
return sigma_next, sigma_next.new_zeros(1)
|
||||
while eta > 0:
|
||||
sigma_down = sigma_next * (1 + (sigma_next / sigma - 1) * eta)
|
||||
alpha_ip1, alpha_down = 1 - sigma_next, 1 - sigma_down
|
||||
sigma_up = (
|
||||
sigma_next**2 - sigma_down**2 * alpha_ip1**2 / alpha_down**2
|
||||
) ** 0.5
|
||||
if sigma_down > 0 and sigma_up > 0:
|
||||
return sigma_down, sigma_up
|
||||
if retry_increment <= 0:
|
||||
break
|
||||
eta -= retry_increment
|
||||
return sigma_next, sigma_next.new_zeros(1)
|
||||
# print(f"\nRF ancestral: down={sigma_down}, up={sigma_up}")
|
||||
|
||||
def clone_edit(self, **kwargs):
|
||||
obj = self.__class__.__new__(self.__class__)
|
||||
for k in (
|
||||
"model",
|
||||
"dhist",
|
||||
"xhist",
|
||||
"extra_args",
|
||||
"eta",
|
||||
"reta",
|
||||
"s_noise",
|
||||
"sigmas",
|
||||
"denoised",
|
||||
"callback_",
|
||||
"noise_sampler",
|
||||
"idx",
|
||||
"sigma",
|
||||
"sigma_next",
|
||||
"sigma_prev",
|
||||
"sigma_down",
|
||||
"sigma_up",
|
||||
"sigma_down_reversible",
|
||||
"sigma_up_reversible",
|
||||
):
|
||||
for k in self.CLONE_KEYS:
|
||||
setattr(obj, k, kwargs[k] if k in kwargs else getattr(self, k))
|
||||
obj.update()
|
||||
return obj
|
||||
|
||||
def callback(self, x):
|
||||
def callback(self, hi=None, *, preview_mode="denoised"):
|
||||
if not self.callback_:
|
||||
return None
|
||||
return self.callback_(
|
||||
{
|
||||
"x": x,
|
||||
"i": self.idx,
|
||||
"sigma": self.sigma,
|
||||
"sigma_hat": self.sigma,
|
||||
"denoised": self.dhist[-1],
|
||||
}
|
||||
)
|
||||
hi = self.hcur if hi is None else hi
|
||||
if preview_mode == "cond":
|
||||
preview = fallback(hi.denoised_cond, hi.denoised)
|
||||
elif preview_mode == "uncond":
|
||||
preview = fallback(hi.denoised_uncond, hi.denoised)
|
||||
elif preview_mode == "raw":
|
||||
preview = hi.x
|
||||
elif (
|
||||
preview_mode == "diff"
|
||||
and hi.denoised_uncond is not None
|
||||
and hi.denoised_cond is not None
|
||||
):
|
||||
preview = (
|
||||
hi.denoised_uncond * 0.25 + (hi.denoised_uncond - hi.denoised_cond) * 16
|
||||
)
|
||||
elif preview_mode == "noisy":
|
||||
preview = (hi.x - hi.denoised) * 0.1 + hi.denoised
|
||||
else:
|
||||
preview = hi.denoised
|
||||
return self.callback_({
|
||||
"x": hi.x,
|
||||
"i": self.step,
|
||||
"sigma": hi.sigma,
|
||||
"sigma_hat": hi.sigma,
|
||||
"denoised": preview,
|
||||
})
|
||||
|
||||
def reset(self):
|
||||
self.hist.reset()
|
||||
self.denoised = None
|
||||
|
||||
def call_model(self, *args, **kwargs):
|
||||
cfg_scale_override = kwargs.pop("cfg_scale_override", self.cfg_scale_override)
|
||||
return self.model(*args, cfg_scale_override=cfg_scale_override, **kwargs)
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
TORCH_FUNCTION_WHITELIST = frozenset((
|
||||
"abs",
|
||||
"absolute",
|
||||
"acos",
|
||||
"acosh",
|
||||
"add",
|
||||
"addbmm",
|
||||
"addcdiv",
|
||||
"addcmul",
|
||||
"addmm",
|
||||
"addmv",
|
||||
"addr",
|
||||
"adjoint",
|
||||
"all",
|
||||
"allclose",
|
||||
"amax",
|
||||
"amin",
|
||||
"aminmax",
|
||||
"angle",
|
||||
"any",
|
||||
"arccos",
|
||||
"arccosh",
|
||||
"arcsin",
|
||||
"arcsinh",
|
||||
"arctan",
|
||||
"arctan2",
|
||||
"arctanh",
|
||||
"argmax",
|
||||
"argmin",
|
||||
"argsort",
|
||||
"argwhere",
|
||||
"as_strided",
|
||||
"asin",
|
||||
"asinh",
|
||||
"atan",
|
||||
"atan2",
|
||||
"atanh",
|
||||
"baddbmm",
|
||||
"bernoulli",
|
||||
"bincount",
|
||||
"bitwise_and",
|
||||
"bitwise_left_shift",
|
||||
"bitwise_not",
|
||||
"bitwise_or",
|
||||
"bitwise_right_shift",
|
||||
"bitwise_xor",
|
||||
"bmm",
|
||||
"broadcast_to",
|
||||
"ceil",
|
||||
"cholesky",
|
||||
"cholesky_inverse",
|
||||
"cholesky_solve",
|
||||
"chunk",
|
||||
"clamp",
|
||||
"clip",
|
||||
"clone",
|
||||
"conj",
|
||||
"conj_physical",
|
||||
"contiguous",
|
||||
"copysign",
|
||||
"corrcoef",
|
||||
"cos",
|
||||
"cosh",
|
||||
"count_nonzero",
|
||||
"cov",
|
||||
"cross",
|
||||
"cummax",
|
||||
"cummin",
|
||||
"cumprod",
|
||||
"cumsum",
|
||||
"deg2rad",
|
||||
"det",
|
||||
"detach",
|
||||
"diag",
|
||||
"diag_embed",
|
||||
"diagflat",
|
||||
"diagonal",
|
||||
"diagonal_scatter",
|
||||
"diff",
|
||||
"digamma",
|
||||
"dim",
|
||||
"dist",
|
||||
"div",
|
||||
"divide",
|
||||
"dot",
|
||||
"dsplit",
|
||||
"eq",
|
||||
"equal",
|
||||
"erf",
|
||||
"erfc",
|
||||
"erfinv",
|
||||
"exp",
|
||||
"expand",
|
||||
"expand_as",
|
||||
"expm1",
|
||||
"fix",
|
||||
"flatten",
|
||||
"flip",
|
||||
"fliplr",
|
||||
"flipud",
|
||||
"float_power",
|
||||
"floor",
|
||||
"floor_divide",
|
||||
"fmax",
|
||||
"fmin",
|
||||
"fmod",
|
||||
"frac",
|
||||
"frexp",
|
||||
"gather",
|
||||
"gcd",
|
||||
"ge",
|
||||
"geqrf",
|
||||
"ger",
|
||||
"greater",
|
||||
"greater_equal",
|
||||
"gt",
|
||||
"hardshrink",
|
||||
"heaviside",
|
||||
"histc",
|
||||
"hsplit",
|
||||
"hypot",
|
||||
"i0",
|
||||
"igamma",
|
||||
"igammac",
|
||||
"index_add",
|
||||
"index_copy",
|
||||
"index_fill",
|
||||
"index_put",
|
||||
"index_reduce",
|
||||
"index_select",
|
||||
"inner",
|
||||
"inverse",
|
||||
"isclose",
|
||||
"isfinite",
|
||||
"isinf",
|
||||
"isnan",
|
||||
"isneginf",
|
||||
"isposinf",
|
||||
"kthvalue",
|
||||
"lcm()",
|
||||
"ldexp",
|
||||
"le",
|
||||
"lerp",
|
||||
"less",
|
||||
"less_equal",
|
||||
"lgamma",
|
||||
"log",
|
||||
"log10",
|
||||
"log1p",
|
||||
"log2",
|
||||
"logaddexp",
|
||||
"logaddexp2",
|
||||
"logcumsumexp",
|
||||
"logdet",
|
||||
"logical_and",
|
||||
"logical_not",
|
||||
"logical_or",
|
||||
"logical_xor",
|
||||
"logit",
|
||||
"logsumexp",
|
||||
"lt",
|
||||
"lu",
|
||||
"lu_solve",
|
||||
"masked_fill",
|
||||
"masked_scatter",
|
||||
"masked_select",
|
||||
"matmul",
|
||||
"matrix_exp",
|
||||
"max",
|
||||
"maximum",
|
||||
"mean",
|
||||
"median",
|
||||
"min",
|
||||
"minimum",
|
||||
"mm",
|
||||
"mode",
|
||||
"moveaxis",
|
||||
"movedim",
|
||||
"msort",
|
||||
"mul",
|
||||
"multinomial",
|
||||
"multiply",
|
||||
"mv",
|
||||
"mvlgamma",
|
||||
"nan_to_num",
|
||||
"nanmean",
|
||||
"nanmedian",
|
||||
"nanquantile",
|
||||
"nansum",
|
||||
"narrow",
|
||||
"narrow_copy",
|
||||
"ne",
|
||||
"neg",
|
||||
"negative",
|
||||
"new_empty",
|
||||
"new_full",
|
||||
"new_ones",
|
||||
"new_zeros",
|
||||
"nextafter",
|
||||
"nonzero",
|
||||
"norm",
|
||||
"not_equal",
|
||||
"numel",
|
||||
"orgqr",
|
||||
"ormqr",
|
||||
"outer",
|
||||
"permute",
|
||||
"polygamma",
|
||||
"positive",
|
||||
"pow",
|
||||
"prod",
|
||||
"qr",
|
||||
"quantile",
|
||||
"rad2deg",
|
||||
"ravel",
|
||||
"reciprocal",
|
||||
"remainder",
|
||||
"renorm",
|
||||
"repeat",
|
||||
"repeat_interleave",
|
||||
"reshape",
|
||||
"reshape_as",
|
||||
"resolve_conj",
|
||||
"resolve_neg",
|
||||
"roll",
|
||||
"rot90",
|
||||
"round",
|
||||
"rsqrt",
|
||||
"scatter",
|
||||
"scatter_add",
|
||||
"scatter_reduce",
|
||||
"select",
|
||||
"select_scatter",
|
||||
"sgn",
|
||||
"sigmoid",
|
||||
"sign",
|
||||
"signbit",
|
||||
"sin",
|
||||
"sinc",
|
||||
"sinh",
|
||||
"slice_scatter",
|
||||
"slogdet",
|
||||
"smm",
|
||||
"softmax",
|
||||
"sort",
|
||||
"sparse_mask",
|
||||
"split",
|
||||
"sqrt",
|
||||
"square",
|
||||
"squeeze",
|
||||
"sspaddmm",
|
||||
"std",
|
||||
"stft",
|
||||
"sub",
|
||||
"subtract",
|
||||
"sum",
|
||||
"sum_to_size",
|
||||
"svd",
|
||||
"swapaxes",
|
||||
"swapdims",
|
||||
"t",
|
||||
"take",
|
||||
"take_along_dim",
|
||||
"tan",
|
||||
"tanh",
|
||||
"tensor_split",
|
||||
"tile",
|
||||
"topk",
|
||||
"transpose",
|
||||
"triangular_solve",
|
||||
"tril",
|
||||
"triu",
|
||||
"true_divide",
|
||||
"trunc",
|
||||
"unflatten",
|
||||
"unfold",
|
||||
"unique",
|
||||
"unique_consecutive",
|
||||
"unsqueeze",
|
||||
"var",
|
||||
"vdot",
|
||||
"view",
|
||||
"view_as",
|
||||
"vsplit",
|
||||
"where",
|
||||
"xlogy",
|
||||
))
|
||||
+230
-10
@@ -1,17 +1,186 @@
|
||||
import math
|
||||
import contextlib
|
||||
|
||||
import torch
|
||||
|
||||
from comfy.k_diffusion.sampling import to_d
|
||||
|
||||
def scale_noise(noise, factor=1.0, *, normalized=True, threshold_std_devs=2.5):
|
||||
# def scale_noise_(
|
||||
# noise,
|
||||
# factor=1.0,
|
||||
# *,
|
||||
# normalized=True,
|
||||
# normalize_dims=(-3, -2, -1),
|
||||
# ):
|
||||
# if not normalized or noise.numel() == 0:
|
||||
# return noise.mul_(factor) if factor != 1 else noise
|
||||
# mean, std = (
|
||||
# noise.mean(dim=normalize_dims, keepdim=True),
|
||||
# noise.std(dim=normalize_dims, keepdim=True),
|
||||
# )
|
||||
# return latent.normalize_to_scale(
|
||||
# noise.sub_(mean).div_(std).clamp(-1, 1), -1.0, 1.0, dim=normalize_dims
|
||||
# ).mul_(factor)
|
||||
|
||||
|
||||
# def scale_noise(
|
||||
# noise,
|
||||
# factor=1.0,
|
||||
# *,
|
||||
# normalized=True,
|
||||
# normalize_dims=(-3, -2, -1),
|
||||
# ):
|
||||
# if not normalized or noise.numel() == 0:
|
||||
# return noise * factor if factor != 1 else noise
|
||||
# mean, std = (
|
||||
# noise.mean(dim=normalize_dims, keepdim=True),
|
||||
# noise.std(dim=normalize_dims, keepdim=True),
|
||||
# )
|
||||
# return (noise - mean).div_(std).mul_(factor)
|
||||
|
||||
|
||||
def scale_noise(
|
||||
noise,
|
||||
factor=1.0,
|
||||
*,
|
||||
normalized=True,
|
||||
normalize_dims=(-3, -2, -1),
|
||||
):
|
||||
if not normalized or noise.numel() == 0:
|
||||
return noise.mul_(factor) if factor != 1 else noise
|
||||
mean, std = noise.mean().item(), noise.std().item()
|
||||
threshold = threshold_std_devs / math.sqrt(noise.numel())
|
||||
if abs(mean) > threshold:
|
||||
noise -= mean
|
||||
if abs(1.0 - std) > threshold:
|
||||
noise /= std
|
||||
return noise.mul_(factor) if factor != 1 else noise
|
||||
return noise * factor if factor != 1 else noise
|
||||
noise = noise / noise.std(dim=normalize_dims, keepdim=True)
|
||||
return noise.sub_(noise.mean(dim=normalize_dims, keepdim=True)).mul_(factor)
|
||||
|
||||
|
||||
def _quantile_norm_scaledown(
|
||||
noise: torch.Tensor,
|
||||
nq: torch.Tensor,
|
||||
**_kwargs: dict,
|
||||
) -> torch.Tensor:
|
||||
mv = noise.abs().max().detach().item()
|
||||
return noise if mv == 0 else torch.where(noise.abs() > nq, noise * (nq / mv), noise)
|
||||
|
||||
|
||||
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": lambda noise, nq, **_kwargs: noise.sigmoid()
|
||||
.mul_(nq.abs())
|
||||
.copysign(noise),
|
||||
"sigmoid_outliers": lambda noise, nq, **_kwargs: torch.where(
|
||||
noise.abs() > nq,
|
||||
noise.sigmoid().mul_(nq.abs()).copysign(noise),
|
||||
noise,
|
||||
),
|
||||
"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,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
# Initial version based on Studentt distribution normalizatino from https://github.com/Clybius/ComfyUI-Extra-Samplers/
|
||||
def quantile_normalize(
|
||||
noise: torch.Tensor,
|
||||
*,
|
||||
quantile: float = 0.75,
|
||||
dim: int | None = 1,
|
||||
flatten: bool = True,
|
||||
nq_fac: float = 1.0,
|
||||
pow_fac: float = 0.5,
|
||||
strategy: str = "clamp",
|
||||
strategy_handler=None,
|
||||
) -> torch.Tensor:
|
||||
if quantile is None or quantile <= 0 or quantile >= 1:
|
||||
return noise
|
||||
orig_shape = noise.shape
|
||||
if isinstance(quantile, (tuple, list)):
|
||||
quantile = torch.tensor(
|
||||
quantile,
|
||||
device=noise.device,
|
||||
dtype=noise.dtype,
|
||||
)
|
||||
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 -1 < qdim < 2: # 0, 1
|
||||
flatdim = qdim + 1
|
||||
elif 1 < qdim < 4: # 2, 3
|
||||
noise = noise.movedim(qdim, 1)
|
||||
tempshape = noise.shape
|
||||
flatdim = 2
|
||||
else:
|
||||
raise ValueError(
|
||||
"Cannot handling quantile normalization flattening dims > 3",
|
||||
)
|
||||
else:
|
||||
flatdim = None
|
||||
nq = torch.quantile(
|
||||
(noise if flatdim is None else noise.flatten(start_dim=flatdim)).abs(),
|
||||
quantile,
|
||||
dim=-1,
|
||||
)
|
||||
nq_shape = tuple(nq.shape) + (1,) * (noise.ndim - nq.ndim)
|
||||
nq = nq.mul_(nq_fac).reshape(*nq_shape)
|
||||
handler = (
|
||||
quantile_handlers.get(strategy)
|
||||
if strategy_handler is None
|
||||
else strategy_handler
|
||||
)
|
||||
if handler is None:
|
||||
raise ValueError("Unknown strategy")
|
||||
noise = handler(
|
||||
noise,
|
||||
nq,
|
||||
dim=dim,
|
||||
flatten=flatten,
|
||||
)
|
||||
noise = noise.abs().pow(pow_fac).copysign(noise)
|
||||
if flatdim is not None and qdim in {2, 3}:
|
||||
return (
|
||||
noise.reshape(tempshape).movedim(1, qdim).reshape(orig_shape).contiguous()
|
||||
)
|
||||
return noise
|
||||
|
||||
|
||||
# def scale_noise(
|
||||
# noise,
|
||||
# factor=1.0,
|
||||
# *,
|
||||
# normalized=True,
|
||||
# normalize_dims=(-3, -2, -1),
|
||||
# ):
|
||||
# if not normalized or noise.numel() == 0:
|
||||
# return noise.mul_(factor) if factor != 1 else noise
|
||||
# n = (
|
||||
# torch.nn.LayerNorm(noise.shape[1:])
|
||||
# if normalize_dims == (-3, -2, -1)
|
||||
# else torch.nn.InstanceNorm2d(noise.shape[1])
|
||||
# ).to(noise)
|
||||
# return n(noise) * factor
|
||||
# return latent.normalize_to_scale(
|
||||
# n(noise).clamp_(-1, 1), -1, 1, dim=normalize_dims
|
||||
# ).mul_(factor)
|
||||
|
||||
|
||||
def find_first_unsorted(tensor, desc=True):
|
||||
@@ -20,3 +189,54 @@ def find_first_unsorted(tensor, desc=True):
|
||||
fun = torch.gt if desc else torch.lt
|
||||
first_unsorted = fun(tensor[1:], tensor[:-1]).nonzero().flatten()[:1].add_(1)
|
||||
return None if not len(first_unsorted) else first_unsorted.item()
|
||||
|
||||
|
||||
def fallback(val, default, exclude=None):
|
||||
return val if val is not exclude else default
|
||||
|
||||
|
||||
def step_generator(gen, *, get_next, initial=None):
|
||||
next_val = initial
|
||||
with contextlib.suppress(StopIteration):
|
||||
while True:
|
||||
result = gen.send(next_val)
|
||||
next_val = get_next(result)
|
||||
yield result
|
||||
|
||||
|
||||
# From Gaeros. Thanks!
|
||||
def extract_pred(x_before, x_after, sigma_before, sigma_after):
|
||||
if sigma_after == 0:
|
||||
return x_after, torch.zeros_like(x_after)
|
||||
alpha = sigma_after / sigma_before
|
||||
denoised = (x_after - alpha * x_before) / (1 - alpha)
|
||||
return denoised, to_d(x_after, sigma_after, denoised)
|
||||
|
||||
|
||||
def resolve_value(keys, obj):
|
||||
if not len(keys):
|
||||
raise ValueError("Cannot resolve empty key list")
|
||||
result = obj
|
||||
|
||||
class Empty:
|
||||
pass
|
||||
|
||||
for idx, key in enumerate(keys):
|
||||
if not (hasattr(result, "__getattr__") or hasattr(obj, "__getattribute__")):
|
||||
raise ValueError(
|
||||
f"Cannot access key {key}: value does not support attribute access"
|
||||
)
|
||||
result = getattr(result, key, Empty)
|
||||
if result is Empty:
|
||||
raise AttributeError(f"Key {key} from path {'.'.join(keys)} does not exist")
|
||||
|
||||
|
||||
def check_time(time_mode, time_start, time_end, sigma, step, steps):
|
||||
step_pct = step / steps if steps != 0 else 0.0
|
||||
if time_mode == "step":
|
||||
return time_start <= step <= time_end
|
||||
if time_mode == "step_pct":
|
||||
return time_start <= step_pct <= time_end
|
||||
if time_mode == "sigma":
|
||||
return time_start >= sigma >= time_end
|
||||
raise ValueError("Bad time mode")
|
||||
|
||||
Reference in New Issue
Block a user