├── .github └── workflows │ └── publish.yml ├── LICENSE ├── README.md ├── __init__.py ├── comparison_example_workflow.json ├── icon.png ├── model ├── LICENSE.txt ├── NoiseTransformer.py ├── SVDNoiseUnet.py └── __init__.py ├── nodes.py ├── pyproject.toml └── requirements.txt /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Comfy registry 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | paths: 9 | - "pyproject.toml" 10 | 11 | permissions: 12 | issues: write 13 | 14 | jobs: 15 | publish-node: 16 | name: Publish Custom Node to registry 17 | runs-on: ubuntu-latest 18 | if: ${{ github.repository_owner == 'LucipherDev' }} 19 | steps: 20 | - name: Check out code 21 | uses: actions/checkout@v4 22 | - name: Publish Custom Node 23 | uses: Comfy-Org/publish-node-action@v1 24 | with: 25 | ## Add your own personal access token to your Github Repository secrets and reference it here. 26 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} 27 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Sumeth Sathnindu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ComfyUI-Golden-Noise 2 | ComfyUI Custom Node for ["Golden Noise for Diffusion Models: A Learning Framework"](https://arxiv.org/abs/2411.09502). Most of the code for this node is adapted from [here]( https://github.com/xie-lab-ml/Golden-Noise-for-Diffusion-Models). This node refines the initial latent noise in the diffusion process, enhancing both image quality and semantic coherence. 3 | 4 | ## Installation 5 | 6 | 1. Navigate to your ComfyUI's custom_nodes directory: 7 | ```bash 8 | cd ComfyUI/custom_nodes 9 | ``` 10 | 11 | 2. Clone this repository: 12 | ```bash 13 | git clone https://github.com/LucipherDev/ComfyUI-Golden-Noise 14 | ``` 15 | 16 | 3. Install requirements: 17 | ```bash 18 | cd ComfyUI-Golden-Noise 19 | pip install -r requirements.txt 20 | ``` 21 | 22 | ### Or Install via ComfyUI Manager 23 | 24 | ## Usage 25 | 26 | Download the safetensors of the pre-trained NPNet weights of Stable Diffusion XL, DreamShaper-xl-v2-turbo, and Hunyuan-DiT from Huggingface [LucipherDev/Golden-Noise-NPNets](https://huggingface.co/LucipherDev/Golden-Noise-NPNets) and put them in the **models/npnets** folder. 27 | 28 | The node can be found in "sampling/custom_sampling/noise" category as "GoldenNoise". 29 | 30 | Take a look at the example workflow for more info. 31 | 32 | ### Inputs 33 | 34 | - **noise**: Noise output from RandomNoise node 35 | - **conditioning**: Prompt conditioning 36 | - **model_id**: "SDXL", "DreamShaper", "DiT" 37 | - **npnet_model**: Pretrained NPNet model 38 | - **device**: "cuda", "cpu" 39 | 40 | ## Image Comparisons 41 | 42 | ![comparison](https://github.com/user-attachments/assets/1e285c39-b044-43c3-bc5c-2986e387cacb) 43 | **Comparisons from the node* 44 | 45 | This is a small comparison with only 50 images for each prompt, with and without using the golden noise node. The images were generated using the provided workflow (the random noise used to generate the first image is fed into the GoldenNoise node to generate the golden noise), and then each image was scored using [ImageReward](https://github.com/THUDM/ImageReward). The mean scores for with and without the node are shown in the comparison. From this, we can see that when using the node, the overall image quality is increased. However, The sample size is admittedly small, but it's all I can do with the resources and time I have. 46 | 47 | Another comparison. This is taken from the original paper. 48 | ![x1](https://github.com/user-attachments/assets/a031e0c0-8ccc-4c4f-b861-e7e72f7c5a9d) 49 | **Comparisons from the original paper* 50 | 51 | ## Citation 52 | 53 | ```bibtex 54 | @misc{zhou2024goldennoisediffusionmodels, 55 | title={Golden Noise for Diffusion Models: A Learning Framework}, 56 | author={Zikai Zhou and Shitong Shao and Lichen Bai and Zhiqiang Xu and Bo Han and Zeke Xie}, 57 | year={2024}, 58 | eprint={2411.09502}, 59 | archivePrefix={arXiv}, 60 | primaryClass={cs.LG}, 61 | url={https://arxiv.org/abs/2411.09502}, 62 | } 63 | ``` 64 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .nodes import NODE_CLASS_MAPPINGS 2 | 3 | __all__ = ["NODE_CLASS_MAPPINGS"] 4 | -------------------------------------------------------------------------------- /comparison_example_workflow.json: -------------------------------------------------------------------------------- 1 | { 2 | "last_node_id": 21, 3 | "last_link_id": 38, 4 | "nodes": [ 5 | { 6 | "id": 8, 7 | "type": "VAEDecode", 8 | "pos": [ 9 | 1990, 10 | 200 11 | ], 12 | "size": [ 13 | 210, 14 | 46 15 | ], 16 | "flags": {}, 17 | "order": 11, 18 | "mode": 0, 19 | "inputs": [ 20 | { 21 | "name": "samples", 22 | "type": "LATENT", 23 | "link": 31 24 | }, 25 | { 26 | "name": "vae", 27 | "type": "VAE", 28 | "link": 8 29 | } 30 | ], 31 | "outputs": [ 32 | { 33 | "name": "IMAGE", 34 | "type": "IMAGE", 35 | "links": [ 36 | 9 37 | ], 38 | "slot_index": 0 39 | } 40 | ], 41 | "properties": { 42 | "Node name for S&R": "VAEDecode" 43 | }, 44 | "widgets_values": [] 45 | }, 46 | { 47 | "id": 17, 48 | "type": "SamplerCustomAdvanced", 49 | "pos": [ 50 | 1600, 51 | 370 52 | ], 53 | "size": [ 54 | 355.20001220703125, 55 | 326 56 | ], 57 | "flags": {}, 58 | "order": 10, 59 | "mode": 0, 60 | "inputs": [ 61 | { 62 | "name": "noise", 63 | "type": "NOISE", 64 | "link": 37 65 | }, 66 | { 67 | "name": "guider", 68 | "type": "GUIDER", 69 | "link": 26 70 | }, 71 | { 72 | "name": "sampler", 73 | "type": "SAMPLER", 74 | "link": 28 75 | }, 76 | { 77 | "name": "sigmas", 78 | "type": "SIGMAS", 79 | "link": 29 80 | }, 81 | { 82 | "name": "latent_image", 83 | "type": "LATENT", 84 | "link": 27 85 | } 86 | ], 87 | "outputs": [ 88 | { 89 | "name": "output", 90 | "type": "LATENT", 91 | "links": [ 92 | 32 93 | ], 94 | "slot_index": 0 95 | }, 96 | { 97 | "name": "denoised_output", 98 | "type": "LATENT", 99 | "links": null 100 | } 101 | ], 102 | "properties": { 103 | "Node name for S&R": "SamplerCustomAdvanced" 104 | }, 105 | "widgets_values": [] 106 | }, 107 | { 108 | "id": 19, 109 | "type": "VAEDecode", 110 | "pos": [ 111 | 2230, 112 | 200 113 | ], 114 | "size": [ 115 | 210, 116 | 46 117 | ], 118 | "flags": {}, 119 | "order": 12, 120 | "mode": 0, 121 | "inputs": [ 122 | { 123 | "name": "samples", 124 | "type": "LATENT", 125 | "link": 32 126 | }, 127 | { 128 | "name": "vae", 129 | "type": "VAE", 130 | "link": 33 131 | } 132 | ], 133 | "outputs": [ 134 | { 135 | "name": "IMAGE", 136 | "type": "IMAGE", 137 | "links": [ 138 | 34 139 | ], 140 | "slot_index": 0 141 | } 142 | ], 143 | "properties": { 144 | "Node name for S&R": "VAEDecode" 145 | }, 146 | "widgets_values": [] 147 | }, 148 | { 149 | "id": 20, 150 | "type": "SaveImage", 151 | "pos": [ 152 | 2230, 153 | 290 154 | ], 155 | "size": [ 156 | 210, 157 | 270 158 | ], 159 | "flags": {}, 160 | "order": 14, 161 | "mode": 0, 162 | "inputs": [ 163 | { 164 | "name": "images", 165 | "type": "IMAGE", 166 | "link": 34 167 | } 168 | ], 169 | "outputs": [], 170 | "properties": {}, 171 | "widgets_values": [ 172 | "GoldenNoise" 173 | ] 174 | }, 175 | { 176 | "id": 9, 177 | "type": "SaveImage", 178 | "pos": [ 179 | 1990, 180 | 290 181 | ], 182 | "size": [ 183 | 210, 184 | 270 185 | ], 186 | "flags": {}, 187 | "order": 13, 188 | "mode": 0, 189 | "inputs": [ 190 | { 191 | "name": "images", 192 | "type": "IMAGE", 193 | "link": 9 194 | } 195 | ], 196 | "outputs": [], 197 | "properties": {}, 198 | "widgets_values": [ 199 | "RandomNoise" 200 | ] 201 | }, 202 | { 203 | "id": 4, 204 | "type": "CheckpointLoaderSimple", 205 | "pos": [ 206 | 80, 207 | 200 208 | ], 209 | "size": [ 210 | 315, 211 | 98 212 | ], 213 | "flags": {}, 214 | "order": 0, 215 | "mode": 0, 216 | "inputs": [], 217 | "outputs": [ 218 | { 219 | "name": "MODEL", 220 | "type": "MODEL", 221 | "links": [ 222 | 11, 223 | 12 224 | ], 225 | "slot_index": 0 226 | }, 227 | { 228 | "name": "CLIP", 229 | "type": "CLIP", 230 | "links": [ 231 | 3, 232 | 5 233 | ], 234 | "slot_index": 1 235 | }, 236 | { 237 | "name": "VAE", 238 | "type": "VAE", 239 | "links": [ 240 | 8, 241 | 33 242 | ], 243 | "slot_index": 2 244 | } 245 | ], 246 | "properties": { 247 | "Node name for S&R": "CheckpointLoaderSimple" 248 | }, 249 | "widgets_values": [ 250 | "sdXL_v10VAEFix.safetensors" 251 | ] 252 | }, 253 | { 254 | "id": 7, 255 | "type": "CLIPTextEncode", 256 | "pos": [ 257 | 420, 258 | 430 259 | ], 260 | "size": [ 261 | 425.27801513671875, 262 | 180.6060791015625 263 | ], 264 | "flags": {}, 265 | "order": 6, 266 | "mode": 0, 267 | "inputs": [ 268 | { 269 | "name": "clip", 270 | "type": "CLIP", 271 | "link": 5 272 | } 273 | ], 274 | "outputs": [ 275 | { 276 | "name": "CONDITIONING", 277 | "type": "CONDITIONING", 278 | "links": [ 279 | 14 280 | ], 281 | "slot_index": 0 282 | } 283 | ], 284 | "properties": { 285 | "Node name for S&R": "CLIPTextEncode" 286 | }, 287 | "widgets_values": [ 288 | "worst quality, low quality, jpeg artifacts, ugly, duplicate, deformed, blurry" 289 | ] 290 | }, 291 | { 292 | "id": 13, 293 | "type": "KSamplerSelect", 294 | "pos": [ 295 | 870, 296 | 640 297 | ], 298 | "size": [ 299 | 315, 300 | 58 301 | ], 302 | "flags": {}, 303 | "order": 1, 304 | "mode": 0, 305 | "inputs": [], 306 | "outputs": [ 307 | { 308 | "name": "SAMPLER", 309 | "type": "SAMPLER", 310 | "links": [ 311 | 20, 312 | 28 313 | ], 314 | "slot_index": 0 315 | } 316 | ], 317 | "properties": { 318 | "Node name for S&R": "KSamplerSelect" 319 | }, 320 | "widgets_values": [ 321 | "dpmpp_2s_ancestral" 322 | ] 323 | }, 324 | { 325 | "id": 12, 326 | "type": "BasicScheduler", 327 | "pos": [ 328 | 870, 329 | 200 330 | ], 331 | "size": [ 332 | 315, 333 | 106 334 | ], 335 | "flags": {}, 336 | "order": 4, 337 | "mode": 0, 338 | "inputs": [ 339 | { 340 | "name": "model", 341 | "type": "MODEL", 342 | "link": 11 343 | } 344 | ], 345 | "outputs": [ 346 | { 347 | "name": "SIGMAS", 348 | "type": "SIGMAS", 349 | "links": [ 350 | 16, 351 | 29 352 | ], 353 | "slot_index": 0 354 | } 355 | ], 356 | "properties": { 357 | "Node name for S&R": "BasicScheduler" 358 | }, 359 | "widgets_values": [ 360 | "karras", 361 | 70, 362 | 1 363 | ] 364 | }, 365 | { 366 | "id": 14, 367 | "type": "CFGGuider", 368 | "pos": [ 369 | 870, 370 | 350 371 | ], 372 | "size": [ 373 | 315, 374 | 98 375 | ], 376 | "flags": {}, 377 | "order": 8, 378 | "mode": 0, 379 | "inputs": [ 380 | { 381 | "name": "model", 382 | "type": "MODEL", 383 | "link": 12 384 | }, 385 | { 386 | "name": "positive", 387 | "type": "CONDITIONING", 388 | "link": 13 389 | }, 390 | { 391 | "name": "negative", 392 | "type": "CONDITIONING", 393 | "link": 14 394 | } 395 | ], 396 | "outputs": [ 397 | { 398 | "name": "GUIDER", 399 | "type": "GUIDER", 400 | "links": [ 401 | 25, 402 | 26 403 | ], 404 | "slot_index": 0 405 | } 406 | ], 407 | "properties": { 408 | "Node name for S&R": "CFGGuider" 409 | }, 410 | "widgets_values": [ 411 | 7.5 412 | ] 413 | }, 414 | { 415 | "id": 21, 416 | "type": "GoldenNoise", 417 | "pos": [ 418 | 1600, 419 | 200 420 | ], 421 | "size": [ 422 | 315, 423 | 126 424 | ], 425 | "flags": {}, 426 | "order": 7, 427 | "mode": 0, 428 | "inputs": [ 429 | { 430 | "name": "noise", 431 | "type": "NOISE", 432 | "link": 36 433 | }, 434 | { 435 | "name": "conditioning", 436 | "type": "CONDITIONING", 437 | "link": 38 438 | } 439 | ], 440 | "outputs": [ 441 | { 442 | "name": "NOISE", 443 | "type": "NOISE", 444 | "links": [ 445 | 37 446 | ], 447 | "slot_index": 0 448 | } 449 | ], 450 | "properties": { 451 | "Node name for S&R": "GoldenNoise" 452 | }, 453 | "widgets_values": [ 454 | "SDXL", 455 | "sdxl.safetensors", 456 | "cuda" 457 | ] 458 | }, 459 | { 460 | "id": 5, 461 | "type": "EmptyLatentImage", 462 | "pos": [ 463 | 870, 464 | 490 465 | ], 466 | "size": [ 467 | 315, 468 | 106 469 | ], 470 | "flags": {}, 471 | "order": 2, 472 | "mode": 0, 473 | "inputs": [], 474 | "outputs": [ 475 | { 476 | "name": "LATENT", 477 | "type": "LATENT", 478 | "links": [ 479 | 21, 480 | 27 481 | ], 482 | "slot_index": 0 483 | } 484 | ], 485 | "properties": { 486 | "Node name for S&R": "EmptyLatentImage" 487 | }, 488 | "widgets_values": [ 489 | 1024, 490 | 1024, 491 | 1 492 | ] 493 | }, 494 | { 495 | "id": 15, 496 | "type": "RandomNoise", 497 | "pos": [ 498 | 1210, 499 | 200 500 | ], 501 | "size": [ 502 | 315, 503 | 82 504 | ], 505 | "flags": {}, 506 | "order": 3, 507 | "mode": 0, 508 | "inputs": [], 509 | "outputs": [ 510 | { 511 | "name": "NOISE", 512 | "type": "NOISE", 513 | "links": [ 514 | 23, 515 | 36 516 | ], 517 | "slot_index": 0 518 | } 519 | ], 520 | "properties": { 521 | "Node name for S&R": "RandomNoise" 522 | }, 523 | "widgets_values": [ 524 | 0, 525 | "randomize" 526 | ] 527 | }, 528 | { 529 | "id": 6, 530 | "type": "CLIPTextEncode", 531 | "pos": [ 532 | 420, 533 | 200 534 | ], 535 | "size": [ 536 | 422.84503173828125, 537 | 164.31304931640625 538 | ], 539 | "flags": {}, 540 | "order": 5, 541 | "mode": 0, 542 | "inputs": [ 543 | { 544 | "name": "clip", 545 | "type": "CLIP", 546 | "link": 3 547 | } 548 | ], 549 | "outputs": [ 550 | { 551 | "name": "CONDITIONING", 552 | "type": "CONDITIONING", 553 | "links": [ 554 | 13, 555 | 38 556 | ], 557 | "slot_index": 0 558 | } 559 | ], 560 | "properties": { 561 | "Node name for S&R": "CLIPTextEncode" 562 | }, 563 | "widgets_values": [ 564 | "A banana on the left of an apple." 565 | ] 566 | }, 567 | { 568 | "id": 16, 569 | "type": "SamplerCustomAdvanced", 570 | "pos": [ 571 | 1210, 572 | 370 573 | ], 574 | "size": [ 575 | 355.20001220703125, 576 | 326 577 | ], 578 | "flags": {}, 579 | "order": 9, 580 | "mode": 0, 581 | "inputs": [ 582 | { 583 | "name": "noise", 584 | "type": "NOISE", 585 | "link": 23 586 | }, 587 | { 588 | "name": "guider", 589 | "type": "GUIDER", 590 | "link": 25 591 | }, 592 | { 593 | "name": "sampler", 594 | "type": "SAMPLER", 595 | "link": 20 596 | }, 597 | { 598 | "name": "sigmas", 599 | "type": "SIGMAS", 600 | "link": 16 601 | }, 602 | { 603 | "name": "latent_image", 604 | "type": "LATENT", 605 | "link": 21 606 | } 607 | ], 608 | "outputs": [ 609 | { 610 | "name": "output", 611 | "type": "LATENT", 612 | "links": [ 613 | 31 614 | ], 615 | "slot_index": 0 616 | }, 617 | { 618 | "name": "denoised_output", 619 | "type": "LATENT", 620 | "links": null 621 | } 622 | ], 623 | "properties": { 624 | "Node name for S&R": "SamplerCustomAdvanced" 625 | }, 626 | "widgets_values": [] 627 | } 628 | ], 629 | "links": [ 630 | [ 631 | 3, 632 | 4, 633 | 1, 634 | 6, 635 | 0, 636 | "CLIP" 637 | ], 638 | [ 639 | 5, 640 | 4, 641 | 1, 642 | 7, 643 | 0, 644 | "CLIP" 645 | ], 646 | [ 647 | 8, 648 | 4, 649 | 2, 650 | 8, 651 | 1, 652 | "VAE" 653 | ], 654 | [ 655 | 9, 656 | 8, 657 | 0, 658 | 9, 659 | 0, 660 | "IMAGE" 661 | ], 662 | [ 663 | 11, 664 | 4, 665 | 0, 666 | 12, 667 | 0, 668 | "MODEL" 669 | ], 670 | [ 671 | 12, 672 | 4, 673 | 0, 674 | 14, 675 | 0, 676 | "MODEL" 677 | ], 678 | [ 679 | 13, 680 | 6, 681 | 0, 682 | 14, 683 | 1, 684 | "CONDITIONING" 685 | ], 686 | [ 687 | 14, 688 | 7, 689 | 0, 690 | 14, 691 | 2, 692 | "CONDITIONING" 693 | ], 694 | [ 695 | 16, 696 | 12, 697 | 0, 698 | 16, 699 | 3, 700 | "SIGMAS" 701 | ], 702 | [ 703 | 20, 704 | 13, 705 | 0, 706 | 16, 707 | 2, 708 | "SAMPLER" 709 | ], 710 | [ 711 | 21, 712 | 5, 713 | 0, 714 | 16, 715 | 4, 716 | "LATENT" 717 | ], 718 | [ 719 | 23, 720 | 15, 721 | 0, 722 | 16, 723 | 0, 724 | "NOISE" 725 | ], 726 | [ 727 | 25, 728 | 14, 729 | 0, 730 | 16, 731 | 1, 732 | "GUIDER" 733 | ], 734 | [ 735 | 26, 736 | 14, 737 | 0, 738 | 17, 739 | 1, 740 | "GUIDER" 741 | ], 742 | [ 743 | 27, 744 | 5, 745 | 0, 746 | 17, 747 | 4, 748 | "LATENT" 749 | ], 750 | [ 751 | 28, 752 | 13, 753 | 0, 754 | 17, 755 | 2, 756 | "SAMPLER" 757 | ], 758 | [ 759 | 29, 760 | 12, 761 | 0, 762 | 17, 763 | 3, 764 | "SIGMAS" 765 | ], 766 | [ 767 | 31, 768 | 16, 769 | 0, 770 | 8, 771 | 0, 772 | "LATENT" 773 | ], 774 | [ 775 | 32, 776 | 17, 777 | 0, 778 | 19, 779 | 0, 780 | "LATENT" 781 | ], 782 | [ 783 | 33, 784 | 4, 785 | 2, 786 | 19, 787 | 1, 788 | "VAE" 789 | ], 790 | [ 791 | 34, 792 | 19, 793 | 0, 794 | 20, 795 | 0, 796 | "IMAGE" 797 | ], 798 | [ 799 | 36, 800 | 15, 801 | 0, 802 | 21, 803 | 0, 804 | "NOISE" 805 | ], 806 | [ 807 | 37, 808 | 21, 809 | 0, 810 | 17, 811 | 0, 812 | "NOISE" 813 | ], 814 | [ 815 | 38, 816 | 6, 817 | 0, 818 | 21, 819 | 1, 820 | "CONDITIONING" 821 | ] 822 | ], 823 | "groups": [], 824 | "config": {}, 825 | "extra": { 826 | "ds": { 827 | "scale": 0.5131581182307071, 828 | "offset": { 829 | "0": -13.676889419555664, 830 | "1": 262.6046142578125 831 | } 832 | } 833 | }, 834 | "version": 0.4 835 | } 836 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucipherDev/ComfyUI-Golden-Noise/05247db9a10caf346080daf928caf5f4430336b1/icon.png -------------------------------------------------------------------------------- /model/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /model/NoiseTransformer.py: -------------------------------------------------------------------------------- 1 | import torch.nn as nn 2 | 3 | from torch.nn import functional as F 4 | from timm import create_model 5 | 6 | 7 | __all__ = ['NoiseTransformer'] 8 | 9 | class NoiseTransformer(nn.Module): 10 | def __init__(self, resolution=128): 11 | super().__init__() 12 | self.upsample = lambda x: F.interpolate(x, [224,224]) 13 | self.downsample = lambda x: F.interpolate(x, [resolution,resolution]) 14 | self.upconv = nn.Conv2d(7,4,(1,1),(1,1),(0,0)) 15 | self.downconv = nn.Conv2d(4,3,(1,1),(1,1),(0,0)) 16 | # self.upconv = nn.Conv2d(7,4,(1,1),(1,1),(0,0)) 17 | self.swin = create_model("swin_tiny_patch4_window7_224",pretrained=True) 18 | 19 | 20 | def forward(self, x, residual=False): 21 | if residual: 22 | x = self.upconv(self.downsample(self.swin.forward_features(self.downconv(self.upsample(x))))) + x 23 | else: 24 | x = self.upconv(self.downsample(self.swin.forward_features(self.downconv(self.upsample(x))))) 25 | 26 | return x -------------------------------------------------------------------------------- /model/SVDNoiseUnet.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import einops 4 | 5 | from torch.nn import functional as F 6 | from torch.jit import Final 7 | from timm.layers import use_fused_attn 8 | from timm.models.layers import PatchEmbed, Mlp, DropPath, trunc_normal_, lecun_normal_, get_act_layer 9 | 10 | __all__ = ['SVDNoiseUnet', 'SVDNoiseUnet_Concise'] 11 | 12 | class Attention(nn.Module): 13 | fused_attn: Final[bool] 14 | 15 | def __init__( 16 | self, 17 | dim: int, 18 | num_heads: int = 8, 19 | qkv_bias: bool = False, 20 | qk_norm: bool = False, 21 | attn_drop: float = 0., 22 | proj_drop: float = 0., 23 | norm_layer: nn.Module = nn.LayerNorm, 24 | ) -> None: 25 | super().__init__() 26 | assert dim % num_heads == 0, 'dim should be divisible by num_heads' 27 | self.num_heads = num_heads 28 | self.head_dim = dim // num_heads 29 | self.scale = self.head_dim ** -0.5 30 | self.fused_attn = use_fused_attn() 31 | 32 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 33 | self.q_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() 34 | self.k_norm = norm_layer(self.head_dim) if qk_norm else nn.Identity() 35 | self.attn_drop = nn.Dropout(attn_drop) 36 | self.proj = nn.Linear(dim, dim) 37 | self.proj_drop = nn.Dropout(proj_drop) 38 | 39 | def forward(self, x: torch.Tensor) -> torch.Tensor: 40 | B, N, C = x.shape 41 | qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4) 42 | q, k, v = qkv.unbind(0) 43 | q, k = self.q_norm(q), self.k_norm(k) 44 | 45 | if self.fused_attn: 46 | x = F.scaled_dot_product_attention( 47 | q, k, v, 48 | dropout_p=self.attn_drop.p if self.training else 0., 49 | ) 50 | else: 51 | q = q * self.scale 52 | attn = q @ k.transpose(-2, -1) 53 | attn = attn.softmax(dim=-1) 54 | attn = self.attn_drop(attn) 55 | x = attn @ v 56 | 57 | x = x.transpose(1, 2).reshape(B, N, C) 58 | x = self.proj(x) 59 | x = self.proj_drop(x) 60 | return x 61 | 62 | 63 | class SVDNoiseUnet(nn.Module): 64 | def __init__(self, in_channels=4, out_channels=4, resolution=128): # resolution = size // 8 65 | super(SVDNoiseUnet, self).__init__() 66 | 67 | _in = int(resolution * in_channels // 2) 68 | _out = int(resolution * out_channels // 2) 69 | self.mlp1 = nn.Sequential( 70 | nn.Linear(_in, 64), 71 | nn.ReLU(inplace=True), 72 | nn.Linear(64, _out), 73 | ) 74 | self.mlp2 = nn.Sequential( 75 | nn.Linear(_in, 64), 76 | nn.ReLU(inplace=True), 77 | nn.Linear(64, _out), 78 | ) 79 | 80 | self.mlp3 = nn.Sequential( 81 | nn.Linear(_in, _out), 82 | ) 83 | 84 | self.attention = Attention(_out) 85 | 86 | self.bn = nn.BatchNorm2d(_out) 87 | 88 | self.mlp4 = nn.Sequential( 89 | nn.Linear(_out, 1024), 90 | nn.ReLU(inplace=True), 91 | nn.Linear(1024, _out), 92 | ) 93 | 94 | def forward(self, x, residual=False): 95 | b, c, h, w = x.shape 96 | x = einops.rearrange(x, "b (a c)h w ->b (a h)(c w)", a=2,c=2) # x -> [1, 256, 256] 97 | U, s, V = torch.linalg.svd(x) # U->[b 256 256], s-> [b 256], V->[b 256 256] 98 | U_T = U.permute(0, 2, 1) 99 | out = self.mlp1(U_T) + self.mlp2(V) + self.mlp3(s).unsqueeze(1) # s -> [b, 1, 256] => [b, 256, 256] 100 | out = self.attention(out).mean(1) 101 | out = self.mlp4(out) + s 102 | pred = U @ torch.diag_embed(out) @ V 103 | return einops.rearrange(pred, "b (a h)(c w) -> b (a c) h w", a=2,c=2) 104 | 105 | 106 | class SVDNoiseUnet_Concise(nn.Module): 107 | def __init__(self, in_channels=4, out_channels=4, resolution=128): 108 | super(SVDNoiseUnet_Concise, self).__init__() 109 | 110 | -------------------------------------------------------------------------------- /model/__init__.py: -------------------------------------------------------------------------------- 1 | from .NoiseTransformer import NoiseTransformer 2 | from .SVDNoiseUnet import SVDNoiseUnet 3 | 4 | # Code from https://github.com/xie-lab-ml/Golden-Noise-for-Diffusion-Models -------------------------------------------------------------------------------- /nodes.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import os 3 | from diffusers.models.normalization import AdaGroupNorm 4 | import safetensors.torch 5 | 6 | import folder_paths 7 | 8 | from comfy.utils import common_upscale 9 | 10 | from .model import NoiseTransformer, SVDNoiseUnet 11 | 12 | MODELS_DIR = os.path.join(folder_paths.models_dir, "npnets") 13 | if "npnets" not in folder_paths.folder_names_and_paths: 14 | current_paths = [MODELS_DIR] 15 | else: 16 | current_paths, _ = folder_paths.folder_names_and_paths["npnets"] 17 | folder_paths.folder_names_and_paths["npnets"] = (current_paths, folder_paths.supported_pt_extensions) 18 | 19 | class Noise_GoldenNoise: 20 | def __init__(self, model, noise, cond): 21 | self.model = model 22 | self.noise = noise 23 | self.cond = cond 24 | self.seed = self.noise.seed 25 | 26 | def generate_noise(self, input_latent): 27 | og_shape = input_latent["samples"].shape 28 | rescale = og_shape[-1] != 128 or og_shape[-2] != 128 29 | 30 | if rescale: 31 | input_latent = input_latent.copy() 32 | input_latent["samples"] = common_upscale(input_latent["samples"], 128, 128, "nearest-exact", "disabled") 33 | 34 | initial_noise = self.noise.generate_noise(input_latent).to(self.model["device"]) 35 | cond = self.cond[0].clone().to(self.model["device"]) 36 | 37 | try: 38 | for _, cond in enumerate(torch.split(cond, 77, 1)): 39 | cond = cond.float().view(cond.shape[0], -1) 40 | text_emb = self.model["text_embedding"](initial_noise.float(), cond) 41 | 42 | encoder_hidden_states_svd = initial_noise 43 | encoder_hidden_states_embedding = initial_noise + text_emb 44 | 45 | golden_embedding = self.model["unet_embedding"](encoder_hidden_states_embedding.float()) 46 | 47 | initial_noise = ( 48 | self.model["unet_svd"](encoder_hidden_states_svd.float()) 49 | + (2 * torch.sigmoid(self.model["_alpha"]) - 1) * text_emb 50 | + self.model["_beta"] * golden_embedding 51 | ) 52 | 53 | golden_noise = initial_noise 54 | golden_noise.to("cpu") 55 | 56 | if rescale: 57 | golden_noise = common_upscale(golden_noise, og_shape[-1], og_shape[-2], "nearest-exact", "disabled") 58 | 59 | except Exception as e: 60 | print("Noise could not be turned golden:", e) 61 | return initial_noise 62 | 63 | return golden_noise 64 | 65 | class GoldenNoise: 66 | @classmethod 67 | def INPUT_TYPES(cls): 68 | return { 69 | "required": { 70 | "noise": ("NOISE",), 71 | "conditioning": ("CONDITIONING",), 72 | "model_id": (["SDXL", "DreamShaper", "DiT"],), 73 | "npnet_model": (folder_paths.get_filename_list("npnets"),), 74 | "device": (["cuda", "cpu"],), 75 | }, 76 | } 77 | 78 | RETURN_TYPES = ("NOISE",) 79 | OUTPUT_TOOLTIPS = ("The golden noise",) 80 | 81 | CATEGORY = "sampling/custom_sampling/noise" 82 | FUNCTION = "get_noise" 83 | DESCRIPTION = "Turn noise into golden noise." 84 | 85 | def __init__(self): 86 | self.models = {} 87 | 88 | def load_model(self, model_id, npnet_model_path, device="cuda"): 89 | if model_id not in self.models: 90 | unet_embedding = NoiseTransformer(resolution=128).to(device, torch.float32) 91 | unet_svd = SVDNoiseUnet(resolution=128).to(device, torch.float32) 92 | 93 | if model_id == 'DiT': 94 | text_embedding = AdaGroupNorm(1024 * 77, 4, 1, eps=1e-6).to(device, torch.float32) 95 | else: 96 | text_embedding = AdaGroupNorm(2048 * 77, 4, 1, eps=1e-6).to(device, torch.float32) 97 | 98 | is_pth = ".pth" in npnet_model_path 99 | 100 | if is_pth: 101 | gloden_unet = torch.load(npnet_model_path, weights_only=True, map_location=device) 102 | else: 103 | gloden_unet = safetensors.torch.load_file(npnet_model_path, device=device) 104 | 105 | unet_svd.load_state_dict(gloden_unet["unet_svd"] if is_pth else {k.replace("unet_svd.", ""): v for k, v in gloden_unet.items() if k.startswith("unet_svd.")}) 106 | unet_embedding.load_state_dict(gloden_unet["unet_embedding"] if is_pth else {k.replace("unet_embedding.", ""): v for k, v in gloden_unet.items() if k.startswith("unet_embedding.")}) 107 | text_embedding.load_state_dict(gloden_unet["embeeding"] if is_pth else {k.replace("embeeding.", ""): v for k, v in gloden_unet.items() if k.startswith("embeeding.")}) 108 | _alpha = gloden_unet["alpha"] 109 | _beta = gloden_unet["beta"] 110 | 111 | self.models[model_id] = { 112 | "unet_svd": unet_svd, 113 | "unet_embedding": unet_embedding, 114 | "text_embedding": text_embedding, 115 | "_alpha": _alpha, 116 | "_beta": _beta, 117 | "device": device 118 | } 119 | 120 | return self.models[model_id] 121 | 122 | def get_noise(self, noise, conditioning, model_id, npnet_model, device): 123 | npnet_model_path = folder_paths.get_full_path("npnets", npnet_model) 124 | 125 | model = self.load_model(model_id, npnet_model_path, device) 126 | cond = conditioning[0] 127 | 128 | return (Noise_GoldenNoise(model, noise, cond),) 129 | 130 | NODE_CLASS_MAPPINGS = { 131 | "GoldenNoise": GoldenNoise, 132 | } 133 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "comfyui-golden-noise" 3 | description = "ComfyUI Custom Node for 'Golden-Noise-for-Diffusion-Models'. This node refines the initial latent noise in the diffusion process, enhancing both image quality and semantic coherence." 4 | version = "1.0.0" 5 | license = {file = "LICENSE"} 6 | dependencies = ["timm", "einops"] 7 | 8 | [project.urls] 9 | Repository = "https://github.com/LucipherDev/ComfyUI-Golden-Noise" 10 | # Used by Comfy Registry https://comfyregistry.org 11 | 12 | [tool.comfy] 13 | PublisherId = "lucipherdev" 14 | DisplayName = "ComfyUI-Golden-Noise" 15 | Icon = "https://raw.githubusercontent.com/LucipherDev/ComfyUI-Golden-Noise/refs/heads/main/icon.png" 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | timm 2 | einops --------------------------------------------------------------------------------