From 3953d97163e096883a59e73635467827d64d4710 Mon Sep 17 00:00:00 2001 From: Ethanfel Date: Wed, 4 Mar 2026 17:15:07 +0100 Subject: [PATCH] Add detailed README with SVG diagrams and Apache 2.0 license Includes algorithm comparison, node wiring, and parameter guide diagrams. SVGs use tags for GitHub compatibility. Co-Authored-By: Claude Opus 4.6 --- LICENSE | 190 +++++++++++++++++++++++++++++++++++++++++ README.md | 172 +++++++++++++++++++++++++++++++++++++ assets/algorithm.svg | 87 +++++++++++++++++++ assets/banner.svg | 18 ++++ assets/node-wiring.svg | 87 +++++++++++++++++++ assets/parameters.svg | 83 ++++++++++++++++++ 6 files changed, 637 insertions(+) create mode 100644 LICENSE create mode 100644 README.md create mode 100644 assets/algorithm.svg create mode 100644 assets/banner.svg create mode 100644 assets/node-wiring.svg create mode 100644 assets/parameters.svg diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8f98dcd --- /dev/null +++ b/LICENSE @@ -0,0 +1,190 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to the Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by the Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding any notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2025 Hang Yang, Shuwei Shi, Changhao Nan, Jingyi Yu, Lan Xu + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a2e5afa --- /dev/null +++ b/README.md @@ -0,0 +1,172 @@ + + + + SMC-CFG Ctrl — Sliding Mode Control for Classifier-Free Guidance + + +A ComfyUI node implementing **SMC-CFG** (Sliding Mode Control CFG) from the paper: + +> **CFG-Ctrl: A Control-Theoretic Perspective on Classifier-Free Guidance** +> Hang Yang, Shuwei Shi, Changhao Nan, Jingyi Yu, Lan Xu — *CVPR 2026* +> [[Paper]](https://github.com/hanyang-21/CFG-Ctrl) [[Original Code]](https://github.com/hanyang-21/CFG-Ctrl) + +Standard CFG uses a fixed linear gain that becomes unstable at high guidance scales — causing oversaturation, artifacts, and semantic drift. This node replaces that linear controller with a **nonlinear sliding mode controller** that keeps guidance stable at any CFG scale. + +--- + +## How It Works + +The paper reframes CFG as a control problem. Standard CFG is P-control (proportional control with fixed gain). SMC-CFG adds a bounded nonlinear correction that enforces convergence along an exponential sliding surface. + + + + + Algorithm comparison: Standard CFG vs SMC-CFG + + +### The math in brief + +At each denoising step *t*: + +``` +e_t = noise_cond - noise_uncond # guidance error signal +s_t = (e_t - e_{t-1}) + λ · e_{t-1} # sliding surface +u_sw = -K · sign(s_t) # switching control (bounded) +e_corrected = e_t + u_sw # corrected guidance +v_out = v_uncond + w · e_corrected # final guided prediction +``` + +The correction `u_sw` is bounded to `[-K, +K]` per element — this is what prevents the unbounded growth that plagues standard CFG. The sliding surface combines the error derivative with a decayed previous error, creating a feedback loop with Lyapunov-stable convergence. + +--- + +## Installation + +### Manual + +Clone into your ComfyUI `custom_nodes` directory: + +```bash +cd ComfyUI/custom_nodes +git clone https://github.com/ethanfel/ComfyUI-CFG-CTRL.git +``` + +Restart ComfyUI. No additional dependencies required — the node only uses PyTorch (already in ComfyUI). + +--- + +## Usage + + + + + Node wiring diagram + + +1. Add the **SMC-CFG Ctrl** node (found in `sampling/custom_sampling`) +2. Connect your model loader's `MODEL` output to the node's `model` input +3. Connect the node's `MODEL` output to your KSampler's `model` input +4. Set your KSampler's CFG scale — you can push it **higher than usual** thanks to the SMC stabilization + +That's it. The node patches the model's internal CFG function. It works with **KSampler**, **KSampler Advanced**, and any sampler that respects the model's CFG configuration. + +--- + +## Parameters + + + + + Parameter guide + + +### `smc_cfg_lambda` — Sliding Surface Coefficient +**Default: `5.0`** | Range: `0.0 – 50.0` + +Controls the sliding surface equation `s_t = (e_t - e_{t-1}) + λ · e_{t-1}`. Higher values weight the previous error magnitude more heavily, making the controller more aggressive about correcting accumulated guidance drift. + +| Value | Behavior | +|-------|----------| +| `0.0` | Surface uses only error derivative — very gentle | +| `1.0 – 5.0` | Balanced correction (recommended range) | +| `> 10.0` | Aggressive — may over-constrain the generation | + +### `smc_cfg_K` — Switching Gain +**Default: `0.2`** | Range: `0.0 – 5.0` + +Bounds the correction to `[-K, +K]` per tensor element. This is the "safety clamp" that prevents instability. Think of it as how hard the controller can push back. + +| Value | Behavior | +|-------|----------| +| `0.0` | No correction — equivalent to standard CFG | +| `0.1 – 0.3` | Subtle stabilization (recommended) | +| `> 0.5` | Strong correction — may introduce chattering artifacts | + +### `warmup_steps` — No-Guidance Warmup +**Default: `0`** | Range: `0 – 100` + +Number of initial denoising steps where guidance is completely disabled (pure conditional prediction). The model establishes rough composition and structure before the SMC controller begins steering. + +| Value | Behavior | +|-------|----------| +| `0` | SMC-CFG active from the first step | +| `2 – 5` | Lets structure form first — can improve diversity | +| `> 10` | Long warmup — useful for experimentation | + +### Quick Start Settings + +For most models, start with the defaults and only adjust if needed: + +``` +smc_cfg_lambda = 5.0 +smc_cfg_K = 0.2 +warmup_steps = 0 +``` + +These match the paper's recommended values and work well across SD 1.5, SDXL, SD3, FLUX, and Wan models. + +--- + +## Compatibility + +- Works with any model that uses CFG (SD 1.5, SDXL, SD3, FLUX, Wan, etc.) +- Compatible with **KSampler**, **KSampler Advanced**, and custom sampling workflows +- Stacks with `sampler_post_cfg_function` nodes (e.g., RescaleCFG can be used alongside) +- **Note:** Replaces the model's CFG function — only one `sampler_cfg_function` node can be active at a time. If another node also sets a custom CFG function, the last one in the chain wins. + +--- + +## Technical Details + +### How it integrates with ComfyUI + +The node uses `model.clone()` + `set_model_sampler_cfg_function()` — the standard model patching pattern. It intercepts the CFG combination step without modifying model weights, conditioning, or the sampling loop itself. + +### State management + +The SMC algorithm requires memory of the previous step's guidance error (`e_{t-1}`). This state is held in a closure and automatically resets when a new generation starts (detected via sigma schedule discontinuity). + +### Performance + +The correction adds only lightweight tensor operations (`sign`, multiply, add) per denoising step. The overhead is negligible compared to the model forward pass. However, `disable_cfg1_optimization=True` is set to ensure both conditional and unconditional predictions are always computed. + +--- + +## Citation + +If you use this in your work, please cite the original paper: + +```bibtex +@article{yang2025cfg, + title={CFG-Ctrl: A Control-Theoretic Perspective on Classifier-Free Guidance}, + author={Yang, Hang and Shi, Shuwei and Nan, Changhao and Yu, Jingyi and Xu, Lan}, + journal={arXiv preprint arXiv:2505.18727}, + year={2025} +} +``` + +--- + +## License + +This ComfyUI node is released under the [Apache 2.0 License](LICENSE), matching the original CFG-Ctrl repository. diff --git a/assets/algorithm.svg b/assets/algorithm.svg new file mode 100644 index 0000000..acc9acf --- /dev/null +++ b/assets/algorithm.svg @@ -0,0 +1,87 @@ + + + + + + + + + + + Algorithm: Standard CFG vs SMC-CFG + + + + Standard CFG (P-Control) + + + + 1. + Compute conditional prediction + v_cond = model(x_t, t, prompt) + + + 2. + Compute unconditional prediction + v_uncond = model(x_t, t, "") + + + 3. + Guidance error (fixed gain) + e_t = v_cond - v_uncond + + + 4. + Linear combination (can diverge!) + v_out = v_uncond + w * e_t + + + + Problem at high CFG scales: + Unbounded linear gain causes oversaturation, + artifacts, and semantic drift + + + + SMC-CFG (Sliding Mode Control) + + + + 1. + Same: compute v_cond, v_uncond + e_t = v_cond - v_uncond + + + 2. + Compute sliding surface + s_t = (e_t - e_{t-1}) + lambda * e_{t-1} + + + 3. + Nonlinear switching control + u_sw = -K * sign(s_t) + + + 4. + Bounded correction + e_corrected = e_t + u_sw + + + 5. + Stable guided output + v_out = v_uncond + w * e_corrected + + + + Correction bounded to [-K, +K]: + Prevents divergence at any CFG scale. + Lyapunov-stable finite-time convergence. + + + + + + + + + diff --git a/assets/banner.svg b/assets/banner.svg new file mode 100644 index 0000000..0b75bde --- /dev/null +++ b/assets/banner.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + SMC-CFG Ctrl + Sliding Mode Control for Classifier-Free Guidance + ComfyUI Node | Based on CFG-Ctrl (CVPR 2026) + diff --git a/assets/node-wiring.svg b/assets/node-wiring.svg new file mode 100644 index 0000000..dd7c036 --- /dev/null +++ b/assets/node-wiring.svg @@ -0,0 +1,87 @@ + + + + + + + + + + Node Wiring in ComfyUI + + + + + + Load Checkpoint + + + MODEL + + CLIP + + + + + + + + + SMC-CFG Ctrl + + + model + + + + smc_cfg_lambda + 5.0 + + + smc_cfg_K + 0.2 + + + warmup_steps + 0 + + + + MODEL + + + + + + + + + KSampler + + + model + + + + steps + 20 + + + cfg + 7.5 + + + sampler + euler + + + scheduler + normal + + + + + + + Insert the SMC-CFG Ctrl node between your model loader and sampler. Use higher CFG scales than usual. + diff --git a/assets/parameters.svg b/assets/parameters.svg new file mode 100644 index 0000000..471ec36 --- /dev/null +++ b/assets/parameters.svg @@ -0,0 +1,83 @@ + + + + + + + + + + Parameter Guide + + + + smc_cfg_lambda + default: 5.0 + + Sliding surface coefficient. Controls how aggressively the + controller corrects accumulated guidance errors. + + + + + + + 0 + 5.0 (sweet spot) + 50 + + Low: gentle, preserves original CFG behavior + High: aggressive correction, may over-constrain + + + + smc_cfg_K + default: 0.2 + + Switching gain. Bounds the per-element correction + magnitude to [-K, +K]. Think of it as a safety clamp. + + + + + + + 0 + 0.2 + 5.0 + + Low: subtle correction, smooth results + High: strong correction, may cause chattering + + + + warmup_steps + default: 0 + + Initial denoising steps with NO guidance at all. + Pure conditional prediction. Lets the model establish + rough structure before guidance corrects direction. + + + + + + warmup + SMC-CFG active + + Typical: 0-5 steps. Try 2-3 for more diverse compositions. + + + + Recommended CFG Scales + + Model CFG Scale + + + SD 1.5 / SDXL 7.0 - 12.0 + SD3 / SD3.5 7.5 + FLUX.1-dev 2.0 - 3.0 + Wan 2.1/2.2 5.0 + + SMC-CFG lets you push CFG higher than usual +